blob: 43e1e6c8bcbdb5411da0c96f12ba9501beb487cb [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
15#include "clang/Analysis/PathSensitive/BugReporter.h"
Ted Kremenek50a6d0c2008-04-09 21:41:14 +000016#include "clang/Analysis/PathSensitive/GRExprEngine.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000017#include "clang/AST/ASTContext.h"
Ted Kremeneke41611a2009-07-16 18:13:04 +000018#include "clang/Analysis/CFG.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000019#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000020#include "clang/AST/ParentMap.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
22#include "clang/Basic/SourceManager.h"
Ted Kremenek61f3e052008-04-03 04:42:52 +000023#include "clang/Analysis/ProgramPoint.h"
24#include "clang/Analysis/PathDiagnostic.h"
Chris Lattner405674c2008-08-23 22:23:37 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek331b0ac2008-06-18 05:34:07 +000026#include "llvm/ADT/DenseMap.h"
Ted Kremenekcf118d42009-02-04 23:49:09 +000027#include "llvm/ADT/STLExtras.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000028#include "llvm/ADT/OwningPtr.h"
Ted Kremenek10aa5542009-03-12 23:41:59 +000029#include <queue>
Ted Kremenek61f3e052008-04-03 04:42:52 +000030
31using namespace clang;
32
Ted Kremenek8966bc12009-05-06 21:39:49 +000033BugReporterVisitor::~BugReporterVisitor() {}
34BugReporterContext::~BugReporterContext() {
35 for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I)
36 if ((*I)->isOwnedByReporterContext()) delete *I;
37}
38
Ted Kremenekcf118d42009-02-04 23:49:09 +000039//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000040// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000041//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenek5f85e172009-07-22 22:35:28 +000043static inline const Stmt* GetStmt(ProgramPoint P) {
Ted Kremenekb697b102009-02-23 22:44:26 +000044 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000045 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000046 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000047 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000048
Ted Kremenekb697b102009-02-23 22:44:26 +000049 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000050}
51
Ted Kremenek3148eb42009-01-24 00:55:43 +000052static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000053GetPredecessorNode(const ExplodedNode<GRState>* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054 return N->pred_empty() ? NULL : *(N->pred_begin());
55}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000056
Ted Kremenekb697b102009-02-23 22:44:26 +000057static inline const ExplodedNode<GRState>*
58GetSuccessorNode(const ExplodedNode<GRState>* N) {
59 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Ted Kremenek5f85e172009-07-22 22:35:28 +000062static const Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000063 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000064 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000065 return S;
66
67 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000068}
69
Ted Kremenek5f85e172009-07-22 22:35:28 +000070static const Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000071 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000072 if (const Stmt *S = GetStmt(N->getLocation())) {
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000073 // Check if the statement is '?' or '&&'/'||'. These are "merges",
74 // not actual statement points.
75 switch (S->getStmtClass()) {
76 case Stmt::ChooseExprClass:
77 case Stmt::ConditionalOperatorClass: continue;
78 case Stmt::BinaryOperatorClass: {
79 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
80 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
81 continue;
82 break;
83 }
84 default:
85 break;
86 }
Ted Kremenekb697b102009-02-23 22:44:26 +000087 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000088 }
Ted Kremenekb697b102009-02-23 22:44:26 +000089
90 return 0;
91}
92
Ted Kremenek5f85e172009-07-22 22:35:28 +000093static inline const Stmt*
94GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
95 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000096 return S;
97
98 return GetPreviousStmt(N);
99}
100
Ted Kremenek5f85e172009-07-22 22:35:28 +0000101static inline const Stmt*
102GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
103 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000104 return S;
105
106 return GetNextStmt(N);
107}
108
109//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000110// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000111//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000112
Ted Kremenek7dc86642009-03-31 20:22:36 +0000113typedef llvm::DenseMap<const ExplodedNode<GRState>*,
114const ExplodedNode<GRState>*> NodeBackMap;
115
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000116namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000117class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
118 NodeBackMap& M;
119public:
120 NodeMapClosure(NodeBackMap *m) : M(*m) {}
121 ~NodeMapClosure() {}
122
123 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
124 NodeBackMap::iterator I = M.find(N);
125 return I == M.end() ? 0 : I->second;
126 }
127};
128
Ted Kremenek8966bc12009-05-06 21:39:49 +0000129class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000130 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000131 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000132 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000133 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000134public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000135 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000136 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000137 PathDiagnosticClient *pdc)
138 : BugReporterContext(br),
139 R(r), PDC(pdc), NMC(Backmap)
140 {
141 addVisitor(R);
142 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000143
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000145
Ted Kremenek00605e02009-03-27 20:55:39 +0000146 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
147 const ExplodedNode<GRState>* N);
148
149 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000150 if (PM.get() == 0)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000151 PM.reset(new ParentMap(getCodeDecl().getBody()));
Ted Kremenek00605e02009-03-27 20:55:39 +0000152 return *PM.get();
153 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000154
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000155 const Stmt *getParent(const Stmt *S) {
156 return getParentMap().getParent(S);
157 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000158
159 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000160 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000161
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000162 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
163
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000164 PathDiagnosticLocation
165 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
166 if (const Stmt *S = L.asStmt())
167 return getEnclosingStmtLocation(S);
168
169 return L;
170 }
171
Ted Kremenek7dc86642009-03-31 20:22:36 +0000172 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
173 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
174 }
175
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000176 bool supportsLogicalOpControlFlow() const {
177 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
178 }
179};
180} // end anonymous namespace
181
Ted Kremenek00605e02009-03-27 20:55:39 +0000182PathDiagnosticLocation
183PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000184 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000185 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000186
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000187 return FullSourceLoc(getCodeDecl().getBodyRBrace(), getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000188}
189
Ted Kremenek00605e02009-03-27 20:55:39 +0000190PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000191PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
192 const ExplodedNode<GRState>* N) {
193
Ted Kremenek143ca222008-05-06 18:11:09 +0000194 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000195 if (os.str().empty())
196 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000197
Ted Kremenek00605e02009-03-27 20:55:39 +0000198 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000199
Ted Kremenek00605e02009-03-27 20:55:39 +0000200 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000201 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000202 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
203 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000204 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000205 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000206 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000207
208 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000209}
210
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000211static bool IsNested(const Stmt *S, ParentMap &PM) {
212 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
213 return true;
214
215 const Stmt *Parent = PM.getParentIgnoreParens(S);
216
217 if (Parent)
218 switch (Parent->getStmtClass()) {
219 case Stmt::ForStmtClass:
220 case Stmt::DoStmtClass:
221 case Stmt::WhileStmtClass:
222 return true;
223 default:
224 break;
225 }
226
227 return false;
228}
229
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000230PathDiagnosticLocation
231PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
232 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000233 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000234 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000235
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000236 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000237 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000238
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000239 if (!Parent)
240 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000241
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000242 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000243 case Stmt::BinaryOperatorClass: {
244 const BinaryOperator *B = cast<BinaryOperator>(Parent);
245 if (B->isLogicalOp())
246 return PathDiagnosticLocation(S, SMgr);
247 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000248 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000249 case Stmt::CompoundStmtClass:
250 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000251 return PathDiagnosticLocation(S, SMgr);
252 case Stmt::ChooseExprClass:
253 // Similar to '?' if we are referring to condition, just have the edge
254 // point to the entire choose expression.
255 if (cast<ChooseExpr>(Parent)->getCond() == S)
256 return PathDiagnosticLocation(Parent, SMgr);
257 else
258 return PathDiagnosticLocation(S, SMgr);
259 case Stmt::ConditionalOperatorClass:
260 // For '?', if we are referring to condition, just have the edge point
261 // to the entire '?' expression.
262 if (cast<ConditionalOperator>(Parent)->getCond() == S)
263 return PathDiagnosticLocation(Parent, SMgr);
264 else
265 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000266 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000267 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000268 case Stmt::ForStmtClass:
269 if (cast<ForStmt>(Parent)->getBody() == S)
270 return PathDiagnosticLocation(S, SMgr);
271 break;
272 case Stmt::IfStmtClass:
273 if (cast<IfStmt>(Parent)->getCond() != S)
274 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000275 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000276 case Stmt::ObjCForCollectionStmtClass:
277 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
278 return PathDiagnosticLocation(S, SMgr);
279 break;
280 case Stmt::WhileStmtClass:
281 if (cast<WhileStmt>(Parent)->getCond() != S)
282 return PathDiagnosticLocation(S, SMgr);
283 break;
284 default:
285 break;
286 }
287
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000288 S = Parent;
289 }
290
291 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000292
293 // Special case: DeclStmts can appear in for statement declarations, in which
294 // case the ForStmt is the context.
295 if (isa<DeclStmt>(S)) {
296 if (const Stmt *Parent = P.getParent(S)) {
297 switch (Parent->getStmtClass()) {
298 case Stmt::ForStmtClass:
299 case Stmt::ObjCForCollectionStmtClass:
300 return PathDiagnosticLocation(Parent, SMgr);
301 default:
302 break;
303 }
304 }
305 }
306 else if (isa<BinaryOperator>(S)) {
307 // Special case: the binary operator represents the initialization
308 // code in a for statement (this can happen when the variable being
309 // initialized is an old variable.
310 if (const ForStmt *FS =
311 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
312 if (FS->getInit() == S)
313 return PathDiagnosticLocation(FS, SMgr);
314 }
315 }
316
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000317 return PathDiagnosticLocation(S, SMgr);
318}
319
Ted Kremenekcf118d42009-02-04 23:49:09 +0000320//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000321// ScanNotableSymbols: closure-like callback for scanning Store bindings.
322//===----------------------------------------------------------------------===//
323
324static const VarDecl*
325GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
326 GRStateManager& VMgr, SVal X) {
327
328 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
329
330 ProgramPoint P = N->getLocation();
331
332 if (!isa<PostStmt>(P))
333 continue;
334
Ted Kremenek5f85e172009-07-22 22:35:28 +0000335 const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
Ted Kremenek31061982009-03-31 23:00:32 +0000336
337 if (!DR)
338 continue;
339
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000340 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000341
342 if (X != Y)
343 continue;
344
Ted Kremenek5f85e172009-07-22 22:35:28 +0000345 const VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
Ted Kremenek31061982009-03-31 23:00:32 +0000346
347 if (!VD)
348 continue;
349
350 return VD;
351 }
352
353 return 0;
354}
355
356namespace {
357class VISIBILITY_HIDDEN NotableSymbolHandler
358: public StoreManager::BindingsHandler {
359
360 SymbolRef Sym;
361 const GRState* PrevSt;
362 const Stmt* S;
363 GRStateManager& VMgr;
364 const ExplodedNode<GRState>* Pred;
365 PathDiagnostic& PD;
366 BugReporter& BR;
367
368public:
369
370 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
371 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
372 PathDiagnostic& pd, BugReporter& br)
373 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
374
375 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
376 SVal V) {
377
378 SymbolRef ScanSym = V.getAsSymbol();
379
380 if (ScanSym != Sym)
381 return true;
382
383 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000384 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000385
386 if (X == V) // Same binding?
387 return true;
388
389 // Different binding. Only handle assignments for now. We don't pull
390 // this check out of the loop because we will eventually handle other
391 // cases.
392
393 VarDecl *VD = 0;
394
395 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
396 if (!B->isAssignmentOp())
397 return true;
398
399 // What variable did we assign to?
400 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
401
402 if (!DR)
403 return true;
404
405 VD = dyn_cast<VarDecl>(DR->getDecl());
406 }
407 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
408 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
409 // assume that each DeclStmt has a single Decl. This invariant
410 // holds by contruction in the CFG.
411 VD = dyn_cast<VarDecl>(*DS->decl_begin());
412 }
413
414 if (!VD)
415 return true;
416
417 // What is the most recently referenced variable with this binding?
418 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
419
420 if (!MostRecent)
421 return true;
422
423 // Create the diagnostic.
424 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
425
426 if (Loc::IsLocType(VD->getType())) {
427 std::string msg = "'" + std::string(VD->getNameAsString()) +
428 "' now aliases '" + MostRecent->getNameAsString() + "'";
429
430 PD.push_front(new PathDiagnosticEventPiece(L, msg));
431 }
432
433 return true;
434 }
435};
436}
437
438static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
439 const Stmt* S,
440 SymbolRef Sym, BugReporter& BR,
441 PathDiagnostic& PD) {
442
443 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
444 const GRState* PrevSt = Pred ? Pred->getState() : 0;
445
446 if (!PrevSt)
447 return;
448
449 // Look at the region bindings of the current state that map to the
450 // specified symbol. Are any of them not in the previous state?
451 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
452 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
453 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
454}
455
456namespace {
457class VISIBILITY_HIDDEN ScanNotableSymbols
458: public StoreManager::BindingsHandler {
459
460 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
461 const ExplodedNode<GRState>* N;
Ted Kremenek5f85e172009-07-22 22:35:28 +0000462 const Stmt* S;
Ted Kremenek31061982009-03-31 23:00:32 +0000463 GRBugReporter& BR;
464 PathDiagnostic& PD;
465
466public:
Ted Kremenek5f85e172009-07-22 22:35:28 +0000467 ScanNotableSymbols(const ExplodedNode<GRState>* n, const Stmt* s,
468 GRBugReporter& br, PathDiagnostic& pd)
Ted Kremenek31061982009-03-31 23:00:32 +0000469 : N(n), S(s), BR(br), PD(pd) {}
470
471 bool HandleBinding(StoreManager& SMgr, Store store,
472 const MemRegion* R, SVal V) {
473
474 SymbolRef ScanSym = V.getAsSymbol();
475
476 if (!ScanSym)
477 return true;
478
479 if (!BR.isNotable(ScanSym))
480 return true;
481
482 if (AlreadyProcessed.count(ScanSym))
483 return true;
484
485 AlreadyProcessed.insert(ScanSym);
486
487 HandleNotableSymbol(N, S, ScanSym, BR, PD);
488 return true;
489 }
490};
491} // end anonymous namespace
492
493//===----------------------------------------------------------------------===//
494// "Minimal" path diagnostic generation algorithm.
495//===----------------------------------------------------------------------===//
496
Ted Kremenek14856d72009-04-06 23:06:54 +0000497static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
498
Ted Kremenek31061982009-03-31 23:00:32 +0000499static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
500 PathDiagnosticBuilder &PDB,
501 const ExplodedNode<GRState> *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000502
Ted Kremenek31061982009-03-31 23:00:32 +0000503 SourceManager& SMgr = PDB.getSourceManager();
504 const ExplodedNode<GRState>* NextNode = N->pred_empty()
505 ? NULL : *(N->pred_begin());
506 while (NextNode) {
507 N = NextNode;
508 NextNode = GetPredecessorNode(N);
509
510 ProgramPoint P = N->getLocation();
511
512 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
513 CFGBlock* Src = BE->getSrc();
514 CFGBlock* Dst = BE->getDst();
515 Stmt* T = Src->getTerminator();
516
517 if (!T)
518 continue;
519
520 FullSourceLoc Start(T->getLocStart(), SMgr);
521
522 switch (T->getStmtClass()) {
523 default:
524 break;
525
526 case Stmt::GotoStmtClass:
527 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000528 const Stmt* S = GetNextStmt(N);
Ted Kremenek31061982009-03-31 23:00:32 +0000529
530 if (!S)
531 continue;
532
533 std::string sbuf;
534 llvm::raw_string_ostream os(sbuf);
535 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
536
537 os << "Control jumps to line "
538 << End.asLocation().getInstantiationLineNumber();
539 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
540 os.str()));
541 break;
542 }
543
544 case Stmt::SwitchStmtClass: {
545 // Figure out what case arm we took.
546 std::string sbuf;
547 llvm::raw_string_ostream os(sbuf);
548
549 if (Stmt* S = Dst->getLabel()) {
550 PathDiagnosticLocation End(S, SMgr);
551
552 switch (S->getStmtClass()) {
553 default:
554 os << "No cases match in the switch statement. "
555 "Control jumps to line "
556 << End.asLocation().getInstantiationLineNumber();
557 break;
558 case Stmt::DefaultStmtClass:
559 os << "Control jumps to the 'default' case at line "
560 << End.asLocation().getInstantiationLineNumber();
561 break;
562
563 case Stmt::CaseStmtClass: {
564 os << "Control jumps to 'case ";
565 CaseStmt* Case = cast<CaseStmt>(S);
566 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
567
568 // Determine if it is an enum.
569 bool GetRawInt = true;
570
571 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
572 // FIXME: Maybe this should be an assertion. Are there cases
573 // were it is not an EnumConstantDecl?
574 EnumConstantDecl* D =
575 dyn_cast<EnumConstantDecl>(DR->getDecl());
576
577 if (D) {
578 GetRawInt = false;
579 os << D->getNameAsString();
580 }
581 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000582
583 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000584 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000585
Ted Kremenek31061982009-03-31 23:00:32 +0000586 os << ":' at line "
587 << End.asLocation().getInstantiationLineNumber();
588 break;
589 }
590 }
591 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
592 os.str()));
593 }
594 else {
595 os << "'Default' branch taken. ";
596 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
597 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
598 os.str()));
599 }
600
601 break;
602 }
603
604 case Stmt::BreakStmtClass:
605 case Stmt::ContinueStmtClass: {
606 std::string sbuf;
607 llvm::raw_string_ostream os(sbuf);
608 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
609 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
610 os.str()));
611 break;
612 }
613
614 // Determine control-flow for ternary '?'.
615 case Stmt::ConditionalOperatorClass: {
616 std::string sbuf;
617 llvm::raw_string_ostream os(sbuf);
618 os << "'?' condition is ";
619
620 if (*(Src->succ_begin()+1) == Dst)
621 os << "false";
622 else
623 os << "true";
624
625 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
626
627 if (const Stmt *S = End.asStmt())
628 End = PDB.getEnclosingStmtLocation(S);
629
630 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
631 os.str()));
632 break;
633 }
634
635 // Determine control-flow for short-circuited '&&' and '||'.
636 case Stmt::BinaryOperatorClass: {
637 if (!PDB.supportsLogicalOpControlFlow())
638 break;
639
640 BinaryOperator *B = cast<BinaryOperator>(T);
641 std::string sbuf;
642 llvm::raw_string_ostream os(sbuf);
643 os << "Left side of '";
644
645 if (B->getOpcode() == BinaryOperator::LAnd) {
646 os << "&&" << "' is ";
647
648 if (*(Src->succ_begin()+1) == Dst) {
649 os << "false";
650 PathDiagnosticLocation End(B->getLHS(), SMgr);
651 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
652 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
653 os.str()));
654 }
655 else {
656 os << "true";
657 PathDiagnosticLocation Start(B->getLHS(), SMgr);
658 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
659 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
660 os.str()));
661 }
662 }
663 else {
664 assert(B->getOpcode() == BinaryOperator::LOr);
665 os << "||" << "' is ";
666
667 if (*(Src->succ_begin()+1) == Dst) {
668 os << "false";
669 PathDiagnosticLocation Start(B->getLHS(), SMgr);
670 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
671 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
672 os.str()));
673 }
674 else {
675 os << "true";
676 PathDiagnosticLocation End(B->getLHS(), SMgr);
677 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
678 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
679 os.str()));
680 }
681 }
682
683 break;
684 }
685
686 case Stmt::DoStmtClass: {
687 if (*(Src->succ_begin()) == Dst) {
688 std::string sbuf;
689 llvm::raw_string_ostream os(sbuf);
690
691 os << "Loop condition is true. ";
692 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
693
694 if (const Stmt *S = End.asStmt())
695 End = PDB.getEnclosingStmtLocation(S);
696
697 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
698 os.str()));
699 }
700 else {
701 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
702
703 if (const Stmt *S = End.asStmt())
704 End = PDB.getEnclosingStmtLocation(S);
705
706 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
707 "Loop condition is false. Exiting loop"));
708 }
709
710 break;
711 }
712
713 case Stmt::WhileStmtClass:
714 case Stmt::ForStmtClass: {
715 if (*(Src->succ_begin()+1) == Dst) {
716 std::string sbuf;
717 llvm::raw_string_ostream os(sbuf);
718
719 os << "Loop condition is false. ";
720 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
721 if (const Stmt *S = End.asStmt())
722 End = PDB.getEnclosingStmtLocation(S);
723
724 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
725 os.str()));
726 }
727 else {
728 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
729 if (const Stmt *S = End.asStmt())
730 End = PDB.getEnclosingStmtLocation(S);
731
732 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000733 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000734 }
735
736 break;
737 }
738
739 case Stmt::IfStmtClass: {
740 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
741
742 if (const Stmt *S = End.asStmt())
743 End = PDB.getEnclosingStmtLocation(S);
744
745 if (*(Src->succ_begin()+1) == Dst)
746 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000747 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000748 else
749 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000750 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000751
752 break;
753 }
754 }
755 }
756
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000757 if (NextNode) {
758 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
759 E = PDB.visitor_end(); I!=E; ++I) {
760 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
761 PD.push_front(p);
762 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000763 }
Ted Kremenek31061982009-03-31 23:00:32 +0000764
765 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
766 // Scan the region bindings, and see if a "notable" symbol has a new
767 // lval binding.
768 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
769 PDB.getStateManager().iterBindings(N->getState(), SNS);
770 }
771 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000772
773 // After constructing the full PathDiagnostic, do a pass over it to compact
774 // PathDiagnosticPieces that occur within a macro.
775 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000776}
777
778//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000779// "Extensive" PathDiagnostic generation.
780//===----------------------------------------------------------------------===//
781
782static bool IsControlFlowExpr(const Stmt *S) {
783 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000784
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000785 if (!E)
786 return false;
787
788 E = E->IgnoreParenCasts();
789
790 if (isa<ConditionalOperator>(E))
791 return true;
792
793 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
794 if (B->isLogicalOp())
795 return true;
796
797 return false;
798}
799
Ted Kremenek14856d72009-04-06 23:06:54 +0000800namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000801class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
802 bool IsDead;
803public:
804 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
805 : PathDiagnosticLocation(L), IsDead(isdead) {}
806
807 void markDead() { IsDead = true; }
808 bool isDead() const { return IsDead; }
809};
810
Ted Kremenek14856d72009-04-06 23:06:54 +0000811class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000812 std::vector<ContextLocation> CLocs;
813 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000814 PathDiagnostic &PD;
815 PathDiagnosticBuilder &PDB;
816 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000817
818 bool IsConsumedExpr(const PathDiagnosticLocation &L);
819
Ted Kremenek14856d72009-04-06 23:06:54 +0000820 bool containsLocation(const PathDiagnosticLocation &Container,
821 const PathDiagnosticLocation &Containee);
822
823 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000824
Ted Kremenek9650cf32009-05-11 21:42:34 +0000825 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
826 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000827 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000828 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000829 while (1) {
830 // Adjust the location for some expressions that are best referenced
831 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000832 switch (S->getStmtClass()) {
833 default:
834 break;
835 case Stmt::ParenExprClass:
836 S = cast<ParenExpr>(S)->IgnoreParens();
837 firstCharOnly = true;
838 continue;
839 case Stmt::ConditionalOperatorClass:
840 S = cast<ConditionalOperator>(S)->getCond();
841 firstCharOnly = true;
842 continue;
843 case Stmt::ChooseExprClass:
844 S = cast<ChooseExpr>(S)->getCond();
845 firstCharOnly = true;
846 continue;
847 case Stmt::BinaryOperatorClass:
848 S = cast<BinaryOperator>(S)->getLHS();
849 firstCharOnly = true;
850 continue;
851 }
852
853 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000854 }
855
Ted Kremenek9650cf32009-05-11 21:42:34 +0000856 if (S != Original)
857 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000858 }
859
Ted Kremenek9650cf32009-05-11 21:42:34 +0000860 if (firstCharOnly)
861 L = PathDiagnosticLocation(L.asLocation());
862
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000863 return L;
864 }
865
Ted Kremenek14856d72009-04-06 23:06:54 +0000866 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000867 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000868 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000869 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000870 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000871 CLocs.pop_back();
872 }
873
874 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
875
876public:
877 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
878 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000879
880 // If the PathDiagnostic already has pieces, add the enclosing statement
881 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000882 if (!PD.empty()) {
883 PrevLoc = PD.begin()->getLocation();
884
885 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000886 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000887 }
888 }
889
890 ~EdgeBuilder() {
891 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000892
893 // Finally, add an initial edge from the start location of the first
894 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000895 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
896 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000897 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000898 if (!CS->body_empty()) {
899 SourceLocation Loc = (*CS->body_begin())->getLocStart();
900 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
901 }
902
Ted Kremenek14856d72009-04-06 23:06:54 +0000903 }
904
905 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
906
907 void addEdge(const Stmt *S, bool alwaysAdd = false) {
908 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
909 }
910
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000911 void rawAddEdge(PathDiagnosticLocation NewLoc);
912
Ted Kremenek14856d72009-04-06 23:06:54 +0000913 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000914 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000915};
916} // end anonymous namespace
917
918
919PathDiagnosticLocation
920EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
921 if (const Stmt *S = L.asStmt()) {
922 if (IsControlFlowExpr(S))
923 return L;
924
925 return PDB.getEnclosingStmtLocation(S);
926 }
927
928 return L;
929}
930
931bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
932 const PathDiagnosticLocation &Containee) {
933
934 if (Container == Containee)
935 return true;
936
937 if (Container.asDecl())
938 return true;
939
940 if (const Stmt *S = Containee.asStmt())
941 if (const Stmt *ContainerS = Container.asStmt()) {
942 while (S) {
943 if (S == ContainerS)
944 return true;
945 S = PDB.getParent(S);
946 }
947 return false;
948 }
949
950 // Less accurate: compare using source ranges.
951 SourceRange ContainerR = Container.asRange();
952 SourceRange ContaineeR = Containee.asRange();
953
954 SourceManager &SM = PDB.getSourceManager();
955 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
956 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
957 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
958 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
959
960 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
961 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
962 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
963 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
964
965 assert(ContainerBegLine <= ContainerEndLine);
966 assert(ContaineeBegLine <= ContaineeEndLine);
967
968 return (ContainerBegLine <= ContaineeBegLine &&
969 ContainerEndLine >= ContaineeEndLine &&
970 (ContainerBegLine != ContaineeBegLine ||
971 SM.getInstantiationColumnNumber(ContainerRBeg) <=
972 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
973 (ContainerEndLine != ContaineeEndLine ||
974 SM.getInstantiationColumnNumber(ContainerREnd) >=
975 SM.getInstantiationColumnNumber(ContainerREnd)));
976}
977
978PathDiagnosticLocation
979EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
980 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
981 return PathDiagnosticLocation(E->IgnoreParenCasts(),
982 PDB.getSourceManager());
983 return L;
984}
985
986void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
987 if (!PrevLoc.isValid()) {
988 PrevLoc = NewLoc;
989 return;
990 }
991
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000992 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
993 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
994
995 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +0000996 return;
997
998 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000999 if (NewLocClean.asLocation().getInstantiationLoc() ==
1000 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001001 return;
1002
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001003 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1004 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001005}
1006
1007void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001008
1009 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1010 return;
1011
Ted Kremenek14856d72009-04-06 23:06:54 +00001012 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1013
1014 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001015 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001016
1017 // Is the top location context the same as the one for the new location?
1018 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001019 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001020 if (IsConsumedExpr(TopContextLoc) &&
1021 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001022 TopContextLoc.markDead();
1023
Ted Kremenek14856d72009-04-06 23:06:54 +00001024 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001025 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001026
1027 return;
1028 }
1029
1030 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001031 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001032 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001033
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001034 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001035 CLocs.push_back(ContextLocation(CLoc, true));
1036 return;
1037 }
1038 }
1039
Ted Kremenek14856d72009-04-06 23:06:54 +00001040 CLocs.push_back(CLoc);
1041 return;
1042 }
1043
1044 // Context does not contain the location. Flush it.
1045 popLocation();
1046 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001047
1048 // If we reach here, there is no enclosing context. Just add the edge.
1049 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001050}
1051
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001052bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1053 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1054 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1055
1056 return false;
1057}
1058
Ted Kremeneke1baed32009-05-05 23:13:38 +00001059void EdgeBuilder::addExtendedContext(const Stmt *S) {
1060 if (!S)
1061 return;
1062
1063 const Stmt *Parent = PDB.getParent(S);
1064 while (Parent) {
1065 if (isa<CompoundStmt>(Parent))
1066 Parent = PDB.getParent(Parent);
1067 else
1068 break;
1069 }
1070
1071 if (Parent) {
1072 switch (Parent->getStmtClass()) {
1073 case Stmt::DoStmtClass:
1074 case Stmt::ObjCAtSynchronizedStmtClass:
1075 addContext(Parent);
1076 default:
1077 break;
1078 }
1079 }
1080
1081 addContext(S);
1082}
1083
Ted Kremenek14856d72009-04-06 23:06:54 +00001084void EdgeBuilder::addContext(const Stmt *S) {
1085 if (!S)
1086 return;
1087
1088 PathDiagnosticLocation L(S, PDB.getSourceManager());
1089
1090 while (!CLocs.empty()) {
1091 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1092
1093 // Is the top location context the same as the one for the new location?
1094 if (TopContextLoc == L)
1095 return;
1096
1097 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001098 CLocs.push_back(L);
1099 return;
1100 }
1101
1102 // Context does not contain the location. Flush it.
1103 popLocation();
1104 }
1105
1106 CLocs.push_back(L);
1107}
1108
1109static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1110 PathDiagnosticBuilder &PDB,
1111 const ExplodedNode<GRState> *N) {
1112
1113
1114 EdgeBuilder EB(PD, PDB);
1115
1116 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1117 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001118 while (NextNode) {
1119 N = NextNode;
1120 NextNode = GetPredecessorNode(N);
1121 ProgramPoint P = N->getLocation();
1122
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001123 do {
1124 // Block edges.
1125 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1126 const CFGBlock &Blk = *BE->getSrc();
1127 const Stmt *Term = Blk.getTerminator();
1128
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001129 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001130 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001131 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001132 const CompoundStmt *CS = NULL;
1133
1134 if (!Term) {
1135 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1136 CS = dyn_cast<CompoundStmt>(FS->getBody());
1137 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1138 CS = dyn_cast<CompoundStmt>(WS->getBody());
1139 }
1140
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001141 PathDiagnosticEventPiece *p =
1142 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001143 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001144
1145 EB.addEdge(p->getLocation(), true);
1146 PD.push_front(p);
1147
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001148 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001149 PathDiagnosticLocation BL(CS->getRBracLoc(),
1150 PDB.getSourceManager());
1151 BL = PathDiagnosticLocation(BL.asLocation());
1152 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001153 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001154 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001155
1156 if (Term)
1157 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001158
1159 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001160 }
1161
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001162 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1163 if (const Stmt* S = BE->getFirstStmt()) {
1164 if (IsControlFlowExpr(S)) {
1165 // Add the proper context for '&&', '||', and '?'.
1166 EB.addContext(S);
1167 }
1168 else
1169 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1170 }
1171
1172 break;
1173 }
1174 } while (0);
1175
1176 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001177 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001178
Ted Kremenek8966bc12009-05-06 21:39:49 +00001179 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1180 E = PDB.visitor_end(); I!=E; ++I) {
1181 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1182 const PathDiagnosticLocation &Loc = p->getLocation();
1183 EB.addEdge(Loc, true);
1184 PD.push_front(p);
1185 if (const Stmt *S = Loc.asStmt())
1186 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1187 }
1188 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001189 }
1190}
1191
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001192//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001193// Methods for BugType and subclasses.
1194//===----------------------------------------------------------------------===//
1195BugType::~BugType() {}
1196void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001197
Ted Kremenekcf118d42009-02-04 23:49:09 +00001198//===----------------------------------------------------------------------===//
1199// Methods for BugReport and subclasses.
1200//===----------------------------------------------------------------------===//
1201BugReport::~BugReport() {}
1202RangedBugReport::~RangedBugReport() {}
1203
Ted Kremenek5f85e172009-07-22 22:35:28 +00001204const Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001205 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001206 const Stmt *S = NULL;
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001207
Ted Kremenekcf118d42009-02-04 23:49:09 +00001208 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001209 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001210 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001211 if (!S)
1212 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001213
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001214 return S;
1215}
1216
1217PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001218BugReport::getEndPath(BugReporterContext& BRC,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001219 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001220
Ted Kremenek5f85e172009-07-22 22:35:28 +00001221 const Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001222
1223 if (!S)
1224 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001225
Ted Kremenekde7161f2008-04-03 18:00:37 +00001226 const SourceRange *Beg, *End;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001227 getRanges(BRC.getBugReporter(), Beg, End);
1228 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001229
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001230 // Only add the statement itself as a range if we didn't specify any
1231 // special ranges for this report.
1232 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1233 Beg == End);
1234
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001235 for (; Beg != End; ++Beg)
1236 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001237
1238 return P;
1239}
1240
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001241void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1242 const SourceRange*& end) {
1243
Ted Kremenek5f85e172009-07-22 22:35:28 +00001244 if (const Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001245 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001246 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001247 beg = &R;
1248 end = beg+1;
1249 }
1250 else
1251 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001252}
1253
Ted Kremenekcf118d42009-02-04 23:49:09 +00001254SourceLocation BugReport::getLocation() const {
1255 if (EndNode)
Ted Kremenek5f85e172009-07-22 22:35:28 +00001256 if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001257 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5f85e172009-07-22 22:35:28 +00001258 if (const MemberExpr* ME = dyn_cast<MemberExpr>(S))
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001259 return ME->getMemberLoc();
1260
Ted Kremenekcf118d42009-02-04 23:49:09 +00001261 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001262 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001263
1264 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001265}
1266
Ted Kremenek3148eb42009-01-24 00:55:43 +00001267PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1268 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001269 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001270 return NULL;
1271}
1272
Ted Kremenekcf118d42009-02-04 23:49:09 +00001273//===----------------------------------------------------------------------===//
1274// Methods for BugReporter and subclasses.
1275//===----------------------------------------------------------------------===//
1276
1277BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001278 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001279}
1280
1281GRBugReporter::~GRBugReporter() { FlushReports(); }
1282BugReporterData::~BugReporterData() {}
1283
1284ExplodedGraph<GRState>&
1285GRBugReporter::getGraph() { return Eng.getGraph(); }
1286
1287GRStateManager&
1288GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1289
1290BugReporter::~BugReporter() { FlushReports(); }
1291
1292void BugReporter::FlushReports() {
1293 if (BugTypes.isEmpty())
1294 return;
1295
1296 // First flush the warnings for each BugType. This may end up creating new
1297 // warnings and new BugTypes. Because ImmutableSet is a functional data
1298 // structure, we do not need to worry about the iterators being invalidated.
1299 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1300 const_cast<BugType*>(*I)->FlushReports(*this);
1301
1302 // Iterate through BugTypes a second time. BugTypes may have been updated
1303 // with new BugType objects and new warnings.
1304 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1305 BugType *BT = const_cast<BugType*>(*I);
1306
1307 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1308 SetTy& EQClasses = BT->EQClasses;
1309
1310 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1311 BugReportEquivClass& EQ = *EI;
1312 FlushReport(EQ);
1313 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001314
Ted Kremenekcf118d42009-02-04 23:49:09 +00001315 // Delete the BugType object. This will also delete the equivalence
1316 // classes.
1317 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001318 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001319
1320 // Remove all references to the BugType objects.
1321 BugTypes = F.GetEmptySet();
1322}
1323
1324//===----------------------------------------------------------------------===//
1325// PathDiagnostics generation.
1326//===----------------------------------------------------------------------===//
1327
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001328static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001329 std::pair<ExplodedNode<GRState>*, unsigned> >
1330MakeReportGraph(const ExplodedGraph<GRState>* G,
1331 const ExplodedNode<GRState>** NStart,
1332 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001333
Ted Kremenekcf118d42009-02-04 23:49:09 +00001334 // Create the trimmed graph. It will contain the shortest paths from the
1335 // error nodes to the root. In the new graph we should only have one
1336 // error node unless there are two or more error nodes with the same minimum
1337 // path length.
1338 ExplodedGraph<GRState>* GTrim;
1339 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001340
1341 llvm::DenseMap<const void*, const void*> InverseMap;
1342 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001343
1344 // Create owning pointers for GTrim and NMap just to ensure that they are
1345 // released when this function exists.
1346 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1347 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1348
1349 // Find the (first) error node in the trimmed graph. We just need to consult
1350 // the node map (NMap) which maps from nodes in the original graph to nodes
1351 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001352
1353 std::queue<const ExplodedNode<GRState>*> WS;
1354 typedef llvm::DenseMap<const ExplodedNode<GRState>*,unsigned> IndexMapTy;
1355 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001356
1357 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
Ted Kremenek938332c2009-05-16 01:11:58 +00001358 if (const ExplodedNode<GRState> *N = NMap->getMappedNode(*I)) {
1359 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1360 WS.push(N);
1361 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001362 }
1363
Ted Kremenek938332c2009-05-16 01:11:58 +00001364 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001365
1366 // Create a new (third!) graph with a single path. This is the graph
1367 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001368 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001369 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1370 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001371
Ted Kremenek10aa5542009-03-12 23:41:59 +00001372 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001373 // to the root node, and then construct a new graph that contains only
1374 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001375 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001376
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001377 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001378 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001379
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001380 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001381 const ExplodedNode<GRState>* Node = WS.front();
1382 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001383
1384 if (Visited.find(Node) != Visited.end())
1385 continue;
1386
1387 Visited[Node] = cnt++;
1388
1389 if (Node->pred_empty()) {
1390 Root = Node;
1391 break;
1392 }
1393
Ted Kremenek3148eb42009-01-24 00:55:43 +00001394 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001395 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001396 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001397 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001398
Ted Kremenek938332c2009-05-16 01:11:58 +00001399 assert(Root);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001400
Ted Kremenek10aa5542009-03-12 23:41:59 +00001401 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001402 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001403 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001404 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001405 unsigned NodeIndex = 0;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001406
Ted Kremenek938332c2009-05-16 01:11:58 +00001407 for ( const ExplodedNode<GRState> *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001408 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001409 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001410 assert(I != Visited.end());
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001411
1412 // Create the equivalent node in the new graph with the same state
1413 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001414 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001415 GNew->getNode(N->getLocation(), N->getState());
1416
1417 // Store the mapping to the original node.
1418 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1419 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1420 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001421
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001422 // Link up the new node with the previous node.
1423 if (Last)
1424 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001425
1426 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001427
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001428 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001429 IndexMapTy::iterator IMI =
1430 IndexMap.find((const ExplodedNode<GRState>*)(IMitr->second));
1431 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001432 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001433 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001434 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001435 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001436
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001437 // Find the next successor node. We choose the node that is marked
1438 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001439 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1440 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001441 N = 0;
1442
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001443 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001444
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001445 I = Visited.find(*SI);
1446
1447 if (I == Visited.end())
1448 continue;
1449
1450 if (!N || I->second < MinVal) {
1451 N = *SI;
1452 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001453 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001454 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001455
Ted Kremenek938332c2009-05-16 01:11:58 +00001456 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001457 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001458
Ted Kremenek938332c2009-05-16 01:11:58 +00001459 assert(First);
1460
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001461 return std::make_pair(std::make_pair(GNew, BM),
1462 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001463}
1464
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001465/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1466/// and collapses PathDiagosticPieces that are expanded by macros.
1467static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1468 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1469 MacroStackTy;
1470
1471 typedef std::vector<PathDiagnosticPiece*>
1472 PiecesTy;
1473
1474 MacroStackTy MacroStack;
1475 PiecesTy Pieces;
1476
1477 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1478 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001479 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001480
1481 // Determine the instantiation location, which is the location we group
1482 // related PathDiagnosticPieces.
1483 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1484 SM.getInstantiationLoc(Loc) :
1485 SourceLocation();
1486
1487 if (Loc.isFileID()) {
1488 MacroStack.clear();
1489 Pieces.push_back(&*I);
1490 continue;
1491 }
1492
1493 assert(Loc.isMacroID());
1494
1495 // Is the PathDiagnosticPiece within the same macro group?
1496 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1497 MacroStack.back().first->push_back(&*I);
1498 continue;
1499 }
1500
1501 // We aren't in the same group. Are we descending into a new macro
1502 // or are part of an old one?
1503 PathDiagnosticMacroPiece *MacroGroup = 0;
1504
1505 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1506 SM.getInstantiationLoc(Loc) :
1507 SourceLocation();
1508
1509 // Walk the entire macro stack.
1510 while (!MacroStack.empty()) {
1511 if (InstantiationLoc == MacroStack.back().second) {
1512 MacroGroup = MacroStack.back().first;
1513 break;
1514 }
1515
1516 if (ParentInstantiationLoc == MacroStack.back().second) {
1517 MacroGroup = MacroStack.back().first;
1518 break;
1519 }
1520
1521 MacroStack.pop_back();
1522 }
1523
1524 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1525 // Create a new macro group and add it to the stack.
1526 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1527
1528 if (MacroGroup)
1529 MacroGroup->push_back(NewGroup);
1530 else {
1531 assert(InstantiationLoc.isFileID());
1532 Pieces.push_back(NewGroup);
1533 }
1534
1535 MacroGroup = NewGroup;
1536 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1537 }
1538
1539 // Finally, add the PathDiagnosticPiece to the group.
1540 MacroGroup->push_back(&*I);
1541 }
1542
1543 // Now take the pieces and construct a new PathDiagnostic.
1544 PD.resetPath(false);
1545
1546 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1547 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1548 if (!MP->containsEvent()) {
1549 delete MP;
1550 continue;
1551 }
1552
1553 PD.push_back(*I);
1554 }
1555}
1556
Ted Kremenek7dc86642009-03-31 20:22:36 +00001557void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001558 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001559
1560 std::vector<const ExplodedNode<GRState>*> Nodes;
1561
Ted Kremenekcf118d42009-02-04 23:49:09 +00001562 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1563 const ExplodedNode<GRState>* N = I->getEndNode();
1564 if (N) Nodes.push_back(N);
1565 }
1566
1567 if (Nodes.empty())
1568 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001569
1570 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001571 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001572 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001573 std::pair<ExplodedNode<GRState>*, unsigned> >&
1574 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001575
Ted Kremenekcf118d42009-02-04 23:49:09 +00001576 // Find the BugReport with the original location.
1577 BugReport *R = 0;
1578 unsigned i = 0;
1579 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1580 if (i == GPair.second.second) { R = *I; break; }
1581
1582 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001583
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001584 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1585 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001586 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001587
Ted Kremenek8966bc12009-05-06 21:39:49 +00001588 // Start building the path diagnostic...
1589 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1590
1591 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001592 PD.push_back(Piece);
1593 else
1594 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001595
1596 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001597
Ted Kremenek7dc86642009-03-31 20:22:36 +00001598 switch (PDB.getGenerationScheme()) {
1599 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001600 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001601 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001602 case PathDiagnosticClient::Minimal:
1603 GenerateMinimalPathDiagnostic(PD, PDB, N);
1604 break;
1605 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001606}
1607
Ted Kremenekcf118d42009-02-04 23:49:09 +00001608void BugReporter::Register(BugType *BT) {
1609 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001610}
1611
Ted Kremenekcf118d42009-02-04 23:49:09 +00001612void BugReporter::EmitReport(BugReport* R) {
1613 // Compute the bug report's hash to determine its equivalence class.
1614 llvm::FoldingSetNodeID ID;
1615 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001616
Ted Kremenekcf118d42009-02-04 23:49:09 +00001617 // Lookup the equivance class. If there isn't one, create it.
1618 BugType& BT = R->getBugType();
1619 Register(&BT);
1620 void *InsertPos;
1621 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1622
1623 if (!EQ) {
1624 EQ = new BugReportEquivClass(R);
1625 BT.EQClasses.InsertNode(EQ, InsertPos);
1626 }
1627 else
1628 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001629}
1630
Ted Kremenekcf118d42009-02-04 23:49:09 +00001631void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1632 assert(!EQ.Reports.empty());
1633 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001634 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001635
1636 // FIXME: Make sure we use the 'R' for the path that was actually used.
1637 // Probably doesn't make a difference in practice.
1638 BugType& BT = R.getBugType();
1639
Ted Kremenekd49967f2009-04-29 21:58:13 +00001640 llvm::OwningPtr<PathDiagnostic>
1641 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001642 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001643 ? R.getDescription() : R.getShortDescription(),
1644 BT.getCategory()));
1645
Ted Kremenekcf118d42009-02-04 23:49:09 +00001646 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001647
1648 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001649 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001650 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001651
Ted Kremenek3148eb42009-01-24 00:55:43 +00001652 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001653 const SourceRange *Beg = 0, *End = 0;
1654 R.getRanges(*this, Beg, End);
1655 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001656 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001657 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001658 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001659
Ted Kremenek3148eb42009-01-24 00:55:43 +00001660 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001661 default: assert(0 && "Don't handle this many ranges yet!");
1662 case 0: Diag.Report(L, ErrorDiag); break;
1663 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1664 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1665 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001666 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001667
1668 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1669 if (!PD)
1670 return;
1671
1672 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001673 PathDiagnosticPiece* piece =
1674 new PathDiagnosticEventPiece(L, R.getDescription());
1675
Ted Kremenek3148eb42009-01-24 00:55:43 +00001676 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1677 D->push_back(piece);
1678 }
1679
1680 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001681}
Ted Kremenek57202072008-07-14 17:40:50 +00001682
Ted Kremenek8c036c72008-09-20 04:23:38 +00001683void BugReporter::EmitBasicReport(const char* name, const char* str,
1684 SourceLocation Loc,
1685 SourceRange* RBeg, unsigned NumRanges) {
1686 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1687}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001688
Ted Kremenek8c036c72008-09-20 04:23:38 +00001689void BugReporter::EmitBasicReport(const char* name, const char* category,
1690 const char* str, SourceLocation Loc,
1691 SourceRange* RBeg, unsigned NumRanges) {
1692
Ted Kremenekcf118d42009-02-04 23:49:09 +00001693 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1694 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001695 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001696 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1697 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1698 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001699}