blob: 38069a56ac7a6a0b7640cd7940a681efe82890b0 [file] [log] [blame]
Ted Kremenek61f3e052008-04-03 04:42:52 +00001// BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines BugReporter, a utility class for generating
Ted Kremenek6c07bdb2009-06-26 00:05:51 +000011// PathDiagnostics.
Ted Kremenek61f3e052008-04-03 04:42:52 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek9b663712011-02-10 01:03:03 +000015#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerc35fb7d2012-01-28 12:06:22 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000018#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000019#include "clang/AST/ParentMap.h"
Chris Lattner16f00492009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "clang/Analysis/CFG.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000022#include "clang/Analysis/ProgramPoint.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Basic/SourceManager.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000025#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
Ted Kremenek331b0ac2008-06-18 05:34:07 +000027#include "llvm/ADT/DenseMap.h"
Ted Kremenek802e0242012-02-08 04:32:34 +000028#include "llvm/ADT/IntrusiveRefCntPtr.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000029#include "llvm/ADT/OwningPtr.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/Support/raw_ostream.h"
Ted Kremenek10aa5542009-03-12 23:41:59 +000033#include <queue>
Ted Kremenek61f3e052008-04-03 04:42:52 +000034
35using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000036using namespace ento;
Ted Kremenek61f3e052008-04-03 04:42:52 +000037
Ted Kremenek8966bc12009-05-06 21:39:49 +000038BugReporterVisitor::~BugReporterVisitor() {}
Ted Kremenek1b431022010-03-20 18:01:57 +000039
David Blaikie99ba9e32011-12-20 02:48:34 +000040void BugReporterContext::anchor() {}
41
Ted Kremenekcf118d42009-02-04 23:49:09 +000042//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000043// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000044//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000045
Ted Kremenek9c378f72011-08-12 23:37:29 +000046static inline const Stmt *GetStmt(const ProgramPoint &P) {
Ted Kremenek592362b2009-08-18 01:05:30 +000047 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
48 return SP->getStmt();
Ted Kremenek9c378f72011-08-12 23:37:29 +000049 else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000050 return BE->getSrc()->getTerminator();
Jordan Rose852aa0d2012-07-10 22:07:52 +000051 else if (const CallEnter *CE = dyn_cast<CallEnter>(&P))
52 return CE->getCallExpr();
53 else if (const CallExitEnd *CEE = dyn_cast<CallExitEnd>(&P))
54 return CEE->getCalleeContext()->getCallSite();
Mike Stump1eb44332009-09-09 15:08:12 +000055
Ted Kremenekb697b102009-02-23 22:44:26 +000056 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000057}
58
Zhongxing Xuc5619d92009-08-06 01:32:16 +000059static inline const ExplodedNode*
Ted Kremenek9c378f72011-08-12 23:37:29 +000060GetPredecessorNode(const ExplodedNode *N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000061 return N->pred_empty() ? NULL : *(N->pred_begin());
62}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000063
Zhongxing Xuc5619d92009-08-06 01:32:16 +000064static inline const ExplodedNode*
Ted Kremenek9c378f72011-08-12 23:37:29 +000065GetSuccessorNode(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000066 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000067}
68
Ted Kremenek9c378f72011-08-12 23:37:29 +000069static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000070 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000071 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000072 return S;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Ted Kremenekb697b102009-02-23 22:44:26 +000074 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000075}
76
Ted Kremenek9c378f72011-08-12 23:37:29 +000077static const Stmt *GetNextStmt(const ExplodedNode *N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000078 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000079 if (const Stmt *S = GetStmt(N->getLocation())) {
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000080 // Check if the statement is '?' or '&&'/'||'. These are "merges",
81 // not actual statement points.
82 switch (S->getStmtClass()) {
83 case Stmt::ChooseExprClass:
John McCall56ca35d2011-02-17 10:25:35 +000084 case Stmt::BinaryConditionalOperatorClass: continue;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000085 case Stmt::ConditionalOperatorClass: continue;
86 case Stmt::BinaryOperatorClass: {
John McCall2de56d12010-08-25 11:45:40 +000087 BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
88 if (Op == BO_LAnd || Op == BO_LOr)
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000089 continue;
90 break;
91 }
92 default:
93 break;
94 }
Ted Kremenekb697b102009-02-23 22:44:26 +000095 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000096 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Ted Kremenekb697b102009-02-23 22:44:26 +000098 return 0;
99}
100
Ted Kremenek5f85e172009-07-22 22:35:28 +0000101static inline const Stmt*
Ted Kremenek9c378f72011-08-12 23:37:29 +0000102GetCurrentOrPreviousStmt(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000103 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000104 return S;
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Ted Kremenekb697b102009-02-23 22:44:26 +0000106 return GetPreviousStmt(N);
107}
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Ted Kremenek5f85e172009-07-22 22:35:28 +0000109static inline const Stmt*
Ted Kremenek9c378f72011-08-12 23:37:29 +0000110GetCurrentOrNextStmt(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000111 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000112 return S;
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Ted Kremenekb697b102009-02-23 22:44:26 +0000114 return GetNextStmt(N);
115}
116
117//===----------------------------------------------------------------------===//
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000118// Diagnostic cleanup.
119//===----------------------------------------------------------------------===//
120
Ted Kremenekb85cce02012-10-25 22:07:10 +0000121static PathDiagnosticEventPiece *
122eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
123 PathDiagnosticEventPiece *Y) {
124 // Prefer diagnostics that come from ConditionBRVisitor over
125 // those that came from TrackConstraintBRVisitor.
126 const void *tagPreferred = ConditionBRVisitor::getTag();
127 const void *tagLesser = TrackConstraintBRVisitor::getTag();
128
129 if (X->getLocation() != Y->getLocation())
130 return 0;
131
132 if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
133 return X;
134
135 if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
136 return Y;
137
138 return 0;
139}
140
Ted Kremenek38001652012-10-26 16:02:36 +0000141/// An optimization pass over PathPieces that removes redundant diagnostics
142/// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
143/// BugReporterVisitors use different methods to generate diagnostics, with
144/// one capable of emitting diagnostics in some cases but not in others. This
145/// can lead to redundant diagnostic pieces at the same point in a path.
146static void removeRedundantMsgs(PathPieces &path) {
Ted Kremenekb85cce02012-10-25 22:07:10 +0000147 unsigned N = path.size();
148 if (N < 2)
149 return;
Ted Kremenek38001652012-10-26 16:02:36 +0000150 // NOTE: this loop intentionally is not using an iterator. Instead, we
151 // are streaming the path and modifying it in place. This is done by
152 // grabbing the front, processing it, and if we decide to keep it append
153 // it to the end of the path. The entire path is processed in this way.
Ted Kremenekb85cce02012-10-25 22:07:10 +0000154 for (unsigned i = 0; i < N; ++i) {
155 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
156 path.pop_front();
157
158 switch (piece->getKind()) {
159 case clang::ento::PathDiagnosticPiece::Call:
Ted Kremenek38001652012-10-26 16:02:36 +0000160 removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000161 break;
162 case clang::ento::PathDiagnosticPiece::Macro:
Ted Kremenek38001652012-10-26 16:02:36 +0000163 removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
Ted Kremenekb85cce02012-10-25 22:07:10 +0000164 break;
165 case clang::ento::PathDiagnosticPiece::ControlFlow:
166 break;
167 case clang::ento::PathDiagnosticPiece::Event: {
168 if (i == N-1)
169 break;
170
171 if (PathDiagnosticEventPiece *nextEvent =
172 dyn_cast<PathDiagnosticEventPiece>(path.front().getPtr())) {
173 PathDiagnosticEventPiece *event =
174 cast<PathDiagnosticEventPiece>(piece);
175 // Check to see if we should keep one of the two pieces. If we
176 // come up with a preference, record which piece to keep, and consume
177 // another piece from the path.
178 if (PathDiagnosticEventPiece *pieceToKeep =
179 eventsDescribeSameCondition(event, nextEvent)) {
180 piece = pieceToKeep;
181 path.pop_front();
182 ++i;
183 }
184 }
185 break;
186 }
187 }
188 path.push_back(piece);
189 }
190}
191
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000192/// Recursively scan through a path and prune out calls and macros pieces
193/// that aren't needed. Return true if afterwards the path contains
Jordan Roseafa7cae2012-12-07 19:56:29 +0000194/// "interesting stuff" which means it shouldn't be pruned from the parent path.
195bool BugReporter::RemoveUnneededCalls(PathPieces &pieces, BugReport *R) {
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000196 bool containsSomethingInteresting = false;
197 const unsigned N = pieces.size();
198
199 for (unsigned i = 0 ; i < N ; ++i) {
200 // Remove the front piece from the path. If it is still something we
201 // want to keep once we are done, we will push it back on the end.
202 IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
203 pieces.pop_front();
204
Jordan Roseafa7cae2012-12-07 19:56:29 +0000205 // Throw away pieces with invalid locations. Note that we can't throw away
206 // calls just yet because they might have something interesting inside them.
207 // If so, their locations will be adjusted as necessary later.
Ted Kremeneka43df952012-09-21 00:09:11 +0000208 if (piece->getKind() != PathDiagnosticPiece::Call &&
209 piece->getLocation().asLocation().isInvalid())
210 continue;
211
Ted Kremenek72516742012-03-01 00:05:06 +0000212 switch (piece->getKind()) {
213 case PathDiagnosticPiece::Call: {
214 PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
Anna Zaks80de4872012-08-29 21:22:37 +0000215 // Check if the location context is interesting.
216 assert(LocationContextMap.count(call));
217 if (R->isInteresting(LocationContextMap[call])) {
218 containsSomethingInteresting = true;
219 break;
220 }
Jordan Rose368f3b02012-11-15 02:07:23 +0000221
Jordan Roseafa7cae2012-12-07 19:56:29 +0000222 if (!RemoveUnneededCalls(call->path, R))
Jordan Rose368f3b02012-11-15 02:07:23 +0000223 continue;
Ted Kremeneka43df952012-09-21 00:09:11 +0000224
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000225 containsSomethingInteresting = true;
Ted Kremenek72516742012-03-01 00:05:06 +0000226 break;
227 }
228 case PathDiagnosticPiece::Macro: {
229 PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
Jordan Roseafa7cae2012-12-07 19:56:29 +0000230 if (!RemoveUnneededCalls(macro->subPieces, R))
Ted Kremenek72516742012-03-01 00:05:06 +0000231 continue;
232 containsSomethingInteresting = true;
233 break;
234 }
235 case PathDiagnosticPiece::Event: {
236 PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
Ted Kremeneka43df952012-09-21 00:09:11 +0000237
Ted Kremenek72516742012-03-01 00:05:06 +0000238 // We never throw away an event, but we do throw it away wholesale
239 // as part of a path if we throw the entire path away.
Ted Kremenek22505ef2012-09-08 07:18:18 +0000240 containsSomethingInteresting |= !event->isPrunable();
Ted Kremenek72516742012-03-01 00:05:06 +0000241 break;
242 }
243 case PathDiagnosticPiece::ControlFlow:
244 break;
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000245 }
246
247 pieces.push_back(piece);
248 }
249
250 return containsSomethingInteresting;
251}
252
Jordan Roseafa7cae2012-12-07 19:56:29 +0000253/// Recursively scan through a path and make sure that all call pieces have
254/// valid locations. Note that all other pieces with invalid locations should
255/// have already been pruned out.
256static void adjustCallLocations(PathPieces &Pieces,
257 PathDiagnosticLocation *LastCallLocation = 0) {
258 for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
259 PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
260
261 if (!Call) {
262 assert((*I)->getLocation().asLocation().isValid());
263 continue;
264 }
265
266 if (LastCallLocation) {
Jordan Rose187f8bd2013-01-21 18:28:30 +0000267 if (!Call->callEnter.asLocation().isValid() ||
268 Call->getCaller()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000269 Call->callEnter = *LastCallLocation;
Jordan Rose187f8bd2013-01-21 18:28:30 +0000270 if (!Call->callReturn.asLocation().isValid() ||
271 Call->getCaller()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000272 Call->callReturn = *LastCallLocation;
273 }
274
275 // Recursively clean out the subclass. Keep this call around if
276 // it contains any informative diagnostics.
277 PathDiagnosticLocation *ThisCallLocation;
Jordan Rose187f8bd2013-01-21 18:28:30 +0000278 if (Call->callEnterWithin.asLocation().isValid() &&
279 !Call->getCallee()->isImplicit())
Jordan Roseafa7cae2012-12-07 19:56:29 +0000280 ThisCallLocation = &Call->callEnterWithin;
281 else
282 ThisCallLocation = &Call->callEnter;
283
284 assert(ThisCallLocation && "Outermost call has an invalid location");
285 adjustCallLocations(Call->path, ThisCallLocation);
286 }
287}
288
Ted Kremenekc89f4b02012-02-28 23:06:21 +0000289//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000290// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000291//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000292
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000293typedef llvm::DenseMap<const ExplodedNode*,
294const ExplodedNode*> NodeBackMap;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000295
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000296namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000297class NodeMapClosure : public BugReport::NodeResolver {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000298 NodeBackMap& M;
299public:
300 NodeMapClosure(NodeBackMap *m) : M(*m) {}
301 ~NodeMapClosure() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Ted Kremenek9c378f72011-08-12 23:37:29 +0000303 const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000304 NodeBackMap::iterator I = M.find(N);
305 return I == M.end() ? 0 : I->second;
306 }
307};
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000309class PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000310 BugReport *R;
David Blaikieef3643f2011-09-26 00:51:36 +0000311 PathDiagnosticConsumer *PDC;
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000312 OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000313 NodeMapClosure NMC;
Mike Stump1eb44332009-09-09 15:08:12 +0000314public:
Ted Kremenek59950d32012-02-24 07:12:52 +0000315 const LocationContext *LC;
316
Ted Kremenek8966bc12009-05-06 21:39:49 +0000317 PathDiagnosticBuilder(GRBugReporter &br,
Mike Stump1eb44332009-09-09 15:08:12 +0000318 BugReport *r, NodeBackMap *Backmap,
David Blaikieef3643f2011-09-26 00:51:36 +0000319 PathDiagnosticConsumer *pdc)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000320 : BugReporterContext(br),
Ted Kremenek59950d32012-02-24 07:12:52 +0000321 R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
322 {}
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Ted Kremenek9c378f72011-08-12 23:37:29 +0000324 PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Ted Kremenek9c378f72011-08-12 23:37:29 +0000326 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
327 const ExplodedNode *N);
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Anna Zaks8e6431a2011-08-18 22:37:56 +0000329 BugReport *getBugReport() { return R; }
330
Tom Care212f6d32010-09-16 03:50:38 +0000331 Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
Ted Kremenek59950d32012-02-24 07:12:52 +0000332
333 ParentMap& getParentMap() { return LC->getParentMap(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000335 const Stmt *getParent(const Stmt *S) {
336 return getParentMap().getParent(S);
337 }
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek8966bc12009-05-06 21:39:49 +0000339 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Douglas Gregor72971342009-04-18 00:02:19 +0000340
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000341 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
David Blaikieef3643f2011-09-26 00:51:36 +0000343 PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
344 return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000345 }
346
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000347 bool supportsLogicalOpControlFlow() const {
348 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
Mike Stump1eb44332009-09-09 15:08:12 +0000349 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000350};
351} // end anonymous namespace
352
Ted Kremenek00605e02009-03-27 20:55:39 +0000353PathDiagnosticLocation
Ted Kremenek9c378f72011-08-12 23:37:29 +0000354PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000355 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek59950d32012-02-24 07:12:52 +0000356 return PathDiagnosticLocation(S, getSourceManager(), LC);
Ted Kremenek00605e02009-03-27 20:55:39 +0000357
Anna Zaks0cd59482011-09-16 19:18:30 +0000358 return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
359 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000360}
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Ted Kremenek00605e02009-03-27 20:55:39 +0000362PathDiagnosticLocation
Ted Kremenek9c378f72011-08-12 23:37:29 +0000363PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
364 const ExplodedNode *N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000365
Ted Kremenek143ca222008-05-06 18:11:09 +0000366 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000367 if (os.str().empty())
368 os << ' ';
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek00605e02009-03-27 20:55:39 +0000370 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Ted Kremenek00605e02009-03-27 20:55:39 +0000372 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000373 os << "Execution continues on line "
Chandler Carruth64211622011-07-25 21:09:52 +0000374 << getSourceManager().getExpansionLineNumber(Loc.asLocation())
Ted Kremenek8966bc12009-05-06 21:39:49 +0000375 << '.';
Ted Kremenek4f1db532009-12-04 20:34:31 +0000376 else {
377 os << "Execution jumps to the end of the ";
378 const Decl *D = N->getLocationContext()->getDecl();
379 if (isa<ObjCMethodDecl>(D))
380 os << "method";
381 else if (isa<FunctionDecl>(D))
382 os << "function";
383 else {
384 assert(isa<BlockDecl>(D));
385 os << "anonymous block";
386 }
387 os << '.';
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000390 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000391}
392
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000393static bool IsNested(const Stmt *S, ParentMap &PM) {
394 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
395 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000397 const Stmt *Parent = PM.getParentIgnoreParens(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000399 if (Parent)
400 switch (Parent->getStmtClass()) {
401 case Stmt::ForStmtClass:
402 case Stmt::DoStmtClass:
403 case Stmt::WhileStmtClass:
404 return true;
405 default:
406 break;
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
409 return false;
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000410}
411
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000412PathDiagnosticLocation
413PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000414 assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
Mike Stump1eb44332009-09-09 15:08:12 +0000415 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000416 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000417
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000418 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000419 const Stmt *Parent = P.getParentIgnoreParens(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000421 if (!Parent)
422 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000424 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000425 case Stmt::BinaryOperatorClass: {
426 const BinaryOperator *B = cast<BinaryOperator>(Parent);
427 if (B->isLogicalOp())
Anna Zaks220ac8c2011-09-15 01:08:34 +0000428 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000429 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000430 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000431 case Stmt::CompoundStmtClass:
432 case Stmt::StmtExprClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000433 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000434 case Stmt::ChooseExprClass:
435 // Similar to '?' if we are referring to condition, just have the edge
436 // point to the entire choose expression.
437 if (cast<ChooseExpr>(Parent)->getCond() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000438 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000439 else
Anna Zaks220ac8c2011-09-15 01:08:34 +0000440 return PathDiagnosticLocation(S, SMgr, LC);
John McCall56ca35d2011-02-17 10:25:35 +0000441 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000442 case Stmt::ConditionalOperatorClass:
443 // For '?', if we are referring to condition, just have the edge point
444 // to the entire '?' expression.
John McCall56ca35d2011-02-17 10:25:35 +0000445 if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000446 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000447 else
Anna Zaks220ac8c2011-09-15 01:08:34 +0000448 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000449 case Stmt::DoStmtClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000450 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000451 case Stmt::ForStmtClass:
452 if (cast<ForStmt>(Parent)->getBody() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000453 return PathDiagnosticLocation(S, SMgr, LC);
Mike Stump1eb44332009-09-09 15:08:12 +0000454 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000455 case Stmt::IfStmtClass:
456 if (cast<IfStmt>(Parent)->getCond() != S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000457 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000458 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000459 case Stmt::ObjCForCollectionStmtClass:
460 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000461 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000462 break;
463 case Stmt::WhileStmtClass:
464 if (cast<WhileStmt>(Parent)->getCond() != S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000465 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000466 break;
467 default:
468 break;
469 }
470
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000471 S = Parent;
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000474 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000475
476 // Special case: DeclStmts can appear in for statement declarations, in which
477 // case the ForStmt is the context.
478 if (isa<DeclStmt>(S)) {
479 if (const Stmt *Parent = P.getParent(S)) {
480 switch (Parent->getStmtClass()) {
481 case Stmt::ForStmtClass:
482 case Stmt::ObjCForCollectionStmtClass:
Anna Zaks220ac8c2011-09-15 01:08:34 +0000483 return PathDiagnosticLocation(Parent, SMgr, LC);
Ted Kremeneke88a1702009-05-11 22:19:32 +0000484 default:
485 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000486 }
487 }
Ted Kremeneke88a1702009-05-11 22:19:32 +0000488 }
489 else if (isa<BinaryOperator>(S)) {
490 // Special case: the binary operator represents the initialization
491 // code in a for statement (this can happen when the variable being
492 // initialized is an old variable.
493 if (const ForStmt *FS =
494 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
495 if (FS->getInit() == S)
Anna Zaks220ac8c2011-09-15 01:08:34 +0000496 return PathDiagnosticLocation(FS, SMgr, LC);
Ted Kremeneke88a1702009-05-11 22:19:32 +0000497 }
498 }
499
Anna Zaks220ac8c2011-09-15 01:08:34 +0000500 return PathDiagnosticLocation(S, SMgr, LC);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000501}
502
Ted Kremenekcf118d42009-02-04 23:49:09 +0000503//===----------------------------------------------------------------------===//
Jordan Rosed632d6f2012-09-22 01:24:56 +0000504// "Visitors only" path diagnostic generation algorithm.
505//===----------------------------------------------------------------------===//
506static bool GenerateVisitorsOnlyPathDiagnostic(PathDiagnostic &PD,
507 PathDiagnosticBuilder &PDB,
508 const ExplodedNode *N,
509 ArrayRef<BugReporterVisitor *> visitors) {
510 // All path generation skips the very first node (the error node).
511 // This is because there is special handling for the end-of-path note.
512 N = N->getFirstPred();
513 if (!N)
514 return true;
515
516 BugReport *R = PDB.getBugReport();
517 while (const ExplodedNode *Pred = N->getFirstPred()) {
518 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
519 E = visitors.end();
520 I != E; ++I) {
521 // Visit all the node pairs, but throw the path pieces away.
522 PathDiagnosticPiece *Piece = (*I)->VisitNode(N, Pred, PDB, *R);
523 delete Piece;
524 }
525
526 N = Pred;
527 }
528
529 return R->isValid();
530}
531
532//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000533// "Minimal" path diagnostic generation algorithm.
534//===----------------------------------------------------------------------===//
Anna Zaks56a938f2012-03-16 23:24:20 +0000535typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
536typedef SmallVector<StackDiagPair, 6> StackDiagVector;
537
Anna Zaks368a0d52012-03-15 21:13:02 +0000538static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
Anna Zaks56a938f2012-03-16 23:24:20 +0000539 StackDiagVector &CallStack) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000540 // If the piece contains a special message, add it to all the call
541 // pieces on the active stack.
542 if (PathDiagnosticEventPiece *ep =
543 dyn_cast<PathDiagnosticEventPiece>(P)) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000544
Anna Zaks56a938f2012-03-16 23:24:20 +0000545 if (ep->hasCallStackHint())
546 for (StackDiagVector::iterator I = CallStack.begin(),
547 E = CallStack.end(); I != E; ++I) {
548 PathDiagnosticCallPiece *CP = I->first;
549 const ExplodedNode *N = I->second;
NAKAMURA Takumi8fe45252012-03-17 13:06:05 +0000550 std::string stackMsg = ep->getCallStackMessage(N);
Anna Zaks56a938f2012-03-16 23:24:20 +0000551
Anna Zaks368a0d52012-03-15 21:13:02 +0000552 // The last message on the path to final bug is the most important
553 // one. Since we traverse the path backwards, do not add the message
554 // if one has been previously added.
Anna Zaks56a938f2012-03-16 23:24:20 +0000555 if (!CP->hasCallStackMessage())
556 CP->setCallStackMessage(stackMsg);
557 }
Anna Zaks368a0d52012-03-15 21:13:02 +0000558 }
559}
Ted Kremenek31061982009-03-31 23:00:32 +0000560
Ted Kremenek77d09442012-03-02 01:27:31 +0000561static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
Ted Kremenek14856d72009-04-06 23:06:54 +0000562
Jordan Rose8347d3d2012-09-22 01:24:53 +0000563static bool GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
Ted Kremenek31061982009-03-31 23:00:32 +0000564 PathDiagnosticBuilder &PDB,
Jordy Rose3bc75ca2012-03-24 03:03:29 +0000565 const ExplodedNode *N,
566 ArrayRef<BugReporterVisitor *> visitors) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000567
Ted Kremenek31061982009-03-31 23:00:32 +0000568 SourceManager& SMgr = PDB.getSourceManager();
Ted Kremenek59950d32012-02-24 07:12:52 +0000569 const LocationContext *LC = PDB.LC;
Ted Kremenek9c378f72011-08-12 23:37:29 +0000570 const ExplodedNode *NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000571 ? NULL : *(N->pred_begin());
Anna Zaks368a0d52012-03-15 21:13:02 +0000572
Anna Zaks56a938f2012-03-16 23:24:20 +0000573 StackDiagVector CallStack;
Anna Zaks368a0d52012-03-15 21:13:02 +0000574
Ted Kremenek31061982009-03-31 23:00:32 +0000575 while (NextNode) {
Mike Stump1eb44332009-09-09 15:08:12 +0000576 N = NextNode;
Ted Kremenek59950d32012-02-24 07:12:52 +0000577 PDB.LC = N->getLocationContext();
Ted Kremenek31061982009-03-31 23:00:32 +0000578 NextNode = GetPredecessorNode(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Ted Kremenek31061982009-03-31 23:00:32 +0000580 ProgramPoint P = N->getLocation();
Jordan Rose183ba8e2012-07-26 20:04:05 +0000581
Anna Zaks80de4872012-08-29 21:22:37 +0000582 do {
583 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) {
584 PathDiagnosticCallPiece *C =
585 PathDiagnosticCallPiece::construct(N, *CE, SMgr);
586 GRBugReporter& BR = PDB.getBugReporter();
587 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
588 PD.getActivePath().push_front(C);
589 PD.pushActivePath(&C->path);
590 CallStack.push_back(StackDiagPair(C, N));
591 break;
Anna Zaks93739372012-03-14 18:58:28 +0000592 }
Jordan Rose183ba8e2012-07-26 20:04:05 +0000593
Anna Zaks80de4872012-08-29 21:22:37 +0000594 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) {
595 // Flush all locations, and pop the active path.
596 bool VisitedEntireCall = PD.isWithinCall();
597 PD.popActivePath();
598
599 // Either we just added a bunch of stuff to the top-level path, or
600 // we have a previous CallExitEnd. If the former, it means that the
601 // path terminated within a function call. We must then take the
602 // current contents of the active path and place it within
603 // a new PathDiagnosticCallPiece.
604 PathDiagnosticCallPiece *C;
605 if (VisitedEntireCall) {
606 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
607 } else {
608 const Decl *Caller = CE->getLocationContext()->getDecl();
609 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
610 GRBugReporter& BR = PDB.getBugReporter();
611 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
612 }
613
614 C->setCallee(*CE, SMgr);
615 if (!CallStack.empty()) {
616 assert(CallStack.back().first == C);
617 CallStack.pop_back();
618 }
619 break;
Anna Zaks368a0d52012-03-15 21:13:02 +0000620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Anna Zaks80de4872012-08-29 21:22:37 +0000622 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
623 const CFGBlock *Src = BE->getSrc();
624 const CFGBlock *Dst = BE->getDst();
625 const Stmt *T = Src->getTerminator();
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Anna Zaks80de4872012-08-29 21:22:37 +0000627 if (!T)
628 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Anna Zaks80de4872012-08-29 21:22:37 +0000630 PathDiagnosticLocation Start =
631 PathDiagnosticLocation::createBegin(T, SMgr,
632 N->getLocationContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Anna Zaks80de4872012-08-29 21:22:37 +0000634 switch (T->getStmtClass()) {
Ted Kremenek31061982009-03-31 23:00:32 +0000635 default:
636 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Ted Kremenek31061982009-03-31 23:00:32 +0000638 case Stmt::GotoStmtClass:
Mike Stump1eb44332009-09-09 15:08:12 +0000639 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek9c378f72011-08-12 23:37:29 +0000640 const Stmt *S = GetNextStmt(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Ted Kremenek31061982009-03-31 23:00:32 +0000642 if (!S)
Anna Zaks80de4872012-08-29 21:22:37 +0000643 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Ted Kremenek31061982009-03-31 23:00:32 +0000645 std::string sbuf;
Mike Stump1eb44332009-09-09 15:08:12 +0000646 llvm::raw_string_ostream os(sbuf);
Ted Kremenek31061982009-03-31 23:00:32 +0000647 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Ted Kremenek31061982009-03-31 23:00:32 +0000649 os << "Control jumps to line "
Anna Zaks80de4872012-08-29 21:22:37 +0000650 << End.asLocation().getExpansionLineNumber();
651 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
652 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000653 break;
654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
656 case Stmt::SwitchStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000657 // Figure out what case arm we took.
658 std::string sbuf;
659 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Ted Kremenek9c378f72011-08-12 23:37:29 +0000661 if (const Stmt *S = Dst->getLabel()) {
Anna Zaks220ac8c2011-09-15 01:08:34 +0000662 PathDiagnosticLocation End(S, SMgr, LC);
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Ted Kremenek31061982009-03-31 23:00:32 +0000664 switch (S->getStmtClass()) {
Anna Zaks80de4872012-08-29 21:22:37 +0000665 default:
666 os << "No cases match in the switch statement. "
667 "Control jumps to line "
668 << End.asLocation().getExpansionLineNumber();
669 break;
670 case Stmt::DefaultStmtClass:
671 os << "Control jumps to the 'default' case at line "
672 << End.asLocation().getExpansionLineNumber();
673 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Anna Zaks80de4872012-08-29 21:22:37 +0000675 case Stmt::CaseStmtClass: {
676 os << "Control jumps to 'case ";
677 const CaseStmt *Case = cast<CaseStmt>(S);
678 const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Anna Zaks80de4872012-08-29 21:22:37 +0000680 // Determine if it is an enum.
681 bool GetRawInt = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Anna Zaks80de4872012-08-29 21:22:37 +0000683 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
684 // FIXME: Maybe this should be an assertion. Are there cases
685 // were it is not an EnumConstantDecl?
686 const EnumConstantDecl *D =
Zhongxing Xu03509ae2010-07-20 06:22:24 +0000687 dyn_cast<EnumConstantDecl>(DR->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Anna Zaks80de4872012-08-29 21:22:37 +0000689 if (D) {
690 GetRawInt = false;
691 os << *D;
Ted Kremenek31061982009-03-31 23:00:32 +0000692 }
Ted Kremenek31061982009-03-31 23:00:32 +0000693 }
Anna Zaks80de4872012-08-29 21:22:37 +0000694
695 if (GetRawInt)
696 os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
697
698 os << ":' at line "
699 << End.asLocation().getExpansionLineNumber();
700 break;
Ted Kremenek31061982009-03-31 23:00:32 +0000701 }
Anna Zaks80de4872012-08-29 21:22:37 +0000702 }
703 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
704 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000705 }
706 else {
707 os << "'Default' branch taken. ";
Mike Stump1eb44332009-09-09 15:08:12 +0000708 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
Anna Zaks80de4872012-08-29 21:22:37 +0000709 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
710 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000711 }
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Ted Kremenek31061982009-03-31 23:00:32 +0000713 break;
714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Ted Kremenek31061982009-03-31 23:00:32 +0000716 case Stmt::BreakStmtClass:
717 case Stmt::ContinueStmtClass: {
718 std::string sbuf;
719 llvm::raw_string_ostream os(sbuf);
720 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
Anna Zaks80de4872012-08-29 21:22:37 +0000721 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
722 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000723 break;
724 }
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Anna Zaks80de4872012-08-29 21:22:37 +0000726 // Determine control-flow for ternary '?'.
John McCall56ca35d2011-02-17 10:25:35 +0000727 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek31061982009-03-31 23:00:32 +0000728 case Stmt::ConditionalOperatorClass: {
729 std::string sbuf;
730 llvm::raw_string_ostream os(sbuf);
731 os << "'?' condition is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Ted Kremenek31061982009-03-31 23:00:32 +0000733 if (*(Src->succ_begin()+1) == Dst)
734 os << "false";
735 else
736 os << "true";
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Ted Kremenek31061982009-03-31 23:00:32 +0000738 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Ted Kremenek31061982009-03-31 23:00:32 +0000740 if (const Stmt *S = End.asStmt())
741 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Anna Zaks80de4872012-08-29 21:22:37 +0000743 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
744 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000745 break;
746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Anna Zaks80de4872012-08-29 21:22:37 +0000748 // Determine control-flow for short-circuited '&&' and '||'.
Ted Kremenek31061982009-03-31 23:00:32 +0000749 case Stmt::BinaryOperatorClass: {
750 if (!PDB.supportsLogicalOpControlFlow())
751 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Zhongxing Xu03509ae2010-07-20 06:22:24 +0000753 const BinaryOperator *B = cast<BinaryOperator>(T);
Ted Kremenek31061982009-03-31 23:00:32 +0000754 std::string sbuf;
755 llvm::raw_string_ostream os(sbuf);
756 os << "Left side of '";
Mike Stump1eb44332009-09-09 15:08:12 +0000757
John McCall2de56d12010-08-25 11:45:40 +0000758 if (B->getOpcode() == BO_LAnd) {
Ted Kremenek31061982009-03-31 23:00:32 +0000759 os << "&&" << "' is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Ted Kremenek31061982009-03-31 23:00:32 +0000761 if (*(Src->succ_begin()+1) == Dst) {
762 os << "false";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000763 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
Anna Zaks0cd59482011-09-16 19:18:30 +0000764 PathDiagnosticLocation Start =
Anna Zaks80de4872012-08-29 21:22:37 +0000765 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
766 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
767 Start, End, os.str()));
Mike Stump1eb44332009-09-09 15:08:12 +0000768 }
Ted Kremenek31061982009-03-31 23:00:32 +0000769 else {
770 os << "true";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000771 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
Ted Kremenek31061982009-03-31 23:00:32 +0000772 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Anna Zaks80de4872012-08-29 21:22:37 +0000773 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
774 Start, End, os.str()));
Mike Stump1eb44332009-09-09 15:08:12 +0000775 }
Ted Kremenek31061982009-03-31 23:00:32 +0000776 }
777 else {
John McCall2de56d12010-08-25 11:45:40 +0000778 assert(B->getOpcode() == BO_LOr);
Ted Kremenek31061982009-03-31 23:00:32 +0000779 os << "||" << "' is ";
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Ted Kremenek31061982009-03-31 23:00:32 +0000781 if (*(Src->succ_begin()+1) == Dst) {
782 os << "false";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000783 PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
Ted Kremenek31061982009-03-31 23:00:32 +0000784 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Anna Zaks80de4872012-08-29 21:22:37 +0000785 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
786 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000787 }
788 else {
789 os << "true";
Anna Zaks220ac8c2011-09-15 01:08:34 +0000790 PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
Anna Zaks0cd59482011-09-16 19:18:30 +0000791 PathDiagnosticLocation Start =
Anna Zaks80de4872012-08-29 21:22:37 +0000792 PathDiagnosticLocation::createOperatorLoc(B, SMgr);
793 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
794 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000795 }
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Ted Kremenek31061982009-03-31 23:00:32 +0000798 break;
799 }
Mike Stump1eb44332009-09-09 15:08:12 +0000800
801 case Stmt::DoStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000802 if (*(Src->succ_begin()) == Dst) {
803 std::string sbuf;
804 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Ted Kremenek31061982009-03-31 23:00:32 +0000806 os << "Loop condition is true. ";
807 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Ted Kremenek31061982009-03-31 23:00:32 +0000809 if (const Stmt *S = End.asStmt())
810 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Anna Zaks80de4872012-08-29 21:22:37 +0000812 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
813 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000814 }
815 else {
816 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Ted Kremenek31061982009-03-31 23:00:32 +0000818 if (const Stmt *S = End.asStmt())
819 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Anna Zaks80de4872012-08-29 21:22:37 +0000821 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
822 Start, End, "Loop condition is false. Exiting loop"));
Ted Kremenek31061982009-03-31 23:00:32 +0000823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Ted Kremenek31061982009-03-31 23:00:32 +0000825 break;
826 }
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Ted Kremenek31061982009-03-31 23:00:32 +0000828 case Stmt::WhileStmtClass:
Mike Stump1eb44332009-09-09 15:08:12 +0000829 case Stmt::ForStmtClass: {
Ted Kremenek31061982009-03-31 23:00:32 +0000830 if (*(Src->succ_begin()+1) == Dst) {
831 std::string sbuf;
832 llvm::raw_string_ostream os(sbuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Ted Kremenek31061982009-03-31 23:00:32 +0000834 os << "Loop condition is false. ";
835 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
836 if (const Stmt *S = End.asStmt())
837 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Anna Zaks80de4872012-08-29 21:22:37 +0000839 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
840 Start, End, os.str()));
Ted Kremenek31061982009-03-31 23:00:32 +0000841 }
842 else {
843 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
844 if (const Stmt *S = End.asStmt())
845 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Anna Zaks80de4872012-08-29 21:22:37 +0000847 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
848 Start, End, "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000849 }
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Ted Kremenek31061982009-03-31 23:00:32 +0000851 break;
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Ted Kremenek31061982009-03-31 23:00:32 +0000854 case Stmt::IfStmtClass: {
855 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Ted Kremenek31061982009-03-31 23:00:32 +0000857 if (const Stmt *S = End.asStmt())
858 End = PDB.getEnclosingStmtLocation(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Ted Kremenek31061982009-03-31 23:00:32 +0000860 if (*(Src->succ_begin()+1) == Dst)
Anna Zaks80de4872012-08-29 21:22:37 +0000861 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
862 Start, End, "Taking false branch"));
Mike Stump1eb44332009-09-09 15:08:12 +0000863 else
Anna Zaks80de4872012-08-29 21:22:37 +0000864 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
865 Start, End, "Taking true branch"));
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Ted Kremenek31061982009-03-31 23:00:32 +0000867 break;
868 }
Anna Zaks80de4872012-08-29 21:22:37 +0000869 }
Ted Kremenek31061982009-03-31 23:00:32 +0000870 }
Anna Zaks80de4872012-08-29 21:22:37 +0000871 } while(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000873 if (NextNode) {
Anna Zaks8e6431a2011-08-18 22:37:56 +0000874 // Add diagnostic pieces from custom visitors.
875 BugReport *R = PDB.getBugReport();
Jordy Rose3bc75ca2012-03-24 03:03:29 +0000876 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
877 E = visitors.end();
878 I != E; ++I) {
Anna Zaks368a0d52012-03-15 21:13:02 +0000879 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
Ted Kremenek2042fc12012-02-24 06:00:00 +0000880 PD.getActivePath().push_front(p);
Anna Zaks368a0d52012-03-15 21:13:02 +0000881 updateStackPiecesWithMessage(p, CallStack);
882 }
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000883 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000884 }
Ted Kremenek31061982009-03-31 23:00:32 +0000885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Jordan Rose8347d3d2012-09-22 01:24:53 +0000887 if (!PDB.getBugReport()->isValid())
888 return false;
889
Ted Kremenek14856d72009-04-06 23:06:54 +0000890 // After constructing the full PathDiagnostic, do a pass over it to compact
891 // PathDiagnosticPieces that occur within a macro.
Ted Kremenek77d09442012-03-02 01:27:31 +0000892 CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
Jordan Rose8347d3d2012-09-22 01:24:53 +0000893 return true;
Ted Kremenek31061982009-03-31 23:00:32 +0000894}
895
896//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000897// "Extensive" PathDiagnostic generation.
898//===----------------------------------------------------------------------===//
899
900static bool IsControlFlowExpr(const Stmt *S) {
901 const Expr *E = dyn_cast<Expr>(S);
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000903 if (!E)
904 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000905
906 E = E->IgnoreParenCasts();
907
John McCall56ca35d2011-02-17 10:25:35 +0000908 if (isa<AbstractConditionalOperator>(E))
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000909 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000911 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
912 if (B->isLogicalOp())
913 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000914
915 return false;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000916}
917
Ted Kremenek14856d72009-04-06 23:06:54 +0000918namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000919class ContextLocation : public PathDiagnosticLocation {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000920 bool IsDead;
921public:
922 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
923 : PathDiagnosticLocation(L), IsDead(isdead) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000924
925 void markDead() { IsDead = true; }
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000926 bool isDead() const { return IsDead; }
927};
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000929class EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000930 std::vector<ContextLocation> CLocs;
931 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000932 PathDiagnostic &PD;
933 PathDiagnosticBuilder &PDB;
934 PathDiagnosticLocation PrevLoc;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000936 bool IsConsumedExpr(const PathDiagnosticLocation &L);
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Ted Kremenek14856d72009-04-06 23:06:54 +0000938 bool containsLocation(const PathDiagnosticLocation &Container,
939 const PathDiagnosticLocation &Containee);
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Ted Kremenek14856d72009-04-06 23:06:54 +0000941 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Ted Kremenek9650cf32009-05-11 21:42:34 +0000943 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
944 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000945 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000946 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000947 while (1) {
948 // Adjust the location for some expressions that are best referenced
949 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000950 switch (S->getStmtClass()) {
951 default:
952 break;
953 case Stmt::ParenExprClass:
Peter Collingbournef111d932011-04-15 00:35:48 +0000954 case Stmt::GenericSelectionExprClass:
955 S = cast<Expr>(S)->IgnoreParens();
Ted Kremenek9650cf32009-05-11 21:42:34 +0000956 firstCharOnly = true;
957 continue;
John McCall56ca35d2011-02-17 10:25:35 +0000958 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek9650cf32009-05-11 21:42:34 +0000959 case Stmt::ConditionalOperatorClass:
John McCall56ca35d2011-02-17 10:25:35 +0000960 S = cast<AbstractConditionalOperator>(S)->getCond();
Ted Kremenek9650cf32009-05-11 21:42:34 +0000961 firstCharOnly = true;
962 continue;
963 case Stmt::ChooseExprClass:
964 S = cast<ChooseExpr>(S)->getCond();
965 firstCharOnly = true;
966 continue;
967 case Stmt::BinaryOperatorClass:
968 S = cast<BinaryOperator>(S)->getLHS();
969 firstCharOnly = true;
970 continue;
971 }
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Ted Kremenek9650cf32009-05-11 21:42:34 +0000973 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000974 }
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Ted Kremenek9650cf32009-05-11 21:42:34 +0000976 if (S != Original)
Ted Kremenek59950d32012-02-24 07:12:52 +0000977 L = PathDiagnosticLocation(S, L.getManager(), PDB.LC);
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Ted Kremenek9650cf32009-05-11 21:42:34 +0000980 if (firstCharOnly)
Anna Zaks1531bb02011-09-20 01:38:47 +0000981 L = PathDiagnosticLocation::createSingleLocation(L);
Ted Kremenek9650cf32009-05-11 21:42:34 +0000982
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000983 return L;
984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Ted Kremenek14856d72009-04-06 23:06:54 +0000986 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000987 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000988 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000989 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000990 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000991 CLocs.pop_back();
992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Ted Kremenek14856d72009-04-06 23:06:54 +0000994public:
995 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
996 : PD(pd), PDB(pdb) {
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Ted Kremeneka301a672009-04-22 18:16:20 +0000998 // If the PathDiagnostic already has pieces, add the enclosing statement
999 // of the first piece as a context as well.
Ted Kremenek802e0242012-02-08 04:32:34 +00001000 if (!PD.path.empty()) {
1001 PrevLoc = (*PD.path.begin())->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Ted Kremenek14856d72009-04-06 23:06:54 +00001003 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +00001004 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001005 }
1006 }
1007
1008 ~EdgeBuilder() {
1009 while (!CLocs.empty()) popLocation();
Anna Zaks0cd59482011-09-16 19:18:30 +00001010
Ted Kremeneka301a672009-04-22 18:16:20 +00001011 // Finally, add an initial edge from the start location of the first
1012 // statement (if it doesn't already exist).
Anna Zaks0cd59482011-09-16 19:18:30 +00001013 PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
Ted Kremenek59950d32012-02-24 07:12:52 +00001014 PDB.LC,
Anna Zaks0cd59482011-09-16 19:18:30 +00001015 PDB.getSourceManager());
1016 if (L.isValid())
1017 rawAddEdge(L);
Ted Kremenek14856d72009-04-06 23:06:54 +00001018 }
1019
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001020 void flushLocations() {
1021 while (!CLocs.empty())
1022 popLocation();
1023 PrevLoc = PathDiagnosticLocation();
1024 }
1025
Ted Kremenek14856d72009-04-06 23:06:54 +00001026 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001028 void rawAddEdge(PathDiagnosticLocation NewLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Ted Kremenek14856d72009-04-06 23:06:54 +00001030 void addContext(const Stmt *S);
Jordan Rose183ba8e2012-07-26 20:04:05 +00001031 void addContext(const PathDiagnosticLocation &L);
Ted Kremeneke1baed32009-05-05 23:13:38 +00001032 void addExtendedContext(const Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +00001033};
Ted Kremenek14856d72009-04-06 23:06:54 +00001034} // end anonymous namespace
1035
1036
1037PathDiagnosticLocation
1038EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
1039 if (const Stmt *S = L.asStmt()) {
1040 if (IsControlFlowExpr(S))
1041 return L;
Mike Stump1eb44332009-09-09 15:08:12 +00001042
1043 return PDB.getEnclosingStmtLocation(S);
Ted Kremenek14856d72009-04-06 23:06:54 +00001044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremenek14856d72009-04-06 23:06:54 +00001046 return L;
1047}
1048
1049bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
1050 const PathDiagnosticLocation &Containee) {
1051
1052 if (Container == Containee)
1053 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Ted Kremenek14856d72009-04-06 23:06:54 +00001055 if (Container.asDecl())
1056 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek14856d72009-04-06 23:06:54 +00001058 if (const Stmt *S = Containee.asStmt())
1059 if (const Stmt *ContainerS = Container.asStmt()) {
1060 while (S) {
1061 if (S == ContainerS)
1062 return true;
1063 S = PDB.getParent(S);
1064 }
1065 return false;
1066 }
1067
1068 // Less accurate: compare using source ranges.
1069 SourceRange ContainerR = Container.asRange();
1070 SourceRange ContaineeR = Containee.asRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Ted Kremenek14856d72009-04-06 23:06:54 +00001072 SourceManager &SM = PDB.getSourceManager();
Chandler Carruth40278532011-07-25 16:49:02 +00001073 SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
1074 SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
1075 SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
1076 SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chandler Carruth64211622011-07-25 21:09:52 +00001078 unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
1079 unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
1080 unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
1081 unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Ted Kremenek14856d72009-04-06 23:06:54 +00001083 assert(ContainerBegLine <= ContainerEndLine);
Mike Stump1eb44332009-09-09 15:08:12 +00001084 assert(ContaineeBegLine <= ContaineeEndLine);
1085
Ted Kremenek14856d72009-04-06 23:06:54 +00001086 return (ContainerBegLine <= ContaineeBegLine &&
1087 ContainerEndLine >= ContaineeEndLine &&
1088 (ContainerBegLine != ContaineeBegLine ||
Chandler Carrutha77c0312011-07-25 20:57:57 +00001089 SM.getExpansionColumnNumber(ContainerRBeg) <=
1090 SM.getExpansionColumnNumber(ContaineeRBeg)) &&
Ted Kremenek14856d72009-04-06 23:06:54 +00001091 (ContainerEndLine != ContaineeEndLine ||
Chandler Carrutha77c0312011-07-25 20:57:57 +00001092 SM.getExpansionColumnNumber(ContainerREnd) >=
Ted Kremenek6488dc32012-03-28 05:24:50 +00001093 SM.getExpansionColumnNumber(ContaineeREnd)));
Ted Kremenek14856d72009-04-06 23:06:54 +00001094}
1095
Ted Kremenek14856d72009-04-06 23:06:54 +00001096void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1097 if (!PrevLoc.isValid()) {
1098 PrevLoc = NewLoc;
1099 return;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001102 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
1103 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Ted Kremeneka43df952012-09-21 00:09:11 +00001105 if (PrevLocClean.asLocation().isInvalid()) {
1106 PrevLoc = NewLoc;
1107 return;
1108 }
1109
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001110 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001111 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Ted Kremenek14856d72009-04-06 23:06:54 +00001113 // FIXME: Ignore intra-macro edges for now.
Chandler Carruth40278532011-07-25 16:49:02 +00001114 if (NewLocClean.asLocation().getExpansionLoc() ==
1115 PrevLocClean.asLocation().getExpansionLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001116 return;
1117
Ted Kremenek2042fc12012-02-24 06:00:00 +00001118 PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001119 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001120}
1121
1122void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Ted Kremeneka301a672009-04-22 18:16:20 +00001124 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1125 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Ted Kremenek14856d72009-04-06 23:06:54 +00001127 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1128
1129 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001130 ContextLocation &TopContextLoc = CLocs.back();
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Ted Kremenek14856d72009-04-06 23:06:54 +00001132 // Is the top location context the same as the one for the new location?
1133 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001134 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001135 if (IsConsumedExpr(TopContextLoc) &&
1136 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001137 TopContextLoc.markDead();
1138
Ted Kremenek14856d72009-04-06 23:06:54 +00001139 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001140 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001141
1142 return;
1143 }
1144
1145 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001146 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001147 rawAddEdge(NewLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001149 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001150 CLocs.push_back(ContextLocation(CLoc, true));
1151 return;
1152 }
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Ted Kremenek14856d72009-04-06 23:06:54 +00001155 CLocs.push_back(CLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001156 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001157 }
1158
1159 // Context does not contain the location. Flush it.
1160 popLocation();
1161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001163 // If we reach here, there is no enclosing context. Just add the edge.
1164 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001165}
1166
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001167bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1168 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1169 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001171 return false;
1172}
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremeneke1baed32009-05-05 23:13:38 +00001174void EdgeBuilder::addExtendedContext(const Stmt *S) {
1175 if (!S)
1176 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001177
1178 const Stmt *Parent = PDB.getParent(S);
Ted Kremeneke1baed32009-05-05 23:13:38 +00001179 while (Parent) {
1180 if (isa<CompoundStmt>(Parent))
1181 Parent = PDB.getParent(Parent);
1182 else
1183 break;
1184 }
1185
1186 if (Parent) {
1187 switch (Parent->getStmtClass()) {
1188 case Stmt::DoStmtClass:
1189 case Stmt::ObjCAtSynchronizedStmtClass:
1190 addContext(Parent);
1191 default:
1192 break;
1193 }
1194 }
Mike Stump1eb44332009-09-09 15:08:12 +00001195
Ted Kremeneke1baed32009-05-05 23:13:38 +00001196 addContext(S);
1197}
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Ted Kremenek14856d72009-04-06 23:06:54 +00001199void EdgeBuilder::addContext(const Stmt *S) {
1200 if (!S)
1201 return;
1202
Ted Kremenek59950d32012-02-24 07:12:52 +00001203 PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
Jordan Rose183ba8e2012-07-26 20:04:05 +00001204 addContext(L);
1205}
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Jordan Rose183ba8e2012-07-26 20:04:05 +00001207void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001208 while (!CLocs.empty()) {
1209 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1210
1211 // Is the top location context the same as the one for the new location?
1212 if (TopContextLoc == L)
1213 return;
1214
1215 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001216 CLocs.push_back(L);
Mike Stump1eb44332009-09-09 15:08:12 +00001217 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001218 }
1219
1220 // Context does not contain the location. Flush it.
1221 popLocation();
1222 }
1223
1224 CLocs.push_back(L);
1225}
1226
Ted Kremenek11abcec2012-05-02 00:31:29 +00001227// Cone-of-influence: support the reverse propagation of "interesting" symbols
1228// and values by tracing interesting calculations backwards through evaluated
1229// expressions along a path. This is probably overly complicated, but the idea
1230// is that if an expression computed an "interesting" value, the child
1231// expressions are are also likely to be "interesting" as well (which then
1232// propagates to the values they in turn compute). This reverse propagation
1233// is needed to track interesting correlations across function call boundaries,
1234// where formal arguments bind to actual arguments, etc. This is also needed
1235// because the constraint solver sometimes simplifies certain symbolic values
1236// into constants when appropriate, and this complicates reasoning about
1237// interesting values.
1238typedef llvm::DenseSet<const Expr *> InterestingExprs;
1239
1240static void reversePropagateIntererstingSymbols(BugReport &R,
1241 InterestingExprs &IE,
1242 const ProgramState *State,
1243 const Expr *Ex,
1244 const LocationContext *LCtx) {
1245 SVal V = State->getSVal(Ex, LCtx);
1246 if (!(R.isInteresting(V) || IE.count(Ex)))
1247 return;
1248
1249 switch (Ex->getStmtClass()) {
1250 default:
1251 if (!isa<CastExpr>(Ex))
1252 break;
1253 // Fall through.
1254 case Stmt::BinaryOperatorClass:
1255 case Stmt::UnaryOperatorClass: {
1256 for (Stmt::const_child_iterator CI = Ex->child_begin(),
1257 CE = Ex->child_end();
1258 CI != CE; ++CI) {
1259 if (const Expr *child = dyn_cast_or_null<Expr>(*CI)) {
1260 IE.insert(child);
1261 SVal ChildV = State->getSVal(child, LCtx);
1262 R.markInteresting(ChildV);
1263 }
1264 break;
1265 }
1266 }
1267 }
1268
1269 R.markInteresting(V);
1270}
1271
1272static void reversePropagateInterestingSymbols(BugReport &R,
1273 InterestingExprs &IE,
1274 const ProgramState *State,
1275 const LocationContext *CalleeCtx,
1276 const LocationContext *CallerCtx)
1277{
Jordan Rose852aa0d2012-07-10 22:07:52 +00001278 // FIXME: Handle non-CallExpr-based CallEvents.
Ted Kremenek11abcec2012-05-02 00:31:29 +00001279 const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
1280 const Stmt *CallSite = Callee->getCallSite();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001281 if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001282 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
1283 FunctionDecl::param_const_iterator PI = FD->param_begin(),
1284 PE = FD->param_end();
1285 CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
1286 for (; AI != AE && PI != PE; ++AI, ++PI) {
1287 if (const Expr *ArgE = *AI) {
1288 if (const ParmVarDecl *PD = *PI) {
1289 Loc LV = State->getLValue(PD, CalleeCtx);
1290 if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
1291 IE.insert(ArgE);
1292 }
1293 }
1294 }
1295 }
1296 }
1297}
1298
Jordan Rose8347d3d2012-09-22 01:24:53 +00001299static bool GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek14856d72009-04-06 23:06:54 +00001300 PathDiagnosticBuilder &PDB,
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001301 const ExplodedNode *N,
1302 ArrayRef<BugReporterVisitor *> visitors) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001303 EdgeBuilder EB(PD, PDB);
Anna Zaks0cd59482011-09-16 19:18:30 +00001304 const SourceManager& SM = PDB.getSourceManager();
Anna Zaks56a938f2012-03-16 23:24:20 +00001305 StackDiagVector CallStack;
Ted Kremenek11abcec2012-05-02 00:31:29 +00001306 InterestingExprs IE;
Ted Kremenek14856d72009-04-06 23:06:54 +00001307
Ted Kremenek9c378f72011-08-12 23:37:29 +00001308 const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001309 while (NextNode) {
1310 N = NextNode;
1311 NextNode = GetPredecessorNode(N);
1312 ProgramPoint P = N->getLocation();
1313
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001314 do {
Ted Kremenek11abcec2012-05-02 00:31:29 +00001315 if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
1316 if (const Expr *Ex = PS->getStmtAs<Expr>())
1317 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1318 N->getState().getPtr(), Ex,
1319 N->getLocationContext());
1320 }
1321
Anna Zaks0b3ade82012-04-20 21:59:08 +00001322 if (const CallExitEnd *CE = dyn_cast<CallExitEnd>(&P)) {
Jordan Rose183ba8e2012-07-26 20:04:05 +00001323 const Stmt *S = CE->getCalleeContext()->getCallSite();
1324 if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001325 reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
1326 N->getState().getPtr(), Ex,
1327 N->getLocationContext());
Jordan Rose852aa0d2012-07-10 22:07:52 +00001328 }
Jordan Rose183ba8e2012-07-26 20:04:05 +00001329
1330 PathDiagnosticCallPiece *C =
1331 PathDiagnosticCallPiece::construct(N, *CE, SM);
Anna Zaks80de4872012-08-29 21:22:37 +00001332 GRBugReporter& BR = PDB.getBugReporter();
1333 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Jordan Rose183ba8e2012-07-26 20:04:05 +00001334
1335 EB.addEdge(C->callReturn, true);
1336 EB.flushLocations();
1337
1338 PD.getActivePath().push_front(C);
1339 PD.pushActivePath(&C->path);
1340 CallStack.push_back(StackDiagPair(C, N));
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001341 break;
1342 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001343
Ted Kremenek2042fc12012-02-24 06:00:00 +00001344 // Pop the call hierarchy if we are done walking the contents
1345 // of a function call.
1346 if (const CallEnter *CE = dyn_cast<CallEnter>(&P)) {
Ted Kremenek097ebb32012-03-06 01:25:01 +00001347 // Add an edge to the start of the function.
1348 const Decl *D = CE->getCalleeContext()->getDecl();
1349 PathDiagnosticLocation pos =
1350 PathDiagnosticLocation::createBegin(D, SM);
1351 EB.addEdge(pos);
1352
1353 // Flush all locations, and pop the active path.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001354 bool VisitedEntireCall = PD.isWithinCall();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001355 EB.flushLocations();
Ted Kremenek2042fc12012-02-24 06:00:00 +00001356 PD.popActivePath();
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001357 PDB.LC = N->getLocationContext();
Ted Kremenek097ebb32012-03-06 01:25:01 +00001358
Jordan Rose183ba8e2012-07-26 20:04:05 +00001359 // Either we just added a bunch of stuff to the top-level path, or
1360 // we have a previous CallExitEnd. If the former, it means that the
Ted Kremenek2042fc12012-02-24 06:00:00 +00001361 // path terminated within a function call. We must then take the
1362 // current contents of the active path and place it within
1363 // a new PathDiagnosticCallPiece.
Jordan Rose183ba8e2012-07-26 20:04:05 +00001364 PathDiagnosticCallPiece *C;
1365 if (VisitedEntireCall) {
1366 C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
1367 } else {
1368 const Decl *Caller = CE->getLocationContext()->getDecl();
Anna Zaks93739372012-03-14 18:58:28 +00001369 C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
Anna Zaks80de4872012-08-29 21:22:37 +00001370 GRBugReporter& BR = PDB.getBugReporter();
1371 BR.addCallPieceLocationContextPair(C, CE->getCalleeContext());
Anna Zaks93739372012-03-14 18:58:28 +00001372 }
Jordan Rose852aa0d2012-07-10 22:07:52 +00001373
Jordan Rose183ba8e2012-07-26 20:04:05 +00001374 C->setCallee(*CE, SM);
1375 EB.addContext(C->getLocation());
Anna Zaks368a0d52012-03-15 21:13:02 +00001376
1377 if (!CallStack.empty()) {
Anna Zaks56a938f2012-03-16 23:24:20 +00001378 assert(CallStack.back().first == C);
Anna Zaks368a0d52012-03-15 21:13:02 +00001379 CallStack.pop_back();
1380 }
Ted Kremenek2042fc12012-02-24 06:00:00 +00001381 break;
1382 }
Ted Kremenek4ba86bc2012-03-02 21:16:22 +00001383
1384 // Note that is important that we update the LocationContext
1385 // after looking at CallExits. CallExit basically adds an
1386 // edge in the *caller*, so we don't want to update the LocationContext
1387 // too soon.
1388 PDB.LC = N->getLocationContext();
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001389
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001390 // Block edges.
Ted Kremenek11abcec2012-05-02 00:31:29 +00001391 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1392 // Does this represent entering a call? If so, look at propagating
1393 // interesting symbols across call boundaries.
1394 if (NextNode) {
1395 const LocationContext *CallerCtx = NextNode->getLocationContext();
1396 const LocationContext *CalleeCtx = PDB.LC;
1397 if (CallerCtx != CalleeCtx) {
1398 reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
1399 N->getState().getPtr(),
1400 CalleeCtx, CallerCtx);
1401 }
1402 }
1403
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001404 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001405 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
Ted Kremenek59950d32012-02-24 07:12:52 +00001406 PathDiagnosticLocation L(Loop, SM, PDB.LC);
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001407 const CompoundStmt *CS = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001409 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1410 CS = dyn_cast<CompoundStmt>(FS->getBody());
1411 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1412 CS = dyn_cast<CompoundStmt>(WS->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001414 PathDiagnosticEventPiece *p =
1415 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001416 "Looping back to the head of the loop");
Ted Kremenek2dd17ab2012-03-06 01:00:36 +00001417 p->setPrunable(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001419 EB.addEdge(p->getLocation(), true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001420 PD.getActivePath().push_front(p);
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001422 if (CS) {
Anna Zaks0cd59482011-09-16 19:18:30 +00001423 PathDiagnosticLocation BL =
1424 PathDiagnosticLocation::createEndBrace(CS, SM);
Ted Kremenek07c015c2009-05-15 02:46:13 +00001425 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001426 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001427 }
Ted Kremenekf57a2aa2012-09-12 06:22:18 +00001428
1429 if (const Stmt *Term = BE->getSrc()->getTerminator())
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001430 EB.addContext(Term);
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001432 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001433 }
1434
Mike Stump1eb44332009-09-09 15:08:12 +00001435 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
Jordan Rose1a7bcc42012-09-12 22:48:08 +00001436 CFGElement First = BE->getFirstElement();
1437 if (const CFGStmt *S = First.getAs<CFGStmt>()) {
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001438 const Stmt *stmt = S->getStmt();
1439 if (IsControlFlowExpr(stmt)) {
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001440 // Add the proper context for '&&', '||', and '?'.
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001441 EB.addContext(stmt);
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001442 }
1443 else
Ted Kremenek3c0349e2011-03-01 03:15:10 +00001444 EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001445 }
Zhongxing Xub36cd3e2010-09-16 01:25:47 +00001446
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001447 break;
1448 }
Ted Kremenek5de4fdb2012-02-07 02:26:17 +00001449
1450
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001451 } while (0);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001453 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001454 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Anna Zaks8e6431a2011-08-18 22:37:56 +00001456 // Add pieces from custom visitors.
1457 BugReport *R = PDB.getBugReport();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001458 for (ArrayRef<BugReporterVisitor *>::iterator I = visitors.begin(),
1459 E = visitors.end();
1460 I != E; ++I) {
Anna Zaks8e6431a2011-08-18 22:37:56 +00001461 if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001462 const PathDiagnosticLocation &Loc = p->getLocation();
1463 EB.addEdge(Loc, true);
Ted Kremenek2042fc12012-02-24 06:00:00 +00001464 PD.getActivePath().push_front(p);
Anna Zaks368a0d52012-03-15 21:13:02 +00001465 updateStackPiecesWithMessage(p, CallStack);
1466
Ted Kremenek8966bc12009-05-06 21:39:49 +00001467 if (const Stmt *S = Loc.asStmt())
Mike Stump1eb44332009-09-09 15:08:12 +00001468 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek8966bc12009-05-06 21:39:49 +00001469 }
Mike Stump1eb44332009-09-09 15:08:12 +00001470 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001471 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00001472
1473 return PDB.getBugReport()->isValid();
Ted Kremenek14856d72009-04-06 23:06:54 +00001474}
1475
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001476//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001477// Methods for BugType and subclasses.
1478//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001479BugType::~BugType() { }
1480
Ted Kremenekcf118d42009-02-04 23:49:09 +00001481void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001482
David Blaikie99ba9e32011-12-20 02:48:34 +00001483void BuiltinBug::anchor() {}
1484
Ted Kremenekcf118d42009-02-04 23:49:09 +00001485//===----------------------------------------------------------------------===//
1486// Methods for BugReport and subclasses.
1487//===----------------------------------------------------------------------===//
Anna Zakse172e8b2011-08-17 23:00:25 +00001488
David Blaikie99ba9e32011-12-20 02:48:34 +00001489void BugReport::NodeResolver::anchor() {}
1490
Anna Zaks8e6431a2011-08-18 22:37:56 +00001491void BugReport::addVisitor(BugReporterVisitor* visitor) {
1492 if (!visitor)
1493 return;
1494
1495 llvm::FoldingSetNodeID ID;
1496 visitor->Profile(ID);
1497 void *InsertPos;
1498
1499 if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
1500 delete visitor;
1501 return;
1502 }
1503
1504 CallbacksSet.InsertNode(visitor, InsertPos);
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001505 Callbacks.push_back(visitor);
1506 ++ConfigurationChangeToken;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001507}
1508
1509BugReport::~BugReport() {
1510 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
Anna Zaksdc757b02011-08-19 23:21:56 +00001511 delete *I;
Anna Zaks8e6431a2011-08-18 22:37:56 +00001512 }
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001513 while (!interestingSymbols.empty()) {
1514 popInterestingSymbolsAndRegions();
1515 }
Anna Zaks8e6431a2011-08-18 22:37:56 +00001516}
Anna Zakse172e8b2011-08-17 23:00:25 +00001517
Ted Kremenek07189522012-04-04 18:11:35 +00001518const Decl *BugReport::getDeclWithIssue() const {
1519 if (DeclWithIssue)
1520 return DeclWithIssue;
1521
1522 const ExplodedNode *N = getErrorNode();
1523 if (!N)
1524 return 0;
1525
1526 const LocationContext *LC = N->getLocationContext();
1527 return LC->getCurrentStackFrame()->getDecl();
1528}
1529
Anna Zakse172e8b2011-08-17 23:00:25 +00001530void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
1531 hash.AddPointer(&BT);
Anna Zakse172e8b2011-08-17 23:00:25 +00001532 hash.AddString(Description);
Anna Zaks97bfb552013-01-08 00:25:29 +00001533 PathDiagnosticLocation UL = getUniqueingLocation();
1534 if (UL.isValid()) {
1535 UL.Profile(hash);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001536 } else if (Location.isValid()) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001537 Location.Profile(hash);
1538 } else {
1539 assert(ErrorNode);
1540 hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
1541 }
Anna Zakse172e8b2011-08-17 23:00:25 +00001542
1543 for (SmallVectorImpl<SourceRange>::const_iterator I =
1544 Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1545 const SourceRange range = *I;
1546 if (!range.isValid())
1547 continue;
1548 hash.AddInteger(range.getBegin().getRawEncoding());
1549 hash.AddInteger(range.getEnd().getRawEncoding());
1550 }
1551}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001552
Ted Kremenek76aadc32012-03-09 01:13:14 +00001553void BugReport::markInteresting(SymbolRef sym) {
1554 if (!sym)
1555 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001556
1557 // If the symbol wasn't already in our set, note a configuration change.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001558 if (getInterestingSymbols().insert(sym).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001559 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001560
1561 if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001562 getInterestingRegions().insert(meta->getRegion());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001563}
1564
1565void BugReport::markInteresting(const MemRegion *R) {
1566 if (!R)
1567 return;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001568
1569 // If the base region wasn't already in our set, note a configuration change.
Ted Kremenek76aadc32012-03-09 01:13:14 +00001570 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001571 if (getInterestingRegions().insert(R).second)
Jordy Rose3bc75ca2012-03-24 03:03:29 +00001572 ++ConfigurationChangeToken;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001573
Ted Kremenek76aadc32012-03-09 01:13:14 +00001574 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001575 getInterestingSymbols().insert(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001576}
1577
1578void BugReport::markInteresting(SVal V) {
1579 markInteresting(V.getAsRegion());
1580 markInteresting(V.getAsSymbol());
1581}
1582
Anna Zaks80de4872012-08-29 21:22:37 +00001583void BugReport::markInteresting(const LocationContext *LC) {
1584 if (!LC)
1585 return;
1586 InterestingLocationContexts.insert(LC);
1587}
1588
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001589bool BugReport::isInteresting(SVal V) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001590 return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
1591}
1592
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001593bool BugReport::isInteresting(SymbolRef sym) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001594 if (!sym)
1595 return false;
Jordy Rose8ec588e2012-03-15 22:45:29 +00001596 // We don't currently consider metadata symbols to be interesting
1597 // even if we know their region is interesting. Is that correct behavior?
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001598 return getInterestingSymbols().count(sym);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001599}
1600
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001601bool BugReport::isInteresting(const MemRegion *R) {
Ted Kremenek76aadc32012-03-09 01:13:14 +00001602 if (!R)
1603 return false;
1604 R = R->getBaseRegion();
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001605 bool b = getInterestingRegions().count(R);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001606 if (b)
1607 return true;
1608 if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001609 return getInterestingSymbols().count(SR->getSymbol());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001610 return false;
1611}
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001612
Anna Zaks80de4872012-08-29 21:22:37 +00001613bool BugReport::isInteresting(const LocationContext *LC) {
1614 if (!LC)
1615 return false;
1616 return InterestingLocationContexts.count(LC);
1617}
1618
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00001619void BugReport::lazyInitializeInterestingSets() {
1620 if (interestingSymbols.empty()) {
1621 interestingSymbols.push_back(new Symbols());
1622 interestingRegions.push_back(new Regions());
1623 }
1624}
1625
1626BugReport::Symbols &BugReport::getInterestingSymbols() {
1627 lazyInitializeInterestingSets();
1628 return *interestingSymbols.back();
1629}
1630
1631BugReport::Regions &BugReport::getInterestingRegions() {
1632 lazyInitializeInterestingSets();
1633 return *interestingRegions.back();
1634}
1635
1636void BugReport::pushInterestingSymbolsAndRegions() {
1637 interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
1638 interestingRegions.push_back(new Regions(getInterestingRegions()));
1639}
1640
1641void BugReport::popInterestingSymbolsAndRegions() {
1642 delete interestingSymbols.back();
1643 interestingSymbols.pop_back();
1644 delete interestingRegions.back();
1645 interestingRegions.pop_back();
1646}
Ted Kremenek76aadc32012-03-09 01:13:14 +00001647
Ted Kremenek9c378f72011-08-12 23:37:29 +00001648const Stmt *BugReport::getStmt() const {
Anna Zakse172e8b2011-08-17 23:00:25 +00001649 if (!ErrorNode)
1650 return 0;
1651
Tom Care212f6d32010-09-16 03:50:38 +00001652 ProgramPoint ProgP = ErrorNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001653 const Stmt *S = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Ted Kremenek9c378f72011-08-12 23:37:29 +00001655 if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) {
Zhongxing Xufafd3832009-08-20 01:23:34 +00001656 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001657 if (BE->getBlock() == &Exit)
Tom Care212f6d32010-09-16 03:50:38 +00001658 S = GetPreviousStmt(ErrorNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001659 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001660 if (!S)
Mike Stump1eb44332009-09-09 15:08:12 +00001661 S = GetStmt(ProgP);
1662
1663 return S;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001664}
1665
Argyrios Kyrtzidis640ccf02010-12-04 01:12:15 +00001666std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
Anna Zakse172e8b2011-08-17 23:00:25 +00001667BugReport::getRanges() {
1668 // If no custom ranges, add the range of the statement corresponding to
1669 // the error node.
1670 if (Ranges.empty()) {
1671 if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
1672 addRange(E->getSourceRange());
1673 else
1674 return std::make_pair(ranges_iterator(), ranges_iterator());
1675 }
1676
Anna Zaks14924262011-08-24 20:31:06 +00001677 // User-specified absence of range info.
1678 if (Ranges.size() == 1 && !Ranges.begin()->isValid())
1679 return std::make_pair(ranges_iterator(), ranges_iterator());
1680
Anna Zakse172e8b2011-08-17 23:00:25 +00001681 return std::make_pair(Ranges.begin(), Ranges.end());
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001682}
1683
Anna Zaks590dd8e2011-09-20 21:38:35 +00001684PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
Anna Zaksb7530a42011-08-17 23:21:23 +00001685 if (ErrorNode) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001686 assert(!Location.isValid() &&
Anna Zaksb7530a42011-08-17 23:21:23 +00001687 "Either Location or ErrorNode should be specified but not both.");
1688
Ted Kremenek9c378f72011-08-12 23:37:29 +00001689 if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
Anna Zaks590dd8e2011-09-20 21:38:35 +00001690 const LocationContext *LC = ErrorNode->getLocationContext();
1691
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001692 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001693 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001694 return PathDiagnosticLocation::createMemberLoc(ME, SM);
Ted Kremenek5b9bd212009-09-11 22:07:28 +00001695 // For binary operators, return the location of the operator.
1696 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
Anna Zaks590dd8e2011-09-20 21:38:35 +00001697 return PathDiagnosticLocation::createOperatorLoc(B, SM);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001698
Jordan Rose63bc1862012-11-15 19:11:43 +00001699 if (isa<PostStmtPurgeDeadSymbols>(ErrorNode->getLocation()))
1700 return PathDiagnosticLocation::createEnd(S, SM, LC);
1701
Anna Zaks590dd8e2011-09-20 21:38:35 +00001702 return PathDiagnosticLocation::createBegin(S, SM, LC);
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001703 }
Anna Zaksb7530a42011-08-17 23:21:23 +00001704 } else {
1705 assert(Location.isValid());
1706 return Location;
1707 }
1708
Anna Zaks590dd8e2011-09-20 21:38:35 +00001709 return PathDiagnosticLocation();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001710}
1711
Ted Kremenekcf118d42009-02-04 23:49:09 +00001712//===----------------------------------------------------------------------===//
1713// Methods for BugReporter and subclasses.
1714//===----------------------------------------------------------------------===//
1715
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00001716BugReportEquivClass::~BugReportEquivClass() { }
Zhongxing Xua2f4ec02009-09-05 06:06:49 +00001717GRBugReporter::~GRBugReporter() { }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001718BugReporterData::~BugReporterData() {}
1719
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001720ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001721
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001722ProgramStateManager&
Ted Kremenekcf118d42009-02-04 23:49:09 +00001723GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1724
Anna Zaks3b030a22011-08-19 01:57:09 +00001725BugReporter::~BugReporter() {
1726 FlushReports();
1727
1728 // Free the bug reports we are tracking.
1729 typedef std::vector<BugReportEquivClass *> ContTy;
1730 for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
1731 I != E; ++I) {
1732 delete *I;
1733 }
1734}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001735
1736void BugReporter::FlushReports() {
1737 if (BugTypes.isEmpty())
1738 return;
1739
1740 // First flush the warnings for each BugType. This may end up creating new
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001741 // warnings and new BugTypes.
1742 // FIXME: Only NSErrorChecker needs BugType's FlushReports.
1743 // Turn NSErrorChecker into a proper checker and remove this.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001744 SmallVector<const BugType*, 16> bugTypes;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001745 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001746 bugTypes.push_back(*I);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001747 for (SmallVector<const BugType*, 16>::iterator
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001748 I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
Ted Kremenekcf118d42009-02-04 23:49:09 +00001749 const_cast<BugType*>(*I)->FlushReports(*this);
1750
Anna Zaksd015f4f2012-08-02 23:41:05 +00001751 // We need to flush reports in deterministic order to ensure the order
1752 // of the reports is consistent between runs.
Anna Zaks0eb6c372012-08-02 00:41:43 +00001753 typedef std::vector<BugReportEquivClass *> ContVecTy;
1754 for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
1755 EI != EE; ++EI){
1756 BugReportEquivClass& EQ = **EI;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001757 FlushReport(EQ);
Ted Kremenek94826a72008-04-03 04:59:14 +00001758 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001759
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00001760 // BugReporter owns and deletes only BugTypes created implicitly through
1761 // EmitBasicReport.
1762 // FIXME: There are leaks from checkers that assume that the BugTypes they
1763 // create will be destroyed by the BugReporter.
1764 for (llvm::StringMap<BugType*>::iterator
1765 I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
1766 delete I->second;
1767
Ted Kremenekcf118d42009-02-04 23:49:09 +00001768 // Remove all references to the BugType objects.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001769 BugTypes = F.getEmptySet();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001770}
1771
1772//===----------------------------------------------------------------------===//
1773// PathDiagnostics generation.
1774//===----------------------------------------------------------------------===//
1775
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001776static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001777 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001778MakeReportGraph(const ExplodedGraph* G,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001779 SmallVectorImpl<const ExplodedNode*> &nodes) {
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Ted Kremenekcf118d42009-02-04 23:49:09 +00001781 // Create the trimmed graph. It will contain the shortest paths from the
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // error nodes to the root. In the new graph we should only have one
Ted Kremenekcf118d42009-02-04 23:49:09 +00001783 // error node unless there are two or more error nodes with the same minimum
1784 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001785 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001786 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001787
1788 llvm::DenseMap<const void*, const void*> InverseMap;
Ted Kremenek40406fe2010-12-03 06:52:30 +00001789 llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
1790 &InverseMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Ted Kremenekcf118d42009-02-04 23:49:09 +00001792 // Create owning pointers for GTrim and NMap just to ensure that they are
1793 // released when this function exists.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001794 OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
1795 OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Ted Kremenekcf118d42009-02-04 23:49:09 +00001797 // Find the (first) error node in the trimmed graph. We just need to consult
1798 // the node map (NMap) which maps from nodes in the original graph to nodes
1799 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001800
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001801 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001802 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001803 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001804
Ted Kremenek40406fe2010-12-03 06:52:30 +00001805 for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
1806 const ExplodedNode *originalNode = nodes[nodeIndex];
1807 if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001808 WS.push(N);
Ted Kremenek40406fe2010-12-03 06:52:30 +00001809 IndexMap[originalNode] = nodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001810 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00001811 }
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Ted Kremenek938332c2009-05-16 01:11:58 +00001813 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001814
1815 // Create a new (third!) graph with a single path. This is the graph
1816 // that will be returned to the caller.
Zhongxing Xuc77a5512010-07-01 07:10:59 +00001817 ExplodedGraph *GNew = new ExplodedGraph();
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Ted Kremenek10aa5542009-03-12 23:41:59 +00001819 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001820 // to the root node, and then construct a new graph that contains only
1821 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001822 llvm::DenseMap<const void*,unsigned> Visited;
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001824 unsigned cnt = 0;
Ted Kremenek9c378f72011-08-12 23:37:29 +00001825 const ExplodedNode *Root = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001827 while (!WS.empty()) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00001828 const ExplodedNode *Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001829 WS.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001831 if (Visited.find(Node) != Visited.end())
1832 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001834 Visited[Node] = cnt++;
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001836 if (Node->pred_empty()) {
1837 Root = Node;
1838 break;
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001841 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001842 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001843 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Ted Kremenek938332c2009-05-16 01:11:58 +00001846 assert(Root);
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Ted Kremenek10aa5542009-03-12 23:41:59 +00001848 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001849 // with the lowest number.
Mike Stump1eb44332009-09-09 15:08:12 +00001850 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001851 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001852 unsigned NodeIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001854 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001855 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001856 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001857 assert(I != Visited.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001859 // Create the equivalent node in the new graph with the same state
1860 // and location.
Ted Kremenek9c378f72011-08-12 23:37:29 +00001861 ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001863 // Store the mapping to the original node.
1864 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1865 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001866 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001868 // Link up the new node with the previous node.
1869 if (Last)
Ted Kremenek5fe4d9d2009-10-07 00:42:52 +00001870 NewN->addPredecessor(Last, *GNew);
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001872 Last = NewN;
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001874 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001875 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001876 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001877 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001878 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001879 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001880 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001881 }
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001883 // Find the next successor node. We choose the node that is marked
1884 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001885 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1886 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001887 N = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001889 for (unsigned MinVal = 0; SI != SE; ++SI) {
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001891 I = Visited.find(*SI);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001893 if (I == Visited.end())
1894 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001896 if (!N || I->second < MinVal) {
1897 N = *SI;
1898 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001899 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Ted Kremenek938332c2009-05-16 01:11:58 +00001902 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Ted Kremenek938332c2009-05-16 01:11:58 +00001905 assert(First);
1906
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001907 return std::make_pair(std::make_pair(GNew, BM),
1908 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001909}
1910
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001911/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1912/// and collapses PathDiagosticPieces that are expanded by macros.
Ted Kremenek77d09442012-03-02 01:27:31 +00001913static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
Ted Kremenek2042fc12012-02-24 06:00:00 +00001914 typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
1915 SourceLocation> > MacroStackTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001917 typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001918 PiecesTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001920 MacroStackTy MacroStack;
1921 PiecesTy Pieces;
Mike Stump1eb44332009-09-09 15:08:12 +00001922
Ted Kremenek77d09442012-03-02 01:27:31 +00001923 for (PathPieces::const_iterator I = path.begin(), E = path.end();
Ted Kremenek2042fc12012-02-24 06:00:00 +00001924 I!=E; ++I) {
Ted Kremenek77d09442012-03-02 01:27:31 +00001925
1926 PathDiagnosticPiece *piece = I->getPtr();
1927
1928 // Recursively compact calls.
1929 if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
1930 CompactPathDiagnostic(call->path, SM);
1931 }
1932
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001933 // Get the location of the PathDiagnosticPiece.
Ted Kremenek77d09442012-03-02 01:27:31 +00001934 const FullSourceLoc Loc = piece->getLocation().asLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001936 // Determine the instantiation location, which is the location we group
1937 // related PathDiagnosticPieces.
Mike Stump1eb44332009-09-09 15:08:12 +00001938 SourceLocation InstantiationLoc = Loc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00001939 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001940 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001942 if (Loc.isFileID()) {
1943 MacroStack.clear();
Ted Kremenek77d09442012-03-02 01:27:31 +00001944 Pieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001945 continue;
1946 }
1947
1948 assert(Loc.isMacroID());
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001950 // Is the PathDiagnosticPiece within the same macro group?
1951 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
Ted Kremenek77d09442012-03-02 01:27:31 +00001952 MacroStack.back().first->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001953 continue;
1954 }
1955
1956 // We aren't in the same group. Are we descending into a new macro
1957 // or are part of an old one?
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001958 IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001959
1960 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
Chandler Carruth40278532011-07-25 16:49:02 +00001961 SM.getExpansionLoc(Loc) :
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001962 SourceLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001964 // Walk the entire macro stack.
1965 while (!MacroStack.empty()) {
1966 if (InstantiationLoc == MacroStack.back().second) {
1967 MacroGroup = MacroStack.back().first;
1968 break;
1969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001971 if (ParentInstantiationLoc == MacroStack.back().second) {
1972 MacroGroup = MacroStack.back().first;
1973 break;
1974 }
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001976 MacroStack.pop_back();
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001979 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1980 // Create a new macro group and add it to the stack.
Anna Zaks590dd8e2011-09-20 21:38:35 +00001981 PathDiagnosticMacroPiece *NewGroup =
1982 new PathDiagnosticMacroPiece(
Ted Kremenek77d09442012-03-02 01:27:31 +00001983 PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001984
1985 if (MacroGroup)
Ted Kremenek802e0242012-02-08 04:32:34 +00001986 MacroGroup->subPieces.push_back(NewGroup);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001987 else {
1988 assert(InstantiationLoc.isFileID());
1989 Pieces.push_back(NewGroup);
1990 }
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001992 MacroGroup = NewGroup;
1993 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1994 }
1995
1996 // Finally, add the PathDiagnosticPiece to the group.
Ted Kremenek77d09442012-03-02 01:27:31 +00001997 MacroGroup->subPieces.push_back(piece);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002000 // Now take the pieces and construct a new PathDiagnostic.
Ted Kremenek77d09442012-03-02 01:27:31 +00002001 path.clear();
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Ted Kremenek77d09442012-03-02 01:27:31 +00002003 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I)
2004 path.push_back(*I);
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00002005}
2006
Jordan Rose8347d3d2012-09-22 01:24:53 +00002007bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002008 PathDiagnosticConsumer &PC,
2009 ArrayRef<BugReport *> &bugReports) {
Ted Kremenek40406fe2010-12-03 06:52:30 +00002010 assert(!bugReports.empty());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002011
2012 bool HasValid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002013 SmallVector<const ExplodedNode *, 10> errorNodes;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002014 for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
2015 E = bugReports.end(); I != E; ++I) {
Jordan Rose8347d3d2012-09-22 01:24:53 +00002016 if ((*I)->isValid()) {
2017 HasValid = true;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002018 errorNodes.push_back((*I)->getErrorNode());
Jordan Rose8347d3d2012-09-22 01:24:53 +00002019 } else {
2020 errorNodes.push_back(0);
2021 }
Ted Kremenek40406fe2010-12-03 06:52:30 +00002022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Jordan Rose8347d3d2012-09-22 01:24:53 +00002024 // If all the reports have been marked invalid, we're done.
2025 if (!HasValid)
2026 return false;
2027
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00002028 // Construct a new graph that contains only a single path from the error
Mike Stump1eb44332009-09-09 15:08:12 +00002029 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00002030 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002031 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek40406fe2010-12-03 06:52:30 +00002032 GPair = MakeReportGraph(&getGraph(), errorNodes);
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Ted Kremenekcf118d42009-02-04 23:49:09 +00002034 // Find the BugReport with the original location.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002035 assert(GPair.second.second < bugReports.size());
2036 BugReport *R = bugReports[GPair.second.second];
Ted Kremenekcf118d42009-02-04 23:49:09 +00002037 assert(R && "No original report found for sliced graph.");
Jordan Rose8347d3d2012-09-22 01:24:53 +00002038 assert(R->isValid() && "Report selected from trimmed graph marked invalid.");
Mike Stump1eb44332009-09-09 15:08:12 +00002039
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002040 OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
2041 OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00002042 const ExplodedNode *N = GPair.second.first;
Mike Stump1eb44332009-09-09 15:08:12 +00002043
2044 // Start building the path diagnostic...
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002045 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), &PC);
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Anna Zaks8e6431a2011-08-18 22:37:56 +00002047 // Register additional node visitors.
Anna Zaks50bbc162011-08-19 22:33:38 +00002048 R->addVisitor(new NilReceiverBRVisitor());
2049 R->addVisitor(new ConditionBRVisitor());
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002051 BugReport::VisitorList visitors;
2052 unsigned originalReportConfigToken, finalReportConfigToken;
Anna Zaks23f395e2011-08-20 01:27:22 +00002053
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002054 // While generating diagnostics, it's possible the visitors will decide
2055 // new symbols and regions are interesting, or add other visitors based on
2056 // the information they find. If they do, we need to regenerate the path
2057 // based on our new report configuration.
2058 do {
2059 // Get a clean copy of all the visitors.
2060 for (BugReport::visitor_iterator I = R->visitor_begin(),
2061 E = R->visitor_end(); I != E; ++I)
2062 visitors.push_back((*I)->clone());
2063
2064 // Clear out the active path from any previous work.
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002065 PD.resetPath();
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002066 originalReportConfigToken = R->getConfigurationChangeToken();
2067
2068 // Generate the very last diagnostic piece - the piece is visible before
2069 // the trace is expanded.
Jordan Rosed632d6f2012-09-22 01:24:56 +00002070 if (PDB.getGenerationScheme() != PathDiagnosticConsumer::None) {
2071 PathDiagnosticPiece *LastPiece = 0;
2072 for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
2073 I != E; ++I) {
2074 if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
2075 assert (!LastPiece &&
2076 "There can only be one final piece in a diagnostic.");
2077 LastPiece = Piece;
2078 }
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002079 }
Jordan Rosed632d6f2012-09-22 01:24:56 +00002080 if (!LastPiece)
2081 LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
2082 if (LastPiece)
2083 PD.setEndOfPath(LastPiece);
2084 else
2085 return false;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002086 }
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002087
2088 switch (PDB.getGenerationScheme()) {
David Blaikieef3643f2011-09-26 00:51:36 +00002089 case PathDiagnosticConsumer::Extensive:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002090 if (!GenerateExtensivePathDiagnostic(PD, PDB, N, visitors)) {
2091 assert(!R->isValid() && "Failed on valid report");
2092 // Try again. We'll filter out the bad report when we trim the graph.
2093 // FIXME: It would be more efficient to use the same intermediate
2094 // trimmed graph, and just repeat the shortest-path search.
2095 return generatePathDiagnostic(PD, PC, bugReports);
2096 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00002097 break;
David Blaikieef3643f2011-09-26 00:51:36 +00002098 case PathDiagnosticConsumer::Minimal:
Jordan Rose8347d3d2012-09-22 01:24:53 +00002099 if (!GenerateMinimalPathDiagnostic(PD, PDB, N, visitors)) {
2100 assert(!R->isValid() && "Failed on valid report");
2101 // Try again. We'll filter out the bad report when we trim the graph.
2102 return generatePathDiagnostic(PD, PC, bugReports);
2103 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00002104 break;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002105 case PathDiagnosticConsumer::None:
Jordan Rosed632d6f2012-09-22 01:24:56 +00002106 if (!GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors)) {
2107 assert(!R->isValid() && "Failed on valid report");
2108 // Try again. We'll filter out the bad report when we trim the graph.
2109 return generatePathDiagnostic(PD, PC, bugReports);
2110 }
2111 break;
Jordy Rose3bc75ca2012-03-24 03:03:29 +00002112 }
2113
2114 // Clean up the visitors we used.
2115 llvm::DeleteContainerPointers(visitors);
2116
2117 // Did anything change while generating this path?
2118 finalReportConfigToken = R->getConfigurationChangeToken();
2119 } while(finalReportConfigToken != originalReportConfigToken);
2120
Ted Kremenekc89f4b02012-02-28 23:06:21 +00002121 // Finally, prune the diagnostic path of uninteresting stuff.
Ted Kremenekb85cce02012-10-25 22:07:10 +00002122 if (!PD.path.empty()) {
2123 // Remove messages that are basically the same.
Ted Kremenek38001652012-10-26 16:02:36 +00002124 removeRedundantMsgs(PD.getMutablePieces());
Ted Kremenekb85cce02012-10-25 22:07:10 +00002125
2126 if (R->shouldPrunePath()) {
Jordan Roseafa7cae2012-12-07 19:56:29 +00002127 bool hasSomethingInteresting = RemoveUnneededCalls(PD.getMutablePieces(),
2128 R);
Ted Kremenekb85cce02012-10-25 22:07:10 +00002129 assert(hasSomethingInteresting);
2130 (void) hasSomethingInteresting;
2131 }
Jordan Roseafa7cae2012-12-07 19:56:29 +00002132
2133 adjustCallLocations(PD.getMutablePieces());
Ted Kremeneked7948b2012-05-31 06:03:17 +00002134 }
Jordan Rose8347d3d2012-09-22 01:24:53 +00002135
2136 return true;
Ted Kremenek7dc86642009-03-31 20:22:36 +00002137}
2138
Ted Kremenekcf118d42009-02-04 23:49:09 +00002139void BugReporter::Register(BugType *BT) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00002140 BugTypes = F.add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00002141}
2142
Anna Zaks1dfebd92013-01-19 02:18:15 +00002143bool BugReporter::suppressReport(BugReport *R) {
2144 const Stmt *S = R->getStmt();
2145 if (!S)
2146 return false;
2147
2148 // Here we suppress false positives coming from system macros. This list is
2149 // based on known issues.
2150
2151 // Skip reports within the sys/queue.h macros as we do not have the ability to
2152 // reason about data structure shapes.
2153 SourceManager &SM = getSourceManager();
2154 SourceLocation Loc = S->getLocStart();
2155 while (Loc.isMacroID()) {
2156 if (SM.isInSystemMacro(Loc) &&
2157 (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h")))
2158 return true;
2159 Loc = SM.getSpellingLoc(Loc);
2160 }
2161
2162 return false;
2163}
2164
Jordan Rose785950e2012-11-02 01:53:40 +00002165void BugReporter::emitReport(BugReport* R) {
Anna Zaks1dfebd92013-01-19 02:18:15 +00002166 if (suppressReport(R))
2167 return;
2168
Ted Kremenekcf118d42009-02-04 23:49:09 +00002169 // Compute the bug report's hash to determine its equivalence class.
2170 llvm::FoldingSetNodeID ID;
2171 R->Profile(ID);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
2173 // Lookup the equivance class. If there isn't one, create it.
Ted Kremenekcf118d42009-02-04 23:49:09 +00002174 BugType& BT = R->getBugType();
2175 Register(&BT);
2176 void *InsertPos;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002177 BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Ted Kremenekcf118d42009-02-04 23:49:09 +00002179 if (!EQ) {
2180 EQ = new BugReportEquivClass(R);
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002181 EQClasses.InsertNode(EQ, InsertPos);
Anna Zaks3b030a22011-08-19 01:57:09 +00002182 EQClassesVector.push_back(EQ);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002183 }
2184 else
2185 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00002186}
2187
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002188
2189//===----------------------------------------------------------------------===//
2190// Emitting reports in equivalence classes.
2191//===----------------------------------------------------------------------===//
2192
2193namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +00002194struct FRIEC_WLItem {
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002195 const ExplodedNode *N;
2196 ExplodedNode::const_succ_iterator I, E;
2197
2198 FRIEC_WLItem(const ExplodedNode *n)
2199 : N(n), I(N->succ_begin()), E(N->succ_end()) {}
2200};
2201}
2202
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002203static BugReport *
2204FindReportInEquivalenceClass(BugReportEquivClass& EQ,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002205 SmallVectorImpl<BugReport*> &bugReports) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002206
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002207 BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
2208 assert(I != E);
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002209 BugType& BT = I->getBugType();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002210
Ted Kremenek40406fe2010-12-03 06:52:30 +00002211 // If we don't need to suppress any of the nodes because they are
2212 // post-dominated by a sink, simply add all the nodes in the equivalence class
2213 // to 'Nodes'. Any of the reports will serve as a "representative" report.
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002214 if (!BT.isSuppressOnSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002215 BugReport *R = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002216 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Ted Kremenek9c378f72011-08-12 23:37:29 +00002217 const ExplodedNode *N = I->getErrorNode();
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002218 if (N) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002219 R = I;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002220 bugReports.push_back(R);
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002221 }
2222 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002223 return R;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002224 }
2225
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002226 // For bug reports that should be suppressed when all paths are post-dominated
2227 // by a sink node, iterate through the reports in the equivalence class
2228 // until we find one that isn't post-dominated (if one exists). We use a
2229 // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
2230 // this as a recursive function, but we don't want to risk blowing out the
2231 // stack for very long paths.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002232 BugReport *exampleReport = 0;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002233
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002234 for (; I != E; ++I) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002235 const ExplodedNode *errorNode = I->getErrorNode();
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002236
Ted Kremenek40406fe2010-12-03 06:52:30 +00002237 if (!errorNode)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002238 continue;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002239 if (errorNode->isSink()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002240 llvm_unreachable(
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002241 "BugType::isSuppressSink() should not be 'true' for sink end nodes");
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002242 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002243 // No successors? By definition this nodes isn't post-dominated by a sink.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002244 if (errorNode->succ_empty()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002245 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002246 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002247 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002248 continue;
2249 }
2250
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002251 // At this point we know that 'N' is not a sink and it has at least one
2252 // successor. Use a DFS worklist to find a non-sink end-of-path node.
2253 typedef FRIEC_WLItem WLItem;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002254 typedef SmallVector<WLItem, 10> DFSWorkList;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002255 llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
2256
2257 DFSWorkList WL;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002258 WL.push_back(errorNode);
2259 Visited[errorNode] = 1;
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002260
2261 while (!WL.empty()) {
2262 WLItem &WI = WL.back();
2263 assert(!WI.N->succ_empty());
2264
2265 for (; WI.I != WI.E; ++WI.I) {
2266 const ExplodedNode *Succ = *WI.I;
2267 // End-of-path node?
2268 if (Succ->succ_empty()) {
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002269 // If we found an end-of-path node that is not a sink.
2270 if (!Succ->isSink()) {
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002271 bugReports.push_back(I);
Ted Kremenek40406fe2010-12-03 06:52:30 +00002272 if (!exampleReport)
Benjamin Kramer4a5f7242012-04-01 19:30:51 +00002273 exampleReport = I;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002274 WL.clear();
2275 break;
2276 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002277 // Found a sink? Continue on to the next successor.
2278 continue;
2279 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002280 // Mark the successor as visited. If it hasn't been explored,
2281 // enqueue it to the DFS worklist.
2282 unsigned &mark = Visited[Succ];
2283 if (!mark) {
2284 mark = 1;
2285 WL.push_back(Succ);
2286 break;
2287 }
2288 }
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002289
2290 // The worklist may have been cleared at this point. First
2291 // check if it is empty before checking the last item.
2292 if (!WL.empty() && &WL.back() == &WI)
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002293 WL.pop_back();
2294 }
2295 }
Ted Kremenek06c9cb42009-09-14 22:01:32 +00002296
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002297 // ExampleReport will be NULL if all the nodes in the equivalence class
2298 // were post-dominated by sinks.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002299 return exampleReport;
Ted Kremenek61f52bd2010-09-09 19:05:34 +00002300}
Ted Kremeneke0a58072009-09-18 22:37:37 +00002301
Ted Kremenekcf118d42009-02-04 23:49:09 +00002302void BugReporter::FlushReport(BugReportEquivClass& EQ) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002303 SmallVector<BugReport*, 10> bugReports;
Ted Kremenek40406fe2010-12-03 06:52:30 +00002304 BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002305 if (exampleReport) {
2306 const PathDiagnosticConsumers &C = getPathDiagnosticConsumers();
2307 for (PathDiagnosticConsumers::const_iterator I=C.begin(),
2308 E=C.end(); I != E; ++I) {
2309 FlushReport(exampleReport, **I, bugReports);
2310 }
2311 }
2312}
2313
2314void BugReporter::FlushReport(BugReport *exampleReport,
2315 PathDiagnosticConsumer &PD,
2316 ArrayRef<BugReport*> bugReports) {
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Ted Kremenekcf118d42009-02-04 23:49:09 +00002318 // FIXME: Make sure we use the 'R' for the path that was actually used.
Mike Stump1eb44332009-09-09 15:08:12 +00002319 // Probably doesn't make a difference in practice.
Ted Kremenek40406fe2010-12-03 06:52:30 +00002320 BugType& BT = exampleReport->getBugType();
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002322 OwningPtr<PathDiagnostic>
Ted Kremenek07189522012-04-04 18:11:35 +00002323 D(new PathDiagnostic(exampleReport->getDeclWithIssue(),
2324 exampleReport->getBugType().getName(),
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002325 exampleReport->getDescription(),
2326 exampleReport->getShortDescription(/*Fallback=*/false),
Anna Zaks97bfb552013-01-08 00:25:29 +00002327 BT.getCategory(),
2328 exampleReport->getUniqueingLocation(),
2329 exampleReport->getUniqueingDecl()));
Ted Kremenekd49967f2009-04-29 21:58:13 +00002330
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002331 // Generate the full path diagnostic, using the generation scheme
Jordan Rosed632d6f2012-09-22 01:24:56 +00002332 // specified by the PathDiagnosticConsumer. Note that we have to generate
2333 // path diagnostics even for consumers which do not support paths, because
2334 // the BugReporterVisitors may mark this bug as a false positive.
2335 if (!bugReports.empty())
2336 if (!generatePathDiagnostic(*D.get(), PD, bugReports))
2337 return;
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002338
2339 // If the path is empty, generate a single step path with the location
2340 // of the issue.
2341 if (D->path.empty()) {
2342 PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
2343 PathDiagnosticPiece *piece =
2344 new PathDiagnosticEventPiece(L, exampleReport->getDescription());
2345 BugReport::ranges_iterator Beg, End;
2346 llvm::tie(Beg, End) = exampleReport->getRanges();
2347 for ( ; Beg != End; ++Beg)
2348 piece->addRange(*Beg);
Jordan Rose3a46f5f2012-08-31 00:36:26 +00002349 D->setEndOfPath(piece);
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002350 }
2351
Ted Kremenek072192b2008-04-30 23:47:44 +00002352 // Get the meta data.
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002353 const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
Anna Zaks7f2531c2011-08-22 20:31:28 +00002354 for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
2355 e = Meta.end(); i != e; ++i) {
2356 D->addMeta(*i);
2357 }
Ted Kremenek75840e12008-04-18 01:56:37 +00002358
Ted Kremenekc4bac8e2012-08-16 17:45:23 +00002359 PD.HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00002360}
Ted Kremenek57202072008-07-14 17:40:50 +00002361
Ted Kremenek07189522012-04-04 18:11:35 +00002362void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
Ted Kremenek07189522012-04-04 18:11:35 +00002363 StringRef name,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002364 StringRef category,
Anna Zaks590dd8e2011-09-20 21:38:35 +00002365 StringRef str, PathDiagnosticLocation Loc,
Ted Kremenek8c036c72008-09-20 04:23:38 +00002366 SourceRange* RBeg, unsigned NumRanges) {
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002368 // 'BT' is owned by BugReporter.
2369 BugType *BT = getBugTypeForName(name, category);
Anna Zaks590dd8e2011-09-20 21:38:35 +00002370 BugReport *R = new BugReport(*BT, str, Loc);
Ted Kremenek07189522012-04-04 18:11:35 +00002371 R->setDeclWithIssue(DeclWithIssue);
Ted Kremenekcf118d42009-02-04 23:49:09 +00002372 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
Jordan Rose785950e2012-11-02 01:53:40 +00002373 emitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00002374}
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002375
Chris Lattner5f9e2722011-07-23 10:55:15 +00002376BugType *BugReporter::getBugTypeForName(StringRef name,
2377 StringRef category) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002378 SmallString<136> fullDesc;
Argyrios Kyrtzidis404fc3a2011-02-23 00:16:01 +00002379 llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
2380 llvm::StringMapEntry<BugType *> &
2381 entry = StrBugTypes.GetOrCreateValue(fullDesc);
2382 BugType *BT = entry.getValue();
2383 if (!BT) {
2384 BT = new BugType(name, category);
2385 entry.setValue(BT);
2386 }
2387 return BT;
2388}