blob: 745e90c38e2a8671fbf2e95f444106d3afb9b471 [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 Kremenek592362b2009-08-18 01:05:30 +000044 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
45 return SP->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
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001209const Stmt* BugReport::getStmt() 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)) {
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001214 CFGBlock &Exit = ProgP.getContext()->getCFG()->getExit();
1215 if (BE->getBlock() == &Exit)
1216 S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001217 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001218 if (!S)
1219 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001220
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001221 return S;
1222}
1223
1224PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001225BugReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001226 const ExplodedNode* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001227
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001228 const Stmt* S = getStmt();
Ted Kremenek61f3e052008-04-03 04:42:52 +00001229
1230 if (!S)
1231 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001232
Ted Kremenekde7161f2008-04-03 18:00:37 +00001233 const SourceRange *Beg, *End;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001234 getRanges(BRC.getBugReporter(), Beg, End);
1235 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001236
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001237 // Only add the statement itself as a range if we didn't specify any
1238 // special ranges for this report.
1239 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1240 Beg == End);
1241
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001242 for (; Beg != End; ++Beg)
1243 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001244
1245 return P;
1246}
1247
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001248void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1249 const SourceRange*& end) {
1250
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001251 if (const Expr* E = dyn_cast_or_null<Expr>(getStmt())) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001252 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001253 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001254 beg = &R;
1255 end = beg+1;
1256 }
1257 else
1258 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001259}
1260
Ted Kremenekcf118d42009-02-04 23:49:09 +00001261SourceLocation BugReport::getLocation() const {
1262 if (EndNode)
Ted Kremenek5f85e172009-07-22 22:35:28 +00001263 if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001264 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5f85e172009-07-22 22:35:28 +00001265 if (const MemberExpr* ME = dyn_cast<MemberExpr>(S))
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001266 return ME->getMemberLoc();
1267
Ted Kremenekcf118d42009-02-04 23:49:09 +00001268 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001269 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001270
1271 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001272}
1273
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001274PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode* N,
1275 const ExplodedNode* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001276 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001277 return NULL;
1278}
1279
Ted Kremenekcf118d42009-02-04 23:49:09 +00001280//===----------------------------------------------------------------------===//
1281// Methods for BugReporter and subclasses.
1282//===----------------------------------------------------------------------===//
1283
1284BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001285 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001286}
1287
1288GRBugReporter::~GRBugReporter() { FlushReports(); }
1289BugReporterData::~BugReporterData() {}
1290
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001291ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001292
1293GRStateManager&
1294GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1295
1296BugReporter::~BugReporter() { FlushReports(); }
1297
1298void BugReporter::FlushReports() {
1299 if (BugTypes.isEmpty())
1300 return;
1301
1302 // First flush the warnings for each BugType. This may end up creating new
1303 // warnings and new BugTypes. Because ImmutableSet is a functional data
1304 // structure, we do not need to worry about the iterators being invalidated.
1305 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1306 const_cast<BugType*>(*I)->FlushReports(*this);
1307
1308 // Iterate through BugTypes a second time. BugTypes may have been updated
1309 // with new BugType objects and new warnings.
1310 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1311 BugType *BT = const_cast<BugType*>(*I);
1312
1313 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1314 SetTy& EQClasses = BT->EQClasses;
1315
1316 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1317 BugReportEquivClass& EQ = *EI;
1318 FlushReport(EQ);
1319 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001320
Zhongxing Xud9b401c2009-07-29 08:13:37 +00001321 // Delete the BugType object.
1322
1323 // FIXME: this will *not* delete the BugReportEquivClasses, since FoldingSet
1324 // only deletes the buckets, not the nodes themselves.
Ted Kremenekcf118d42009-02-04 23:49:09 +00001325 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001326 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001327
1328 // Remove all references to the BugType objects.
1329 BugTypes = F.GetEmptySet();
1330}
1331
1332//===----------------------------------------------------------------------===//
1333// PathDiagnostics generation.
1334//===----------------------------------------------------------------------===//
1335
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001336static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001337 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001338MakeReportGraph(const ExplodedGraph* G,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001339 const ExplodedNode** NStart,
1340 const ExplodedNode** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001341
Ted Kremenekcf118d42009-02-04 23:49:09 +00001342 // Create the trimmed graph. It will contain the shortest paths from the
1343 // error nodes to the root. In the new graph we should only have one
1344 // error node unless there are two or more error nodes with the same minimum
1345 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001346 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001347 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001348
1349 llvm::DenseMap<const void*, const void*> InverseMap;
1350 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001351
1352 // Create owning pointers for GTrim and NMap just to ensure that they are
1353 // released when this function exists.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001354 llvm::OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001355 llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001356
1357 // Find the (first) error node in the trimmed graph. We just need to consult
1358 // the node map (NMap) which maps from nodes in the original graph to nodes
1359 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001360
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001361 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001362 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001363 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001364
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001365 for (const ExplodedNode** I = NStart; I != NEnd; ++I)
1366 if (const ExplodedNode *N = NMap->getMappedNode(*I)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001367 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1368 WS.push(N);
1369 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001370 }
1371
Ted Kremenek938332c2009-05-16 01:11:58 +00001372 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001373
1374 // Create a new (third!) graph with a single path. This is the graph
1375 // that will be returned to the caller.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001376 ExplodedGraph *GNew = new ExplodedGraph(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 Xu38b02b92009-08-06 06:28:40 +00001421 ExplodedNode* NewN = GNew->getNode(N->getLocation(), N->getState());
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001422
1423 // Store the mapping to the original node.
1424 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1425 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001426 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001427
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001428 // Link up the new node with the previous node.
1429 if (Last)
1430 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001431
1432 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001433
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001434 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001435 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001436 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001437 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001438 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001439 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001440 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001441 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001442
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001443 // Find the next successor node. We choose the node that is marked
1444 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001445 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1446 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001447 N = 0;
1448
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001449 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001450
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001451 I = Visited.find(*SI);
1452
1453 if (I == Visited.end())
1454 continue;
1455
1456 if (!N || I->second < MinVal) {
1457 N = *SI;
1458 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001459 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001460 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001461
Ted Kremenek938332c2009-05-16 01:11:58 +00001462 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001463 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001464
Ted Kremenek938332c2009-05-16 01:11:58 +00001465 assert(First);
1466
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001467 return std::make_pair(std::make_pair(GNew, BM),
1468 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001469}
1470
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001471/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1472/// and collapses PathDiagosticPieces that are expanded by macros.
1473static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1474 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1475 MacroStackTy;
1476
1477 typedef std::vector<PathDiagnosticPiece*>
1478 PiecesTy;
1479
1480 MacroStackTy MacroStack;
1481 PiecesTy Pieces;
1482
1483 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1484 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001485 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001486
1487 // Determine the instantiation location, which is the location we group
1488 // related PathDiagnosticPieces.
1489 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1490 SM.getInstantiationLoc(Loc) :
1491 SourceLocation();
1492
1493 if (Loc.isFileID()) {
1494 MacroStack.clear();
1495 Pieces.push_back(&*I);
1496 continue;
1497 }
1498
1499 assert(Loc.isMacroID());
1500
1501 // Is the PathDiagnosticPiece within the same macro group?
1502 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1503 MacroStack.back().first->push_back(&*I);
1504 continue;
1505 }
1506
1507 // We aren't in the same group. Are we descending into a new macro
1508 // or are part of an old one?
1509 PathDiagnosticMacroPiece *MacroGroup = 0;
1510
1511 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1512 SM.getInstantiationLoc(Loc) :
1513 SourceLocation();
1514
1515 // Walk the entire macro stack.
1516 while (!MacroStack.empty()) {
1517 if (InstantiationLoc == MacroStack.back().second) {
1518 MacroGroup = MacroStack.back().first;
1519 break;
1520 }
1521
1522 if (ParentInstantiationLoc == MacroStack.back().second) {
1523 MacroGroup = MacroStack.back().first;
1524 break;
1525 }
1526
1527 MacroStack.pop_back();
1528 }
1529
1530 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1531 // Create a new macro group and add it to the stack.
1532 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1533
1534 if (MacroGroup)
1535 MacroGroup->push_back(NewGroup);
1536 else {
1537 assert(InstantiationLoc.isFileID());
1538 Pieces.push_back(NewGroup);
1539 }
1540
1541 MacroGroup = NewGroup;
1542 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1543 }
1544
1545 // Finally, add the PathDiagnosticPiece to the group.
1546 MacroGroup->push_back(&*I);
1547 }
1548
1549 // Now take the pieces and construct a new PathDiagnostic.
1550 PD.resetPath(false);
1551
1552 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1553 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1554 if (!MP->containsEvent()) {
1555 delete MP;
1556 continue;
1557 }
1558
1559 PD.push_back(*I);
1560 }
1561}
1562
Ted Kremenek7dc86642009-03-31 20:22:36 +00001563void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001564 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001565
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001566 std::vector<const ExplodedNode*> Nodes;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001567
Ted Kremenekcf118d42009-02-04 23:49:09 +00001568 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001569 const ExplodedNode* N = I->getEndNode();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001570 if (N) Nodes.push_back(N);
1571 }
1572
1573 if (Nodes.empty())
1574 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001575
1576 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001577 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001578 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001579 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek7dc86642009-03-31 20:22:36 +00001580 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001581
Ted Kremenekcf118d42009-02-04 23:49:09 +00001582 // Find the BugReport with the original location.
1583 BugReport *R = 0;
1584 unsigned i = 0;
1585 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1586 if (i == GPair.second.second) { R = *I; break; }
1587
1588 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001589
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001590 llvm::OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001591 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001592 const ExplodedNode *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001593
Ted Kremenek8966bc12009-05-06 21:39:49 +00001594 // Start building the path diagnostic...
1595 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1596
1597 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001598 PD.push_back(Piece);
1599 else
1600 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001601
1602 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001603
Ted Kremenek7dc86642009-03-31 20:22:36 +00001604 switch (PDB.getGenerationScheme()) {
1605 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001606 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001607 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001608 case PathDiagnosticClient::Minimal:
1609 GenerateMinimalPathDiagnostic(PD, PDB, N);
1610 break;
1611 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001612}
1613
Ted Kremenekcf118d42009-02-04 23:49:09 +00001614void BugReporter::Register(BugType *BT) {
1615 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001616}
1617
Ted Kremenekcf118d42009-02-04 23:49:09 +00001618void BugReporter::EmitReport(BugReport* R) {
1619 // Compute the bug report's hash to determine its equivalence class.
1620 llvm::FoldingSetNodeID ID;
1621 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001622
Ted Kremenekcf118d42009-02-04 23:49:09 +00001623 // Lookup the equivance class. If there isn't one, create it.
1624 BugType& BT = R->getBugType();
1625 Register(&BT);
1626 void *InsertPos;
1627 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1628
1629 if (!EQ) {
1630 EQ = new BugReportEquivClass(R);
1631 BT.EQClasses.InsertNode(EQ, InsertPos);
1632 }
1633 else
1634 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001635}
1636
Ted Kremenekcf118d42009-02-04 23:49:09 +00001637void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1638 assert(!EQ.Reports.empty());
1639 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001640 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001641
1642 // FIXME: Make sure we use the 'R' for the path that was actually used.
1643 // Probably doesn't make a difference in practice.
1644 BugType& BT = R.getBugType();
1645
Ted Kremenekd49967f2009-04-29 21:58:13 +00001646 llvm::OwningPtr<PathDiagnostic>
1647 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001648 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001649 ? R.getDescription() : R.getShortDescription(),
1650 BT.getCategory()));
1651
Ted Kremenekcf118d42009-02-04 23:49:09 +00001652 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001653
1654 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001655 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001656 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001657
Ted Kremenek3148eb42009-01-24 00:55:43 +00001658 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001659 const SourceRange *Beg = 0, *End = 0;
1660 R.getRanges(*this, Beg, End);
1661 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001662 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001663 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001664 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001665
Ted Kremenek3148eb42009-01-24 00:55:43 +00001666 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001667 default: assert(0 && "Don't handle this many ranges yet!");
1668 case 0: Diag.Report(L, ErrorDiag); break;
1669 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1670 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1671 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001672 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001673
1674 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1675 if (!PD)
1676 return;
1677
1678 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001679 PathDiagnosticPiece* piece =
1680 new PathDiagnosticEventPiece(L, R.getDescription());
1681
Ted Kremenek3148eb42009-01-24 00:55:43 +00001682 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1683 D->push_back(piece);
1684 }
1685
1686 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001687}
Ted Kremenek57202072008-07-14 17:40:50 +00001688
Ted Kremenek8c036c72008-09-20 04:23:38 +00001689void BugReporter::EmitBasicReport(const char* name, const char* str,
1690 SourceLocation Loc,
1691 SourceRange* RBeg, unsigned NumRanges) {
1692 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1693}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001694
Ted Kremenek8c036c72008-09-20 04:23:38 +00001695void BugReporter::EmitBasicReport(const char* name, const char* category,
1696 const char* str, SourceLocation Loc,
1697 SourceRange* RBeg, unsigned NumRanges) {
1698
Ted Kremenekcf118d42009-02-04 23:49:09 +00001699 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1700 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001701 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001702 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1703 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1704 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001705}