blob: 19a031a1ae93db7bc002c4970ed73d01529ccb42 [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
Zhongxing Xuc5619d92009-08-06 01:32:16 +000052static inline const ExplodedNode*
53GetPredecessorNode(const ExplodedNode* 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
Zhongxing Xuc5619d92009-08-06 01:32:16 +000057static inline const ExplodedNode*
58GetSuccessorNode(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000059 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Zhongxing Xuc5619d92009-08-06 01:32:16 +000062static const Stmt* GetPreviousStmt(const ExplodedNode* 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
Zhongxing Xuc5619d92009-08-06 01:32:16 +000070static const Stmt* GetNextStmt(const ExplodedNode* 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 Kremenekb7c51522009-07-28 00:07:15 +000087
88 // Some expressions don't have locations.
89 if (S->getLocStart().isInvalid())
90 continue;
91
Ted Kremenekb697b102009-02-23 22:44:26 +000092 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000093 }
Ted Kremenekb697b102009-02-23 22:44:26 +000094
95 return 0;
96}
97
Ted Kremenek5f85e172009-07-22 22:35:28 +000098static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +000099GetCurrentOrPreviousStmt(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000100 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000101 return S;
102
103 return GetPreviousStmt(N);
104}
105
Ted Kremenek5f85e172009-07-22 22:35:28 +0000106static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000107GetCurrentOrNextStmt(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000108 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000109 return S;
110
111 return GetNextStmt(N);
112}
113
114//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000115// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000116//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000117
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000118typedef llvm::DenseMap<const ExplodedNode*,
119const ExplodedNode*> NodeBackMap;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000120
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000121namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000122class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
123 NodeBackMap& M;
124public:
125 NodeMapClosure(NodeBackMap *m) : M(*m) {}
126 ~NodeMapClosure() {}
127
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000128 const ExplodedNode* getOriginalNode(const ExplodedNode* N) {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000129 NodeBackMap::iterator I = M.find(N);
130 return I == M.end() ? 0 : I->second;
131 }
132};
133
Ted Kremenek8966bc12009-05-06 21:39:49 +0000134class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000135 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000136 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000137 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000138 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000139public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000140 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000141 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000142 PathDiagnosticClient *pdc)
143 : BugReporterContext(br),
144 R(r), PDC(pdc), NMC(Backmap)
145 {
146 addVisitor(R);
147 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000148
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000149 PathDiagnosticLocation ExecutionContinues(const ExplodedNode* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000150
Ted Kremenek00605e02009-03-27 20:55:39 +0000151 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000152 const ExplodedNode* N);
Ted Kremenek00605e02009-03-27 20:55:39 +0000153
154 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000155 if (PM.get() == 0)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000156 PM.reset(new ParentMap(getCodeDecl().getBody()));
Ted Kremenek00605e02009-03-27 20:55:39 +0000157 return *PM.get();
158 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000159
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000160 const Stmt *getParent(const Stmt *S) {
161 return getParentMap().getParent(S);
162 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000163
164 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000165 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000166
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000167 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
168
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000169 PathDiagnosticLocation
170 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
171 if (const Stmt *S = L.asStmt())
172 return getEnclosingStmtLocation(S);
173
174 return L;
175 }
176
Ted Kremenek7dc86642009-03-31 20:22:36 +0000177 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
178 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
179 }
180
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000181 bool supportsLogicalOpControlFlow() const {
182 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
183 }
184};
185} // end anonymous namespace
186
Ted Kremenek00605e02009-03-27 20:55:39 +0000187PathDiagnosticLocation
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000188PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000189 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000190 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000191
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000192 return FullSourceLoc(getCodeDecl().getBodyRBrace(), getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000193}
194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000196PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000197 const ExplodedNode* N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000198
Ted Kremenek143ca222008-05-06 18:11:09 +0000199 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 if (os.str().empty())
201 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000202
Ted Kremenek00605e02009-03-27 20:55:39 +0000203 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000204
Ted Kremenek00605e02009-03-27 20:55:39 +0000205 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000206 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000207 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
208 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000209 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000210 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000211 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000212
213 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000214}
215
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000216static bool IsNested(const Stmt *S, ParentMap &PM) {
217 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
218 return true;
219
220 const Stmt *Parent = PM.getParentIgnoreParens(S);
221
222 if (Parent)
223 switch (Parent->getStmtClass()) {
224 case Stmt::ForStmtClass:
225 case Stmt::DoStmtClass:
226 case Stmt::WhileStmtClass:
227 return true;
228 default:
229 break;
230 }
231
232 return false;
233}
234
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000235PathDiagnosticLocation
236PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
237 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000238 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000239 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000240
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000241 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000242 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000243
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000244 if (!Parent)
245 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000246
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000247 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000248 case Stmt::BinaryOperatorClass: {
249 const BinaryOperator *B = cast<BinaryOperator>(Parent);
250 if (B->isLogicalOp())
251 return PathDiagnosticLocation(S, SMgr);
252 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000253 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000254 case Stmt::CompoundStmtClass:
255 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000256 return PathDiagnosticLocation(S, SMgr);
257 case Stmt::ChooseExprClass:
258 // Similar to '?' if we are referring to condition, just have the edge
259 // point to the entire choose expression.
260 if (cast<ChooseExpr>(Parent)->getCond() == S)
261 return PathDiagnosticLocation(Parent, SMgr);
262 else
263 return PathDiagnosticLocation(S, SMgr);
264 case Stmt::ConditionalOperatorClass:
265 // For '?', if we are referring to condition, just have the edge point
266 // to the entire '?' expression.
267 if (cast<ConditionalOperator>(Parent)->getCond() == S)
268 return PathDiagnosticLocation(Parent, SMgr);
269 else
270 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000271 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000272 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000273 case Stmt::ForStmtClass:
274 if (cast<ForStmt>(Parent)->getBody() == S)
275 return PathDiagnosticLocation(S, SMgr);
276 break;
277 case Stmt::IfStmtClass:
278 if (cast<IfStmt>(Parent)->getCond() != S)
279 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000280 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000281 case Stmt::ObjCForCollectionStmtClass:
282 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
283 return PathDiagnosticLocation(S, SMgr);
284 break;
285 case Stmt::WhileStmtClass:
286 if (cast<WhileStmt>(Parent)->getCond() != S)
287 return PathDiagnosticLocation(S, SMgr);
288 break;
289 default:
290 break;
291 }
292
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000293 S = Parent;
294 }
295
296 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000297
298 // Special case: DeclStmts can appear in for statement declarations, in which
299 // case the ForStmt is the context.
300 if (isa<DeclStmt>(S)) {
301 if (const Stmt *Parent = P.getParent(S)) {
302 switch (Parent->getStmtClass()) {
303 case Stmt::ForStmtClass:
304 case Stmt::ObjCForCollectionStmtClass:
305 return PathDiagnosticLocation(Parent, SMgr);
306 default:
307 break;
308 }
309 }
310 }
311 else if (isa<BinaryOperator>(S)) {
312 // Special case: the binary operator represents the initialization
313 // code in a for statement (this can happen when the variable being
314 // initialized is an old variable.
315 if (const ForStmt *FS =
316 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
317 if (FS->getInit() == S)
318 return PathDiagnosticLocation(FS, SMgr);
319 }
320 }
321
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000322 return PathDiagnosticLocation(S, SMgr);
323}
324
Ted Kremenekcf118d42009-02-04 23:49:09 +0000325//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000326// ScanNotableSymbols: closure-like callback for scanning Store bindings.
327//===----------------------------------------------------------------------===//
328
329static const VarDecl*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000330GetMostRecentVarDeclBinding(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000331 GRStateManager& VMgr, SVal X) {
332
333 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
334
335 ProgramPoint P = N->getLocation();
336
337 if (!isa<PostStmt>(P))
338 continue;
339
Ted Kremenek5f85e172009-07-22 22:35:28 +0000340 const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
Ted Kremenek31061982009-03-31 23:00:32 +0000341
342 if (!DR)
343 continue;
344
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000345 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000346
347 if (X != Y)
348 continue;
349
Ted Kremenek5f85e172009-07-22 22:35:28 +0000350 const VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
Ted Kremenek31061982009-03-31 23:00:32 +0000351
352 if (!VD)
353 continue;
354
355 return VD;
356 }
357
358 return 0;
359}
360
361namespace {
362class VISIBILITY_HIDDEN NotableSymbolHandler
363: public StoreManager::BindingsHandler {
364
365 SymbolRef Sym;
366 const GRState* PrevSt;
367 const Stmt* S;
368 GRStateManager& VMgr;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000369 const ExplodedNode* Pred;
Ted Kremenek31061982009-03-31 23:00:32 +0000370 PathDiagnostic& PD;
371 BugReporter& BR;
372
373public:
374
375 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000376 GRStateManager& vmgr, const ExplodedNode* pred,
Ted Kremenek31061982009-03-31 23:00:32 +0000377 PathDiagnostic& pd, BugReporter& br)
378 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
379
380 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
381 SVal V) {
382
383 SymbolRef ScanSym = V.getAsSymbol();
384
385 if (ScanSym != Sym)
386 return true;
387
388 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000389 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000390
391 if (X == V) // Same binding?
392 return true;
393
394 // Different binding. Only handle assignments for now. We don't pull
395 // this check out of the loop because we will eventually handle other
396 // cases.
397
398 VarDecl *VD = 0;
399
400 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
401 if (!B->isAssignmentOp())
402 return true;
403
404 // What variable did we assign to?
405 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
406
407 if (!DR)
408 return true;
409
410 VD = dyn_cast<VarDecl>(DR->getDecl());
411 }
412 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
413 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
414 // assume that each DeclStmt has a single Decl. This invariant
415 // holds by contruction in the CFG.
416 VD = dyn_cast<VarDecl>(*DS->decl_begin());
417 }
418
419 if (!VD)
420 return true;
421
422 // What is the most recently referenced variable with this binding?
423 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
424
425 if (!MostRecent)
426 return true;
427
428 // Create the diagnostic.
429 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
430
431 if (Loc::IsLocType(VD->getType())) {
432 std::string msg = "'" + std::string(VD->getNameAsString()) +
433 "' now aliases '" + MostRecent->getNameAsString() + "'";
434
435 PD.push_front(new PathDiagnosticEventPiece(L, msg));
436 }
437
438 return true;
439 }
440};
441}
442
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000443static void HandleNotableSymbol(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000444 const Stmt* S,
445 SymbolRef Sym, BugReporter& BR,
446 PathDiagnostic& PD) {
447
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000448 const ExplodedNode* Pred = N->pred_empty() ? 0 : *N->pred_begin();
Ted Kremenek31061982009-03-31 23:00:32 +0000449 const GRState* PrevSt = Pred ? Pred->getState() : 0;
450
451 if (!PrevSt)
452 return;
453
454 // Look at the region bindings of the current state that map to the
455 // specified symbol. Are any of them not in the previous state?
456 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
457 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
458 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
459}
460
461namespace {
462class VISIBILITY_HIDDEN ScanNotableSymbols
463: public StoreManager::BindingsHandler {
464
465 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000466 const ExplodedNode* N;
Ted Kremenek5f85e172009-07-22 22:35:28 +0000467 const Stmt* S;
Ted Kremenek31061982009-03-31 23:00:32 +0000468 GRBugReporter& BR;
469 PathDiagnostic& PD;
470
471public:
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000472 ScanNotableSymbols(const ExplodedNode* n, const Stmt* s,
Ted Kremenek5f85e172009-07-22 22:35:28 +0000473 GRBugReporter& br, PathDiagnostic& pd)
Ted Kremenek31061982009-03-31 23:00:32 +0000474 : N(n), S(s), BR(br), PD(pd) {}
475
476 bool HandleBinding(StoreManager& SMgr, Store store,
477 const MemRegion* R, SVal V) {
478
479 SymbolRef ScanSym = V.getAsSymbol();
480
481 if (!ScanSym)
482 return true;
483
484 if (!BR.isNotable(ScanSym))
485 return true;
486
487 if (AlreadyProcessed.count(ScanSym))
488 return true;
489
490 AlreadyProcessed.insert(ScanSym);
491
492 HandleNotableSymbol(N, S, ScanSym, BR, PD);
493 return true;
494 }
495};
496} // end anonymous namespace
497
498//===----------------------------------------------------------------------===//
499// "Minimal" path diagnostic generation algorithm.
500//===----------------------------------------------------------------------===//
501
Ted Kremenek14856d72009-04-06 23:06:54 +0000502static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
503
Ted Kremenek31061982009-03-31 23:00:32 +0000504static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
505 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000506 const ExplodedNode *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000507
Ted Kremenek31061982009-03-31 23:00:32 +0000508 SourceManager& SMgr = PDB.getSourceManager();
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000509 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000510 ? NULL : *(N->pred_begin());
511 while (NextNode) {
512 N = NextNode;
513 NextNode = GetPredecessorNode(N);
514
515 ProgramPoint P = N->getLocation();
516
517 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
518 CFGBlock* Src = BE->getSrc();
519 CFGBlock* Dst = BE->getDst();
520 Stmt* T = Src->getTerminator();
521
522 if (!T)
523 continue;
524
525 FullSourceLoc Start(T->getLocStart(), SMgr);
526
527 switch (T->getStmtClass()) {
528 default:
529 break;
530
531 case Stmt::GotoStmtClass:
532 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000533 const Stmt* S = GetNextStmt(N);
Ted Kremenek31061982009-03-31 23:00:32 +0000534
535 if (!S)
536 continue;
537
538 std::string sbuf;
539 llvm::raw_string_ostream os(sbuf);
540 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
541
542 os << "Control jumps to line "
543 << End.asLocation().getInstantiationLineNumber();
544 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
545 os.str()));
546 break;
547 }
548
549 case Stmt::SwitchStmtClass: {
550 // Figure out what case arm we took.
551 std::string sbuf;
552 llvm::raw_string_ostream os(sbuf);
553
554 if (Stmt* S = Dst->getLabel()) {
555 PathDiagnosticLocation End(S, SMgr);
556
557 switch (S->getStmtClass()) {
558 default:
559 os << "No cases match in the switch statement. "
560 "Control jumps to line "
561 << End.asLocation().getInstantiationLineNumber();
562 break;
563 case Stmt::DefaultStmtClass:
564 os << "Control jumps to the 'default' case at line "
565 << End.asLocation().getInstantiationLineNumber();
566 break;
567
568 case Stmt::CaseStmtClass: {
569 os << "Control jumps to 'case ";
570 CaseStmt* Case = cast<CaseStmt>(S);
571 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
572
573 // Determine if it is an enum.
574 bool GetRawInt = true;
575
576 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
577 // FIXME: Maybe this should be an assertion. Are there cases
578 // were it is not an EnumConstantDecl?
579 EnumConstantDecl* D =
580 dyn_cast<EnumConstantDecl>(DR->getDecl());
581
582 if (D) {
583 GetRawInt = false;
584 os << D->getNameAsString();
585 }
586 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000587
588 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000589 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000590
Ted Kremenek31061982009-03-31 23:00:32 +0000591 os << ":' at line "
592 << End.asLocation().getInstantiationLineNumber();
593 break;
594 }
595 }
596 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
597 os.str()));
598 }
599 else {
600 os << "'Default' branch taken. ";
601 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
602 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
603 os.str()));
604 }
605
606 break;
607 }
608
609 case Stmt::BreakStmtClass:
610 case Stmt::ContinueStmtClass: {
611 std::string sbuf;
612 llvm::raw_string_ostream os(sbuf);
613 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
614 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
615 os.str()));
616 break;
617 }
618
619 // Determine control-flow for ternary '?'.
620 case Stmt::ConditionalOperatorClass: {
621 std::string sbuf;
622 llvm::raw_string_ostream os(sbuf);
623 os << "'?' condition is ";
624
625 if (*(Src->succ_begin()+1) == Dst)
626 os << "false";
627 else
628 os << "true";
629
630 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
631
632 if (const Stmt *S = End.asStmt())
633 End = PDB.getEnclosingStmtLocation(S);
634
635 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
636 os.str()));
637 break;
638 }
639
640 // Determine control-flow for short-circuited '&&' and '||'.
641 case Stmt::BinaryOperatorClass: {
642 if (!PDB.supportsLogicalOpControlFlow())
643 break;
644
645 BinaryOperator *B = cast<BinaryOperator>(T);
646 std::string sbuf;
647 llvm::raw_string_ostream os(sbuf);
648 os << "Left side of '";
649
650 if (B->getOpcode() == BinaryOperator::LAnd) {
651 os << "&&" << "' is ";
652
653 if (*(Src->succ_begin()+1) == Dst) {
654 os << "false";
655 PathDiagnosticLocation End(B->getLHS(), SMgr);
656 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
657 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
658 os.str()));
659 }
660 else {
661 os << "true";
662 PathDiagnosticLocation Start(B->getLHS(), SMgr);
663 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
664 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
665 os.str()));
666 }
667 }
668 else {
669 assert(B->getOpcode() == BinaryOperator::LOr);
670 os << "||" << "' is ";
671
672 if (*(Src->succ_begin()+1) == Dst) {
673 os << "false";
674 PathDiagnosticLocation Start(B->getLHS(), SMgr);
675 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
676 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
677 os.str()));
678 }
679 else {
680 os << "true";
681 PathDiagnosticLocation End(B->getLHS(), SMgr);
682 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
683 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
684 os.str()));
685 }
686 }
687
688 break;
689 }
690
691 case Stmt::DoStmtClass: {
692 if (*(Src->succ_begin()) == Dst) {
693 std::string sbuf;
694 llvm::raw_string_ostream os(sbuf);
695
696 os << "Loop condition is true. ";
697 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
698
699 if (const Stmt *S = End.asStmt())
700 End = PDB.getEnclosingStmtLocation(S);
701
702 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
703 os.str()));
704 }
705 else {
706 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
707
708 if (const Stmt *S = End.asStmt())
709 End = PDB.getEnclosingStmtLocation(S);
710
711 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
712 "Loop condition is false. Exiting loop"));
713 }
714
715 break;
716 }
717
718 case Stmt::WhileStmtClass:
719 case Stmt::ForStmtClass: {
720 if (*(Src->succ_begin()+1) == Dst) {
721 std::string sbuf;
722 llvm::raw_string_ostream os(sbuf);
723
724 os << "Loop condition is false. ";
725 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
726 if (const Stmt *S = End.asStmt())
727 End = PDB.getEnclosingStmtLocation(S);
728
729 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
730 os.str()));
731 }
732 else {
733 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
734 if (const Stmt *S = End.asStmt())
735 End = PDB.getEnclosingStmtLocation(S);
736
737 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000738 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000739 }
740
741 break;
742 }
743
744 case Stmt::IfStmtClass: {
745 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
746
747 if (const Stmt *S = End.asStmt())
748 End = PDB.getEnclosingStmtLocation(S);
749
750 if (*(Src->succ_begin()+1) == Dst)
751 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000752 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000753 else
754 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000755 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000756
757 break;
758 }
759 }
760 }
761
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000762 if (NextNode) {
763 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
764 E = PDB.visitor_end(); I!=E; ++I) {
765 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
766 PD.push_front(p);
767 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000768 }
Ted Kremenek31061982009-03-31 23:00:32 +0000769
770 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
771 // Scan the region bindings, and see if a "notable" symbol has a new
772 // lval binding.
773 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
774 PDB.getStateManager().iterBindings(N->getState(), SNS);
775 }
776 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000777
778 // After constructing the full PathDiagnostic, do a pass over it to compact
779 // PathDiagnosticPieces that occur within a macro.
780 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000781}
782
783//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000784// "Extensive" PathDiagnostic generation.
785//===----------------------------------------------------------------------===//
786
787static bool IsControlFlowExpr(const Stmt *S) {
788 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000789
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000790 if (!E)
791 return false;
792
793 E = E->IgnoreParenCasts();
794
795 if (isa<ConditionalOperator>(E))
796 return true;
797
798 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
799 if (B->isLogicalOp())
800 return true;
801
802 return false;
803}
804
Ted Kremenek14856d72009-04-06 23:06:54 +0000805namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000806class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
807 bool IsDead;
808public:
809 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
810 : PathDiagnosticLocation(L), IsDead(isdead) {}
811
812 void markDead() { IsDead = true; }
813 bool isDead() const { return IsDead; }
814};
815
Ted Kremenek14856d72009-04-06 23:06:54 +0000816class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000817 std::vector<ContextLocation> CLocs;
818 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000819 PathDiagnostic &PD;
820 PathDiagnosticBuilder &PDB;
821 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000822
823 bool IsConsumedExpr(const PathDiagnosticLocation &L);
824
Ted Kremenek14856d72009-04-06 23:06:54 +0000825 bool containsLocation(const PathDiagnosticLocation &Container,
826 const PathDiagnosticLocation &Containee);
827
828 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000829
Ted Kremenek9650cf32009-05-11 21:42:34 +0000830 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
831 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000832 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000833 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000834 while (1) {
835 // Adjust the location for some expressions that are best referenced
836 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000837 switch (S->getStmtClass()) {
838 default:
839 break;
840 case Stmt::ParenExprClass:
841 S = cast<ParenExpr>(S)->IgnoreParens();
842 firstCharOnly = true;
843 continue;
844 case Stmt::ConditionalOperatorClass:
845 S = cast<ConditionalOperator>(S)->getCond();
846 firstCharOnly = true;
847 continue;
848 case Stmt::ChooseExprClass:
849 S = cast<ChooseExpr>(S)->getCond();
850 firstCharOnly = true;
851 continue;
852 case Stmt::BinaryOperatorClass:
853 S = cast<BinaryOperator>(S)->getLHS();
854 firstCharOnly = true;
855 continue;
856 }
857
858 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000859 }
860
Ted Kremenek9650cf32009-05-11 21:42:34 +0000861 if (S != Original)
862 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000863 }
864
Ted Kremenek9650cf32009-05-11 21:42:34 +0000865 if (firstCharOnly)
866 L = PathDiagnosticLocation(L.asLocation());
867
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000868 return L;
869 }
870
Ted Kremenek14856d72009-04-06 23:06:54 +0000871 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000872 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000873 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000874 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000875 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000876 CLocs.pop_back();
877 }
878
879 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
880
881public:
882 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
883 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000884
885 // If the PathDiagnostic already has pieces, add the enclosing statement
886 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000887 if (!PD.empty()) {
888 PrevLoc = PD.begin()->getLocation();
889
890 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000891 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000892 }
893 }
894
895 ~EdgeBuilder() {
896 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000897
898 // Finally, add an initial edge from the start location of the first
899 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000900 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
901 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000902 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000903 if (!CS->body_empty()) {
904 SourceLocation Loc = (*CS->body_begin())->getLocStart();
905 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
906 }
907
Ted Kremenek14856d72009-04-06 23:06:54 +0000908 }
909
910 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
911
912 void addEdge(const Stmt *S, bool alwaysAdd = false) {
913 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
914 }
915
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000916 void rawAddEdge(PathDiagnosticLocation NewLoc);
917
Ted Kremenek14856d72009-04-06 23:06:54 +0000918 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000919 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000920};
921} // end anonymous namespace
922
923
924PathDiagnosticLocation
925EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
926 if (const Stmt *S = L.asStmt()) {
927 if (IsControlFlowExpr(S))
928 return L;
929
930 return PDB.getEnclosingStmtLocation(S);
931 }
932
933 return L;
934}
935
936bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
937 const PathDiagnosticLocation &Containee) {
938
939 if (Container == Containee)
940 return true;
941
942 if (Container.asDecl())
943 return true;
944
945 if (const Stmt *S = Containee.asStmt())
946 if (const Stmt *ContainerS = Container.asStmt()) {
947 while (S) {
948 if (S == ContainerS)
949 return true;
950 S = PDB.getParent(S);
951 }
952 return false;
953 }
954
955 // Less accurate: compare using source ranges.
956 SourceRange ContainerR = Container.asRange();
957 SourceRange ContaineeR = Containee.asRange();
958
959 SourceManager &SM = PDB.getSourceManager();
960 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
961 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
962 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
963 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
964
965 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
966 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
967 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
968 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
969
970 assert(ContainerBegLine <= ContainerEndLine);
971 assert(ContaineeBegLine <= ContaineeEndLine);
972
973 return (ContainerBegLine <= ContaineeBegLine &&
974 ContainerEndLine >= ContaineeEndLine &&
975 (ContainerBegLine != ContaineeBegLine ||
976 SM.getInstantiationColumnNumber(ContainerRBeg) <=
977 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
978 (ContainerEndLine != ContaineeEndLine ||
979 SM.getInstantiationColumnNumber(ContainerREnd) >=
980 SM.getInstantiationColumnNumber(ContainerREnd)));
981}
982
983PathDiagnosticLocation
984EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
985 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
986 return PathDiagnosticLocation(E->IgnoreParenCasts(),
987 PDB.getSourceManager());
988 return L;
989}
990
991void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
992 if (!PrevLoc.isValid()) {
993 PrevLoc = NewLoc;
994 return;
995 }
996
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000997 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
998 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
999
1000 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001001 return;
1002
1003 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001004 if (NewLocClean.asLocation().getInstantiationLoc() ==
1005 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001006 return;
1007
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001008 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1009 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001010}
1011
1012void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001013
1014 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1015 return;
1016
Ted Kremenek14856d72009-04-06 23:06:54 +00001017 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1018
1019 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001020 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001021
1022 // Is the top location context the same as the one for the new location?
1023 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001024 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001025 if (IsConsumedExpr(TopContextLoc) &&
1026 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001027 TopContextLoc.markDead();
1028
Ted Kremenek14856d72009-04-06 23:06:54 +00001029 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001030 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001031
1032 return;
1033 }
1034
1035 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001036 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001037 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001038
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001039 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001040 CLocs.push_back(ContextLocation(CLoc, true));
1041 return;
1042 }
1043 }
1044
Ted Kremenek14856d72009-04-06 23:06:54 +00001045 CLocs.push_back(CLoc);
1046 return;
1047 }
1048
1049 // Context does not contain the location. Flush it.
1050 popLocation();
1051 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001052
1053 // If we reach here, there is no enclosing context. Just add the edge.
1054 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001055}
1056
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001057bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1058 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1059 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1060
1061 return false;
1062}
1063
Ted Kremeneke1baed32009-05-05 23:13:38 +00001064void EdgeBuilder::addExtendedContext(const Stmt *S) {
1065 if (!S)
1066 return;
1067
1068 const Stmt *Parent = PDB.getParent(S);
1069 while (Parent) {
1070 if (isa<CompoundStmt>(Parent))
1071 Parent = PDB.getParent(Parent);
1072 else
1073 break;
1074 }
1075
1076 if (Parent) {
1077 switch (Parent->getStmtClass()) {
1078 case Stmt::DoStmtClass:
1079 case Stmt::ObjCAtSynchronizedStmtClass:
1080 addContext(Parent);
1081 default:
1082 break;
1083 }
1084 }
1085
1086 addContext(S);
1087}
1088
Ted Kremenek14856d72009-04-06 23:06:54 +00001089void EdgeBuilder::addContext(const Stmt *S) {
1090 if (!S)
1091 return;
1092
1093 PathDiagnosticLocation L(S, PDB.getSourceManager());
1094
1095 while (!CLocs.empty()) {
1096 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1097
1098 // Is the top location context the same as the one for the new location?
1099 if (TopContextLoc == L)
1100 return;
1101
1102 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001103 CLocs.push_back(L);
1104 return;
1105 }
1106
1107 // Context does not contain the location. Flush it.
1108 popLocation();
1109 }
1110
1111 CLocs.push_back(L);
1112}
1113
1114static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1115 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001116 const ExplodedNode *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001117
1118
1119 EdgeBuilder EB(PD, PDB);
1120
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001121 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001122 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001123 while (NextNode) {
1124 N = NextNode;
1125 NextNode = GetPredecessorNode(N);
1126 ProgramPoint P = N->getLocation();
1127
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001128 do {
1129 // Block edges.
1130 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1131 const CFGBlock &Blk = *BE->getSrc();
1132 const Stmt *Term = Blk.getTerminator();
1133
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001134 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001135 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001136 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001137 const CompoundStmt *CS = NULL;
1138
1139 if (!Term) {
1140 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1141 CS = dyn_cast<CompoundStmt>(FS->getBody());
1142 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1143 CS = dyn_cast<CompoundStmt>(WS->getBody());
1144 }
1145
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001146 PathDiagnosticEventPiece *p =
1147 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001148 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001149
1150 EB.addEdge(p->getLocation(), true);
1151 PD.push_front(p);
1152
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001153 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001154 PathDiagnosticLocation BL(CS->getRBracLoc(),
1155 PDB.getSourceManager());
1156 BL = PathDiagnosticLocation(BL.asLocation());
1157 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001158 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001159 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001160
1161 if (Term)
1162 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001163
1164 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001165 }
1166
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001167 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1168 if (const Stmt* S = BE->getFirstStmt()) {
1169 if (IsControlFlowExpr(S)) {
1170 // Add the proper context for '&&', '||', and '?'.
1171 EB.addContext(S);
1172 }
1173 else
1174 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1175 }
1176
1177 break;
1178 }
1179 } while (0);
1180
1181 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001182 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001183
Ted Kremenek8966bc12009-05-06 21:39:49 +00001184 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1185 E = PDB.visitor_end(); I!=E; ++I) {
1186 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1187 const PathDiagnosticLocation &Loc = p->getLocation();
1188 EB.addEdge(Loc, true);
1189 PD.push_front(p);
1190 if (const Stmt *S = Loc.asStmt())
1191 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1192 }
1193 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001194 }
1195}
1196
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001197//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001198// Methods for BugType and subclasses.
1199//===----------------------------------------------------------------------===//
1200BugType::~BugType() {}
1201void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001202
Ted Kremenekcf118d42009-02-04 23:49:09 +00001203//===----------------------------------------------------------------------===//
1204// Methods for BugReport and subclasses.
1205//===----------------------------------------------------------------------===//
1206BugReport::~BugReport() {}
1207RangedBugReport::~RangedBugReport() {}
1208
Ted Kremenek5f85e172009-07-22 22:35:28 +00001209const Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001210 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001211 const Stmt *S = NULL;
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001212
Ted Kremenekcf118d42009-02-04 23:49:09 +00001213 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001214 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001215 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001216 if (!S)
1217 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001218
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001219 return S;
1220}
1221
1222PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001223BugReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001224 const ExplodedNode* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001225
Ted Kremenek5f85e172009-07-22 22:35:28 +00001226 const Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001227
1228 if (!S)
1229 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001230
Ted Kremenekde7161f2008-04-03 18:00:37 +00001231 const SourceRange *Beg, *End;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001232 getRanges(BRC.getBugReporter(), Beg, End);
1233 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001234
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001235 // Only add the statement itself as a range if we didn't specify any
1236 // special ranges for this report.
1237 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1238 Beg == End);
1239
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001240 for (; Beg != End; ++Beg)
1241 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001242
1243 return P;
1244}
1245
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001246void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1247 const SourceRange*& end) {
1248
Ted Kremenek5f85e172009-07-22 22:35:28 +00001249 if (const Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001250 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001251 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001252 beg = &R;
1253 end = beg+1;
1254 }
1255 else
1256 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001257}
1258
Ted Kremenekcf118d42009-02-04 23:49:09 +00001259SourceLocation BugReport::getLocation() const {
1260 if (EndNode)
Ted Kremenek5f85e172009-07-22 22:35:28 +00001261 if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001262 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5f85e172009-07-22 22:35:28 +00001263 if (const MemberExpr* ME = dyn_cast<MemberExpr>(S))
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001264 return ME->getMemberLoc();
1265
Ted Kremenekcf118d42009-02-04 23:49:09 +00001266 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001267 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001268
1269 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001270}
1271
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001272PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode* N,
1273 const ExplodedNode* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001274 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001275 return NULL;
1276}
1277
Ted Kremenekcf118d42009-02-04 23:49:09 +00001278//===----------------------------------------------------------------------===//
1279// Methods for BugReporter and subclasses.
1280//===----------------------------------------------------------------------===//
1281
1282BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001283 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001284}
1285
1286GRBugReporter::~GRBugReporter() { FlushReports(); }
1287BugReporterData::~BugReporterData() {}
1288
1289ExplodedGraph<GRState>&
1290GRBugReporter::getGraph() { return Eng.getGraph(); }
1291
1292GRStateManager&
1293GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1294
1295BugReporter::~BugReporter() { FlushReports(); }
1296
1297void BugReporter::FlushReports() {
1298 if (BugTypes.isEmpty())
1299 return;
1300
1301 // First flush the warnings for each BugType. This may end up creating new
1302 // warnings and new BugTypes. Because ImmutableSet is a functional data
1303 // structure, we do not need to worry about the iterators being invalidated.
1304 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1305 const_cast<BugType*>(*I)->FlushReports(*this);
1306
1307 // Iterate through BugTypes a second time. BugTypes may have been updated
1308 // with new BugType objects and new warnings.
1309 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1310 BugType *BT = const_cast<BugType*>(*I);
1311
1312 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1313 SetTy& EQClasses = BT->EQClasses;
1314
1315 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1316 BugReportEquivClass& EQ = *EI;
1317 FlushReport(EQ);
1318 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001319
Zhongxing Xud9b401c2009-07-29 08:13:37 +00001320 // Delete the BugType object.
1321
1322 // FIXME: this will *not* delete the BugReportEquivClasses, since FoldingSet
1323 // only deletes the buckets, not the nodes themselves.
Ted Kremenekcf118d42009-02-04 23:49:09 +00001324 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001325 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001326
1327 // Remove all references to the BugType objects.
1328 BugTypes = F.GetEmptySet();
1329}
1330
1331//===----------------------------------------------------------------------===//
1332// PathDiagnostics generation.
1333//===----------------------------------------------------------------------===//
1334
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001335static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001336 std::pair<ExplodedNode*, unsigned> >
Ted Kremenekcf118d42009-02-04 23:49:09 +00001337MakeReportGraph(const ExplodedGraph<GRState>* G,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001338 const ExplodedNode** NStart,
1339 const ExplodedNode** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001340
Ted Kremenekcf118d42009-02-04 23:49:09 +00001341 // Create the trimmed graph. It will contain the shortest paths from the
1342 // error nodes to the root. In the new graph we should only have one
1343 // error node unless there are two or more error nodes with the same minimum
1344 // path length.
1345 ExplodedGraph<GRState>* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001346 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001347
1348 llvm::DenseMap<const void*, const void*> InverseMap;
1349 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001350
1351 // Create owning pointers for GTrim and NMap just to ensure that they are
1352 // released when this function exists.
1353 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001354 llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001355
1356 // Find the (first) error node in the trimmed graph. We just need to consult
1357 // the node map (NMap) which maps from nodes in the original graph to nodes
1358 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001359
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001360 std::queue<const ExplodedNode*> WS;
1361 typedef llvm::DenseMap<const ExplodedNode*,unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001362 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001363
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001364 for (const ExplodedNode** I = NStart; I != NEnd; ++I)
1365 if (const ExplodedNode *N = NMap->getMappedNode(*I)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001366 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1367 WS.push(N);
1368 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001369 }
1370
Ted Kremenek938332c2009-05-16 01:11:58 +00001371 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001372
1373 // Create a new (third!) graph with a single path. This is the graph
1374 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001375 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001376 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1377 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001378
Ted Kremenek10aa5542009-03-12 23:41:59 +00001379 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001380 // to the root node, and then construct a new graph that contains only
1381 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001382 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001383
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001384 unsigned cnt = 0;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001385 const ExplodedNode* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001386
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001387 while (!WS.empty()) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001388 const ExplodedNode* Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001389 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001390
1391 if (Visited.find(Node) != Visited.end())
1392 continue;
1393
1394 Visited[Node] = cnt++;
1395
1396 if (Node->pred_empty()) {
1397 Root = Node;
1398 break;
1399 }
1400
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001401 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001402 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001403 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001404 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001405
Ted Kremenek938332c2009-05-16 01:11:58 +00001406 assert(Root);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001407
Ted Kremenek10aa5542009-03-12 23:41:59 +00001408 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001409 // with the lowest number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001410 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001411 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001412 unsigned NodeIndex = 0;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001413
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001414 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001415 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001416 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001417 assert(I != Visited.end());
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001418
1419 // Create the equivalent node in the new graph with the same state
1420 // and location.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001421 ExplodedNode* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001422 GNew->getNode(N->getLocation(), N->getState());
1423
1424 // Store the mapping to the original node.
1425 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1426 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001427 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001428
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001429 // Link up the new node with the previous node.
1430 if (Last)
1431 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001432
1433 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001434
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001435 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001436 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001437 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001438 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001439 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001440 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001441 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001442 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001443
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001444 // Find the next successor node. We choose the node that is marked
1445 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001446 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1447 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001448 N = 0;
1449
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001450 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001451
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001452 I = Visited.find(*SI);
1453
1454 if (I == Visited.end())
1455 continue;
1456
1457 if (!N || I->second < MinVal) {
1458 N = *SI;
1459 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001460 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001461 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001462
Ted Kremenek938332c2009-05-16 01:11:58 +00001463 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001464 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001465
Ted Kremenek938332c2009-05-16 01:11:58 +00001466 assert(First);
1467
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001468 return std::make_pair(std::make_pair(GNew, BM),
1469 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001470}
1471
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001472/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1473/// and collapses PathDiagosticPieces that are expanded by macros.
1474static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1475 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1476 MacroStackTy;
1477
1478 typedef std::vector<PathDiagnosticPiece*>
1479 PiecesTy;
1480
1481 MacroStackTy MacroStack;
1482 PiecesTy Pieces;
1483
1484 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1485 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001486 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001487
1488 // Determine the instantiation location, which is the location we group
1489 // related PathDiagnosticPieces.
1490 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1491 SM.getInstantiationLoc(Loc) :
1492 SourceLocation();
1493
1494 if (Loc.isFileID()) {
1495 MacroStack.clear();
1496 Pieces.push_back(&*I);
1497 continue;
1498 }
1499
1500 assert(Loc.isMacroID());
1501
1502 // Is the PathDiagnosticPiece within the same macro group?
1503 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1504 MacroStack.back().first->push_back(&*I);
1505 continue;
1506 }
1507
1508 // We aren't in the same group. Are we descending into a new macro
1509 // or are part of an old one?
1510 PathDiagnosticMacroPiece *MacroGroup = 0;
1511
1512 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1513 SM.getInstantiationLoc(Loc) :
1514 SourceLocation();
1515
1516 // Walk the entire macro stack.
1517 while (!MacroStack.empty()) {
1518 if (InstantiationLoc == MacroStack.back().second) {
1519 MacroGroup = MacroStack.back().first;
1520 break;
1521 }
1522
1523 if (ParentInstantiationLoc == MacroStack.back().second) {
1524 MacroGroup = MacroStack.back().first;
1525 break;
1526 }
1527
1528 MacroStack.pop_back();
1529 }
1530
1531 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1532 // Create a new macro group and add it to the stack.
1533 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1534
1535 if (MacroGroup)
1536 MacroGroup->push_back(NewGroup);
1537 else {
1538 assert(InstantiationLoc.isFileID());
1539 Pieces.push_back(NewGroup);
1540 }
1541
1542 MacroGroup = NewGroup;
1543 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1544 }
1545
1546 // Finally, add the PathDiagnosticPiece to the group.
1547 MacroGroup->push_back(&*I);
1548 }
1549
1550 // Now take the pieces and construct a new PathDiagnostic.
1551 PD.resetPath(false);
1552
1553 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1554 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1555 if (!MP->containsEvent()) {
1556 delete MP;
1557 continue;
1558 }
1559
1560 PD.push_back(*I);
1561 }
1562}
1563
Ted Kremenek7dc86642009-03-31 20:22:36 +00001564void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001565 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001566
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001567 std::vector<const ExplodedNode*> Nodes;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001568
Ted Kremenekcf118d42009-02-04 23:49:09 +00001569 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001570 const ExplodedNode* N = I->getEndNode();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001571 if (N) Nodes.push_back(N);
1572 }
1573
1574 if (Nodes.empty())
1575 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001576
1577 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001578 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001579 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001580 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek7dc86642009-03-31 20:22:36 +00001581 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001582
Ted Kremenekcf118d42009-02-04 23:49:09 +00001583 // Find the BugReport with the original location.
1584 BugReport *R = 0;
1585 unsigned i = 0;
1586 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1587 if (i == GPair.second.second) { R = *I; break; }
1588
1589 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001590
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001591 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1592 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001593 const ExplodedNode *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001594
Ted Kremenek8966bc12009-05-06 21:39:49 +00001595 // Start building the path diagnostic...
1596 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1597
1598 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001599 PD.push_back(Piece);
1600 else
1601 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001602
1603 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001604
Ted Kremenek7dc86642009-03-31 20:22:36 +00001605 switch (PDB.getGenerationScheme()) {
1606 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001607 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001608 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001609 case PathDiagnosticClient::Minimal:
1610 GenerateMinimalPathDiagnostic(PD, PDB, N);
1611 break;
1612 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001613}
1614
Ted Kremenekcf118d42009-02-04 23:49:09 +00001615void BugReporter::Register(BugType *BT) {
1616 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001617}
1618
Ted Kremenekcf118d42009-02-04 23:49:09 +00001619void BugReporter::EmitReport(BugReport* R) {
1620 // Compute the bug report's hash to determine its equivalence class.
1621 llvm::FoldingSetNodeID ID;
1622 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001623
Ted Kremenekcf118d42009-02-04 23:49:09 +00001624 // Lookup the equivance class. If there isn't one, create it.
1625 BugType& BT = R->getBugType();
1626 Register(&BT);
1627 void *InsertPos;
1628 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1629
1630 if (!EQ) {
1631 EQ = new BugReportEquivClass(R);
1632 BT.EQClasses.InsertNode(EQ, InsertPos);
1633 }
1634 else
1635 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001636}
1637
Ted Kremenekcf118d42009-02-04 23:49:09 +00001638void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1639 assert(!EQ.Reports.empty());
1640 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001641 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001642
1643 // FIXME: Make sure we use the 'R' for the path that was actually used.
1644 // Probably doesn't make a difference in practice.
1645 BugType& BT = R.getBugType();
1646
Ted Kremenekd49967f2009-04-29 21:58:13 +00001647 llvm::OwningPtr<PathDiagnostic>
1648 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001649 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001650 ? R.getDescription() : R.getShortDescription(),
1651 BT.getCategory()));
1652
Ted Kremenekcf118d42009-02-04 23:49:09 +00001653 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001654
1655 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001656 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001657 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001658
Ted Kremenek3148eb42009-01-24 00:55:43 +00001659 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001660 const SourceRange *Beg = 0, *End = 0;
1661 R.getRanges(*this, Beg, End);
1662 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001663 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001664 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001665 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001666
Ted Kremenek3148eb42009-01-24 00:55:43 +00001667 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001668 default: assert(0 && "Don't handle this many ranges yet!");
1669 case 0: Diag.Report(L, ErrorDiag); break;
1670 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1671 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1672 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001673 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001674
1675 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1676 if (!PD)
1677 return;
1678
1679 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001680 PathDiagnosticPiece* piece =
1681 new PathDiagnosticEventPiece(L, R.getDescription());
1682
Ted Kremenek3148eb42009-01-24 00:55:43 +00001683 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1684 D->push_back(piece);
1685 }
1686
1687 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001688}
Ted Kremenek57202072008-07-14 17:40:50 +00001689
Ted Kremenek8c036c72008-09-20 04:23:38 +00001690void BugReporter::EmitBasicReport(const char* name, const char* str,
1691 SourceLocation Loc,
1692 SourceRange* RBeg, unsigned NumRanges) {
1693 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1694}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001695
Ted Kremenek8c036c72008-09-20 04:23:38 +00001696void BugReporter::EmitBasicReport(const char* name, const char* category,
1697 const char* str, SourceLocation Loc,
1698 SourceRange* RBeg, unsigned NumRanges) {
1699
Ted Kremenekcf118d42009-02-04 23:49:09 +00001700 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1701 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001702 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001703 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1704 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1705 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001706}