blob: e54a50078e91d81631075b1b9d2d9340a2124fb4 [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
Zhongxing Xu5032ffe2009-08-25 06:51:30 +000039const Decl& BugReporterContext::getCodeDecl() {
40 return *BR.getEngine().getAnalysisManager().getCodeDecl();
41}
42
43const CFG& BugReporterContext::getCFG() {
44 return *BR.getEngine().getAnalysisManager().getCFG();
45}
46
Ted Kremenekcf118d42009-02-04 23:49:09 +000047//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000048// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000049//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000050
Ted Kremenek5f85e172009-07-22 22:35:28 +000051static inline const Stmt* GetStmt(ProgramPoint P) {
Ted Kremenek592362b2009-08-18 01:05:30 +000052 if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
53 return SP->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000054 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000055 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000056
Ted Kremenekb697b102009-02-23 22:44:26 +000057 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000058}
59
Zhongxing Xuc5619d92009-08-06 01:32:16 +000060static inline const ExplodedNode*
61GetPredecessorNode(const ExplodedNode* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000062 return N->pred_empty() ? NULL : *(N->pred_begin());
63}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000064
Zhongxing Xuc5619d92009-08-06 01:32:16 +000065static inline const ExplodedNode*
66GetSuccessorNode(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000067 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000068}
69
Zhongxing Xuc5619d92009-08-06 01:32:16 +000070static const Stmt* GetPreviousStmt(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000071 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000072 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +000073 return S;
74
75 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000076}
77
Zhongxing Xuc5619d92009-08-06 01:32:16 +000078static const Stmt* GetNextStmt(const ExplodedNode* N) {
Ted Kremenekb697b102009-02-23 22:44:26 +000079 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenek5f85e172009-07-22 22:35:28 +000080 if (const Stmt *S = GetStmt(N->getLocation())) {
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000081 // Check if the statement is '?' or '&&'/'||'. These are "merges",
82 // not actual statement points.
83 switch (S->getStmtClass()) {
84 case Stmt::ChooseExprClass:
85 case Stmt::ConditionalOperatorClass: continue;
86 case Stmt::BinaryOperatorClass: {
87 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
88 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
89 continue;
90 break;
91 }
92 default:
93 break;
94 }
Ted Kremenekb7c51522009-07-28 00:07:15 +000095
96 // Some expressions don't have locations.
97 if (S->getLocStart().isInvalid())
98 continue;
99
Ted Kremenekb697b102009-02-23 22:44:26 +0000100 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +0000101 }
Ted Kremenekb697b102009-02-23 22:44:26 +0000102
103 return 0;
104}
105
Ted Kremenek5f85e172009-07-22 22:35:28 +0000106static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000107GetCurrentOrPreviousStmt(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 GetPreviousStmt(N);
112}
113
Ted Kremenek5f85e172009-07-22 22:35:28 +0000114static inline const Stmt*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000115GetCurrentOrNextStmt(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000116 if (const Stmt *S = GetStmt(N->getLocation()))
Ted Kremenekb697b102009-02-23 22:44:26 +0000117 return S;
118
119 return GetNextStmt(N);
120}
121
122//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000123// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000124//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000125
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000126typedef llvm::DenseMap<const ExplodedNode*,
127const ExplodedNode*> NodeBackMap;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000128
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000129namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000130class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
131 NodeBackMap& M;
132public:
133 NodeMapClosure(NodeBackMap *m) : M(*m) {}
134 ~NodeMapClosure() {}
135
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000136 const ExplodedNode* getOriginalNode(const ExplodedNode* N) {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000137 NodeBackMap::iterator I = M.find(N);
138 return I == M.end() ? 0 : I->second;
139 }
140};
141
Ted Kremenek8966bc12009-05-06 21:39:49 +0000142class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000143 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000144 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000145 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000146 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000147public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000148 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000149 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000150 PathDiagnosticClient *pdc)
151 : BugReporterContext(br),
152 R(r), PDC(pdc), NMC(Backmap)
153 {
154 addVisitor(R);
155 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000156
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000157 PathDiagnosticLocation ExecutionContinues(const ExplodedNode* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000158
Ted Kremenek00605e02009-03-27 20:55:39 +0000159 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000160 const ExplodedNode* N);
Ted Kremenek00605e02009-03-27 20:55:39 +0000161
162 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000163 if (PM.get() == 0)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000164 PM.reset(new ParentMap(getCodeDecl().getBody()));
Ted Kremenek00605e02009-03-27 20:55:39 +0000165 return *PM.get();
166 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000167
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000168 const Stmt *getParent(const Stmt *S) {
169 return getParentMap().getParent(S);
170 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000171
172 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000173 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000174
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000175 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
176
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000177 PathDiagnosticLocation
178 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
179 if (const Stmt *S = L.asStmt())
180 return getEnclosingStmtLocation(S);
181
182 return L;
183 }
184
Ted Kremenek7dc86642009-03-31 20:22:36 +0000185 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
186 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
187 }
188
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000189 bool supportsLogicalOpControlFlow() const {
190 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
191 }
192};
193} // end anonymous namespace
194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195PathDiagnosticLocation
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000196PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode* N) {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000197 if (const Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000198 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000199
Zhongxing Xuf7a50a42009-08-19 12:50:00 +0000200 return FullSourceLoc(N->getLocationContext()->getDecl()->getBodyRBrace(),
201 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000202}
203
Ted Kremenek00605e02009-03-27 20:55:39 +0000204PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000205PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000206 const ExplodedNode* N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000207
Ted Kremenek143ca222008-05-06 18:11:09 +0000208 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000209 if (os.str().empty())
210 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000211
Ted Kremenek00605e02009-03-27 20:55:39 +0000212 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000213
Ted Kremenek00605e02009-03-27 20:55:39 +0000214 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000215 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000216 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
217 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000218 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000219 os << "Execution jumps to the end of the "
Zhongxing Xuf7a50a42009-08-19 12:50:00 +0000220 << (isa<ObjCMethodDecl>(N->getLocationContext()->getDecl()) ?
221 "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000222
223 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000224}
225
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000226static bool IsNested(const Stmt *S, ParentMap &PM) {
227 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
228 return true;
229
230 const Stmt *Parent = PM.getParentIgnoreParens(S);
231
232 if (Parent)
233 switch (Parent->getStmtClass()) {
234 case Stmt::ForStmtClass:
235 case Stmt::DoStmtClass:
236 case Stmt::WhileStmtClass:
237 return true;
238 default:
239 break;
240 }
241
242 return false;
243}
244
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000245PathDiagnosticLocation
246PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
247 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000248 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000249 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000250
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000251 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000252 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000253
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000254 if (!Parent)
255 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000256
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000257 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000258 case Stmt::BinaryOperatorClass: {
259 const BinaryOperator *B = cast<BinaryOperator>(Parent);
260 if (B->isLogicalOp())
261 return PathDiagnosticLocation(S, SMgr);
262 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000263 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000264 case Stmt::CompoundStmtClass:
265 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000266 return PathDiagnosticLocation(S, SMgr);
267 case Stmt::ChooseExprClass:
268 // Similar to '?' if we are referring to condition, just have the edge
269 // point to the entire choose expression.
270 if (cast<ChooseExpr>(Parent)->getCond() == S)
271 return PathDiagnosticLocation(Parent, SMgr);
272 else
273 return PathDiagnosticLocation(S, SMgr);
274 case Stmt::ConditionalOperatorClass:
275 // For '?', if we are referring to condition, just have the edge point
276 // to the entire '?' expression.
277 if (cast<ConditionalOperator>(Parent)->getCond() == S)
278 return PathDiagnosticLocation(Parent, SMgr);
279 else
280 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000281 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000282 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000283 case Stmt::ForStmtClass:
284 if (cast<ForStmt>(Parent)->getBody() == S)
285 return PathDiagnosticLocation(S, SMgr);
286 break;
287 case Stmt::IfStmtClass:
288 if (cast<IfStmt>(Parent)->getCond() != S)
289 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000290 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000291 case Stmt::ObjCForCollectionStmtClass:
292 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
293 return PathDiagnosticLocation(S, SMgr);
294 break;
295 case Stmt::WhileStmtClass:
296 if (cast<WhileStmt>(Parent)->getCond() != S)
297 return PathDiagnosticLocation(S, SMgr);
298 break;
299 default:
300 break;
301 }
302
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000303 S = Parent;
304 }
305
306 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000307
308 // Special case: DeclStmts can appear in for statement declarations, in which
309 // case the ForStmt is the context.
310 if (isa<DeclStmt>(S)) {
311 if (const Stmt *Parent = P.getParent(S)) {
312 switch (Parent->getStmtClass()) {
313 case Stmt::ForStmtClass:
314 case Stmt::ObjCForCollectionStmtClass:
315 return PathDiagnosticLocation(Parent, SMgr);
316 default:
317 break;
318 }
319 }
320 }
321 else if (isa<BinaryOperator>(S)) {
322 // Special case: the binary operator represents the initialization
323 // code in a for statement (this can happen when the variable being
324 // initialized is an old variable.
325 if (const ForStmt *FS =
326 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
327 if (FS->getInit() == S)
328 return PathDiagnosticLocation(FS, SMgr);
329 }
330 }
331
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000332 return PathDiagnosticLocation(S, SMgr);
333}
334
Ted Kremenekcf118d42009-02-04 23:49:09 +0000335//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000336// ScanNotableSymbols: closure-like callback for scanning Store bindings.
337//===----------------------------------------------------------------------===//
338
339static const VarDecl*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000340GetMostRecentVarDeclBinding(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000341 GRStateManager& VMgr, SVal X) {
342
343 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
344
345 ProgramPoint P = N->getLocation();
346
347 if (!isa<PostStmt>(P))
348 continue;
349
Ted Kremenek5f85e172009-07-22 22:35:28 +0000350 const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
Ted Kremenek31061982009-03-31 23:00:32 +0000351
352 if (!DR)
353 continue;
354
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000355 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000356
357 if (X != Y)
358 continue;
359
Ted Kremenek5f85e172009-07-22 22:35:28 +0000360 const VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
Ted Kremenek31061982009-03-31 23:00:32 +0000361
362 if (!VD)
363 continue;
364
365 return VD;
366 }
367
368 return 0;
369}
370
371namespace {
372class VISIBILITY_HIDDEN NotableSymbolHandler
373: public StoreManager::BindingsHandler {
374
375 SymbolRef Sym;
376 const GRState* PrevSt;
377 const Stmt* S;
378 GRStateManager& VMgr;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000379 const ExplodedNode* Pred;
Ted Kremenek31061982009-03-31 23:00:32 +0000380 PathDiagnostic& PD;
381 BugReporter& BR;
382
383public:
384
385 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000386 GRStateManager& vmgr, const ExplodedNode* pred,
Ted Kremenek31061982009-03-31 23:00:32 +0000387 PathDiagnostic& pd, BugReporter& br)
388 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
389
390 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
391 SVal V) {
392
393 SymbolRef ScanSym = V.getAsSymbol();
394
395 if (ScanSym != Sym)
396 return true;
397
398 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000399 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000400
401 if (X == V) // Same binding?
402 return true;
403
404 // Different binding. Only handle assignments for now. We don't pull
405 // this check out of the loop because we will eventually handle other
406 // cases.
407
408 VarDecl *VD = 0;
409
410 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
411 if (!B->isAssignmentOp())
412 return true;
413
414 // What variable did we assign to?
415 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
416
417 if (!DR)
418 return true;
419
420 VD = dyn_cast<VarDecl>(DR->getDecl());
421 }
422 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
423 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
424 // assume that each DeclStmt has a single Decl. This invariant
425 // holds by contruction in the CFG.
426 VD = dyn_cast<VarDecl>(*DS->decl_begin());
427 }
428
429 if (!VD)
430 return true;
431
432 // What is the most recently referenced variable with this binding?
433 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
434
435 if (!MostRecent)
436 return true;
437
438 // Create the diagnostic.
439 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
440
441 if (Loc::IsLocType(VD->getType())) {
442 std::string msg = "'" + std::string(VD->getNameAsString()) +
443 "' now aliases '" + MostRecent->getNameAsString() + "'";
444
445 PD.push_front(new PathDiagnosticEventPiece(L, msg));
446 }
447
448 return true;
449 }
450};
451}
452
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000453static void HandleNotableSymbol(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000454 const Stmt* S,
455 SymbolRef Sym, BugReporter& BR,
456 PathDiagnostic& PD) {
457
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000458 const ExplodedNode* Pred = N->pred_empty() ? 0 : *N->pred_begin();
Ted Kremenek31061982009-03-31 23:00:32 +0000459 const GRState* PrevSt = Pred ? Pred->getState() : 0;
460
461 if (!PrevSt)
462 return;
463
464 // Look at the region bindings of the current state that map to the
465 // specified symbol. Are any of them not in the previous state?
466 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
467 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
468 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
469}
470
471namespace {
472class VISIBILITY_HIDDEN ScanNotableSymbols
473: public StoreManager::BindingsHandler {
474
475 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000476 const ExplodedNode* N;
Ted Kremenek5f85e172009-07-22 22:35:28 +0000477 const Stmt* S;
Ted Kremenek31061982009-03-31 23:00:32 +0000478 GRBugReporter& BR;
479 PathDiagnostic& PD;
480
481public:
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000482 ScanNotableSymbols(const ExplodedNode* n, const Stmt* s,
Ted Kremenek5f85e172009-07-22 22:35:28 +0000483 GRBugReporter& br, PathDiagnostic& pd)
Ted Kremenek31061982009-03-31 23:00:32 +0000484 : N(n), S(s), BR(br), PD(pd) {}
485
486 bool HandleBinding(StoreManager& SMgr, Store store,
487 const MemRegion* R, SVal V) {
488
489 SymbolRef ScanSym = V.getAsSymbol();
490
491 if (!ScanSym)
492 return true;
493
494 if (!BR.isNotable(ScanSym))
495 return true;
496
497 if (AlreadyProcessed.count(ScanSym))
498 return true;
499
500 AlreadyProcessed.insert(ScanSym);
501
502 HandleNotableSymbol(N, S, ScanSym, BR, PD);
503 return true;
504 }
505};
506} // end anonymous namespace
507
508//===----------------------------------------------------------------------===//
509// "Minimal" path diagnostic generation algorithm.
510//===----------------------------------------------------------------------===//
511
Ted Kremenek14856d72009-04-06 23:06:54 +0000512static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
513
Ted Kremenek31061982009-03-31 23:00:32 +0000514static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
515 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000516 const ExplodedNode *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000517
Ted Kremenek31061982009-03-31 23:00:32 +0000518 SourceManager& SMgr = PDB.getSourceManager();
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000519 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000520 ? NULL : *(N->pred_begin());
521 while (NextNode) {
522 N = NextNode;
523 NextNode = GetPredecessorNode(N);
524
525 ProgramPoint P = N->getLocation();
526
527 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
528 CFGBlock* Src = BE->getSrc();
529 CFGBlock* Dst = BE->getDst();
530 Stmt* T = Src->getTerminator();
531
532 if (!T)
533 continue;
534
535 FullSourceLoc Start(T->getLocStart(), SMgr);
536
537 switch (T->getStmtClass()) {
538 default:
539 break;
540
541 case Stmt::GotoStmtClass:
542 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000543 const Stmt* S = GetNextStmt(N);
Ted Kremenek31061982009-03-31 23:00:32 +0000544
545 if (!S)
546 continue;
547
548 std::string sbuf;
549 llvm::raw_string_ostream os(sbuf);
550 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
551
552 os << "Control jumps to line "
553 << End.asLocation().getInstantiationLineNumber();
554 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
555 os.str()));
556 break;
557 }
558
559 case Stmt::SwitchStmtClass: {
560 // Figure out what case arm we took.
561 std::string sbuf;
562 llvm::raw_string_ostream os(sbuf);
563
564 if (Stmt* S = Dst->getLabel()) {
565 PathDiagnosticLocation End(S, SMgr);
566
567 switch (S->getStmtClass()) {
568 default:
569 os << "No cases match in the switch statement. "
570 "Control jumps to line "
571 << End.asLocation().getInstantiationLineNumber();
572 break;
573 case Stmt::DefaultStmtClass:
574 os << "Control jumps to the 'default' case at line "
575 << End.asLocation().getInstantiationLineNumber();
576 break;
577
578 case Stmt::CaseStmtClass: {
579 os << "Control jumps to 'case ";
580 CaseStmt* Case = cast<CaseStmt>(S);
581 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
582
583 // Determine if it is an enum.
584 bool GetRawInt = true;
585
586 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
587 // FIXME: Maybe this should be an assertion. Are there cases
588 // were it is not an EnumConstantDecl?
589 EnumConstantDecl* D =
590 dyn_cast<EnumConstantDecl>(DR->getDecl());
591
592 if (D) {
593 GetRawInt = false;
594 os << D->getNameAsString();
595 }
596 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000597
598 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000599 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000600
Ted Kremenek31061982009-03-31 23:00:32 +0000601 os << ":' at line "
602 << End.asLocation().getInstantiationLineNumber();
603 break;
604 }
605 }
606 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
607 os.str()));
608 }
609 else {
610 os << "'Default' branch taken. ";
611 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
612 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
613 os.str()));
614 }
615
616 break;
617 }
618
619 case Stmt::BreakStmtClass:
620 case Stmt::ContinueStmtClass: {
621 std::string sbuf;
622 llvm::raw_string_ostream os(sbuf);
623 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
624 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
625 os.str()));
626 break;
627 }
628
629 // Determine control-flow for ternary '?'.
630 case Stmt::ConditionalOperatorClass: {
631 std::string sbuf;
632 llvm::raw_string_ostream os(sbuf);
633 os << "'?' condition is ";
634
635 if (*(Src->succ_begin()+1) == Dst)
636 os << "false";
637 else
638 os << "true";
639
640 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
641
642 if (const Stmt *S = End.asStmt())
643 End = PDB.getEnclosingStmtLocation(S);
644
645 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
646 os.str()));
647 break;
648 }
649
650 // Determine control-flow for short-circuited '&&' and '||'.
651 case Stmt::BinaryOperatorClass: {
652 if (!PDB.supportsLogicalOpControlFlow())
653 break;
654
655 BinaryOperator *B = cast<BinaryOperator>(T);
656 std::string sbuf;
657 llvm::raw_string_ostream os(sbuf);
658 os << "Left side of '";
659
660 if (B->getOpcode() == BinaryOperator::LAnd) {
661 os << "&&" << "' is ";
662
663 if (*(Src->succ_begin()+1) == Dst) {
664 os << "false";
665 PathDiagnosticLocation End(B->getLHS(), SMgr);
666 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
667 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
668 os.str()));
669 }
670 else {
671 os << "true";
672 PathDiagnosticLocation Start(B->getLHS(), SMgr);
673 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
674 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
675 os.str()));
676 }
677 }
678 else {
679 assert(B->getOpcode() == BinaryOperator::LOr);
680 os << "||" << "' is ";
681
682 if (*(Src->succ_begin()+1) == Dst) {
683 os << "false";
684 PathDiagnosticLocation Start(B->getLHS(), SMgr);
685 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
686 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
687 os.str()));
688 }
689 else {
690 os << "true";
691 PathDiagnosticLocation End(B->getLHS(), SMgr);
692 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
693 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
694 os.str()));
695 }
696 }
697
698 break;
699 }
700
701 case Stmt::DoStmtClass: {
702 if (*(Src->succ_begin()) == Dst) {
703 std::string sbuf;
704 llvm::raw_string_ostream os(sbuf);
705
706 os << "Loop condition is true. ";
707 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
708
709 if (const Stmt *S = End.asStmt())
710 End = PDB.getEnclosingStmtLocation(S);
711
712 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
713 os.str()));
714 }
715 else {
716 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
717
718 if (const Stmt *S = End.asStmt())
719 End = PDB.getEnclosingStmtLocation(S);
720
721 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
722 "Loop condition is false. Exiting loop"));
723 }
724
725 break;
726 }
727
728 case Stmt::WhileStmtClass:
729 case Stmt::ForStmtClass: {
730 if (*(Src->succ_begin()+1) == Dst) {
731 std::string sbuf;
732 llvm::raw_string_ostream os(sbuf);
733
734 os << "Loop condition is false. ";
735 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
736 if (const Stmt *S = End.asStmt())
737 End = PDB.getEnclosingStmtLocation(S);
738
739 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
740 os.str()));
741 }
742 else {
743 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
744 if (const Stmt *S = End.asStmt())
745 End = PDB.getEnclosingStmtLocation(S);
746
747 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000748 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000749 }
750
751 break;
752 }
753
754 case Stmt::IfStmtClass: {
755 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
756
757 if (const Stmt *S = End.asStmt())
758 End = PDB.getEnclosingStmtLocation(S);
759
760 if (*(Src->succ_begin()+1) == Dst)
761 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000762 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000763 else
764 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000765 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000766
767 break;
768 }
769 }
770 }
771
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000772 if (NextNode) {
773 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
774 E = PDB.visitor_end(); I!=E; ++I) {
775 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
776 PD.push_front(p);
777 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000778 }
Ted Kremenek31061982009-03-31 23:00:32 +0000779
780 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
781 // Scan the region bindings, and see if a "notable" symbol has a new
782 // lval binding.
783 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
784 PDB.getStateManager().iterBindings(N->getState(), SNS);
785 }
786 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000787
788 // After constructing the full PathDiagnostic, do a pass over it to compact
789 // PathDiagnosticPieces that occur within a macro.
790 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000791}
792
793//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000794// "Extensive" PathDiagnostic generation.
795//===----------------------------------------------------------------------===//
796
797static bool IsControlFlowExpr(const Stmt *S) {
798 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000799
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000800 if (!E)
801 return false;
802
803 E = E->IgnoreParenCasts();
804
805 if (isa<ConditionalOperator>(E))
806 return true;
807
808 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
809 if (B->isLogicalOp())
810 return true;
811
812 return false;
813}
814
Ted Kremenek14856d72009-04-06 23:06:54 +0000815namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000816class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
817 bool IsDead;
818public:
819 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
820 : PathDiagnosticLocation(L), IsDead(isdead) {}
821
822 void markDead() { IsDead = true; }
823 bool isDead() const { return IsDead; }
824};
825
Ted Kremenek14856d72009-04-06 23:06:54 +0000826class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000827 std::vector<ContextLocation> CLocs;
828 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000829 PathDiagnostic &PD;
830 PathDiagnosticBuilder &PDB;
831 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000832
833 bool IsConsumedExpr(const PathDiagnosticLocation &L);
834
Ted Kremenek14856d72009-04-06 23:06:54 +0000835 bool containsLocation(const PathDiagnosticLocation &Container,
836 const PathDiagnosticLocation &Containee);
837
838 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000839
Ted Kremenek9650cf32009-05-11 21:42:34 +0000840 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
841 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000842 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000843 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000844 while (1) {
845 // Adjust the location for some expressions that are best referenced
846 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000847 switch (S->getStmtClass()) {
848 default:
849 break;
850 case Stmt::ParenExprClass:
851 S = cast<ParenExpr>(S)->IgnoreParens();
852 firstCharOnly = true;
853 continue;
854 case Stmt::ConditionalOperatorClass:
855 S = cast<ConditionalOperator>(S)->getCond();
856 firstCharOnly = true;
857 continue;
858 case Stmt::ChooseExprClass:
859 S = cast<ChooseExpr>(S)->getCond();
860 firstCharOnly = true;
861 continue;
862 case Stmt::BinaryOperatorClass:
863 S = cast<BinaryOperator>(S)->getLHS();
864 firstCharOnly = true;
865 continue;
866 }
867
868 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000869 }
870
Ted Kremenek9650cf32009-05-11 21:42:34 +0000871 if (S != Original)
872 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000873 }
874
Ted Kremenek9650cf32009-05-11 21:42:34 +0000875 if (firstCharOnly)
876 L = PathDiagnosticLocation(L.asLocation());
877
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000878 return L;
879 }
880
Ted Kremenek14856d72009-04-06 23:06:54 +0000881 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000882 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000883 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000884 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000885 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000886 CLocs.pop_back();
887 }
888
889 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
890
891public:
892 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
893 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000894
895 // If the PathDiagnostic already has pieces, add the enclosing statement
896 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000897 if (!PD.empty()) {
898 PrevLoc = PD.begin()->getLocation();
899
900 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000901 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000902 }
903 }
904
905 ~EdgeBuilder() {
906 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000907
908 // Finally, add an initial edge from the start location of the first
909 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000910 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
911 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000912 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000913 if (!CS->body_empty()) {
914 SourceLocation Loc = (*CS->body_begin())->getLocStart();
915 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
916 }
917
Ted Kremenek14856d72009-04-06 23:06:54 +0000918 }
919
920 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
921
922 void addEdge(const Stmt *S, bool alwaysAdd = false) {
923 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
924 }
925
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000926 void rawAddEdge(PathDiagnosticLocation NewLoc);
927
Ted Kremenek14856d72009-04-06 23:06:54 +0000928 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000929 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000930};
931} // end anonymous namespace
932
933
934PathDiagnosticLocation
935EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
936 if (const Stmt *S = L.asStmt()) {
937 if (IsControlFlowExpr(S))
938 return L;
939
940 return PDB.getEnclosingStmtLocation(S);
941 }
942
943 return L;
944}
945
946bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
947 const PathDiagnosticLocation &Containee) {
948
949 if (Container == Containee)
950 return true;
951
952 if (Container.asDecl())
953 return true;
954
955 if (const Stmt *S = Containee.asStmt())
956 if (const Stmt *ContainerS = Container.asStmt()) {
957 while (S) {
958 if (S == ContainerS)
959 return true;
960 S = PDB.getParent(S);
961 }
962 return false;
963 }
964
965 // Less accurate: compare using source ranges.
966 SourceRange ContainerR = Container.asRange();
967 SourceRange ContaineeR = Containee.asRange();
968
969 SourceManager &SM = PDB.getSourceManager();
970 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
971 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
972 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
973 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
974
975 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
976 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
977 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
978 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
979
980 assert(ContainerBegLine <= ContainerEndLine);
981 assert(ContaineeBegLine <= ContaineeEndLine);
982
983 return (ContainerBegLine <= ContaineeBegLine &&
984 ContainerEndLine >= ContaineeEndLine &&
985 (ContainerBegLine != ContaineeBegLine ||
986 SM.getInstantiationColumnNumber(ContainerRBeg) <=
987 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
988 (ContainerEndLine != ContaineeEndLine ||
989 SM.getInstantiationColumnNumber(ContainerREnd) >=
990 SM.getInstantiationColumnNumber(ContainerREnd)));
991}
992
993PathDiagnosticLocation
994EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
995 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
996 return PathDiagnosticLocation(E->IgnoreParenCasts(),
997 PDB.getSourceManager());
998 return L;
999}
1000
1001void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
1002 if (!PrevLoc.isValid()) {
1003 PrevLoc = NewLoc;
1004 return;
1005 }
1006
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001007 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
1008 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
1009
1010 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001011 return;
1012
1013 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001014 if (NewLocClean.asLocation().getInstantiationLoc() ==
1015 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001016 return;
1017
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001018 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1019 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001020}
1021
1022void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001023
1024 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1025 return;
1026
Ted Kremenek14856d72009-04-06 23:06:54 +00001027 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1028
1029 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001030 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001031
1032 // Is the top location context the same as the one for the new location?
1033 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001034 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001035 if (IsConsumedExpr(TopContextLoc) &&
1036 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001037 TopContextLoc.markDead();
1038
Ted Kremenek14856d72009-04-06 23:06:54 +00001039 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001040 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001041
1042 return;
1043 }
1044
1045 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001046 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001047 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001048
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001049 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001050 CLocs.push_back(ContextLocation(CLoc, true));
1051 return;
1052 }
1053 }
1054
Ted Kremenek14856d72009-04-06 23:06:54 +00001055 CLocs.push_back(CLoc);
1056 return;
1057 }
1058
1059 // Context does not contain the location. Flush it.
1060 popLocation();
1061 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001062
1063 // If we reach here, there is no enclosing context. Just add the edge.
1064 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001065}
1066
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001067bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1068 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1069 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1070
1071 return false;
1072}
1073
Ted Kremeneke1baed32009-05-05 23:13:38 +00001074void EdgeBuilder::addExtendedContext(const Stmt *S) {
1075 if (!S)
1076 return;
1077
1078 const Stmt *Parent = PDB.getParent(S);
1079 while (Parent) {
1080 if (isa<CompoundStmt>(Parent))
1081 Parent = PDB.getParent(Parent);
1082 else
1083 break;
1084 }
1085
1086 if (Parent) {
1087 switch (Parent->getStmtClass()) {
1088 case Stmt::DoStmtClass:
1089 case Stmt::ObjCAtSynchronizedStmtClass:
1090 addContext(Parent);
1091 default:
1092 break;
1093 }
1094 }
1095
1096 addContext(S);
1097}
1098
Ted Kremenek14856d72009-04-06 23:06:54 +00001099void EdgeBuilder::addContext(const Stmt *S) {
1100 if (!S)
1101 return;
1102
1103 PathDiagnosticLocation L(S, PDB.getSourceManager());
1104
1105 while (!CLocs.empty()) {
1106 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1107
1108 // Is the top location context the same as the one for the new location?
1109 if (TopContextLoc == L)
1110 return;
1111
1112 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001113 CLocs.push_back(L);
1114 return;
1115 }
1116
1117 // Context does not contain the location. Flush it.
1118 popLocation();
1119 }
1120
1121 CLocs.push_back(L);
1122}
1123
1124static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1125 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001126 const ExplodedNode *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001127
1128
1129 EdgeBuilder EB(PD, PDB);
1130
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001131 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001132 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001133 while (NextNode) {
1134 N = NextNode;
1135 NextNode = GetPredecessorNode(N);
1136 ProgramPoint P = N->getLocation();
1137
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001138 do {
1139 // Block edges.
1140 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1141 const CFGBlock &Blk = *BE->getSrc();
1142 const Stmt *Term = Blk.getTerminator();
1143
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001144 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001145 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001146 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001147 const CompoundStmt *CS = NULL;
1148
1149 if (!Term) {
1150 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1151 CS = dyn_cast<CompoundStmt>(FS->getBody());
1152 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1153 CS = dyn_cast<CompoundStmt>(WS->getBody());
1154 }
1155
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001156 PathDiagnosticEventPiece *p =
1157 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001158 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001159
1160 EB.addEdge(p->getLocation(), true);
1161 PD.push_front(p);
1162
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001163 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001164 PathDiagnosticLocation BL(CS->getRBracLoc(),
1165 PDB.getSourceManager());
1166 BL = PathDiagnosticLocation(BL.asLocation());
1167 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001168 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001169 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001170
1171 if (Term)
1172 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001173
1174 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001175 }
1176
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001177 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1178 if (const Stmt* S = BE->getFirstStmt()) {
1179 if (IsControlFlowExpr(S)) {
1180 // Add the proper context for '&&', '||', and '?'.
1181 EB.addContext(S);
1182 }
1183 else
1184 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1185 }
1186
1187 break;
1188 }
1189 } while (0);
1190
1191 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001192 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001193
Ted Kremenek8966bc12009-05-06 21:39:49 +00001194 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1195 E = PDB.visitor_end(); I!=E; ++I) {
1196 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1197 const PathDiagnosticLocation &Loc = p->getLocation();
1198 EB.addEdge(Loc, true);
1199 PD.push_front(p);
1200 if (const Stmt *S = Loc.asStmt())
1201 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1202 }
1203 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001204 }
1205}
1206
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001207//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001208// Methods for BugType and subclasses.
1209//===----------------------------------------------------------------------===//
1210BugType::~BugType() {}
1211void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001212
Ted Kremenekcf118d42009-02-04 23:49:09 +00001213//===----------------------------------------------------------------------===//
1214// Methods for BugReport and subclasses.
1215//===----------------------------------------------------------------------===//
1216BugReport::~BugReport() {}
1217RangedBugReport::~RangedBugReport() {}
1218
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001219const Stmt* BugReport::getStmt() const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001220 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001221 const Stmt *S = NULL;
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001222
Ted Kremenekcf118d42009-02-04 23:49:09 +00001223 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Zhongxing Xufafd3832009-08-20 01:23:34 +00001224 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001225 if (BE->getBlock() == &Exit)
1226 S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001227 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001228 if (!S)
1229 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001230
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001231 return S;
1232}
1233
1234PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001235BugReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001236 const ExplodedNode* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001237
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001238 const Stmt* S = getStmt();
Ted Kremenek61f3e052008-04-03 04:42:52 +00001239
1240 if (!S)
1241 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001242
Ted Kremenekde7161f2008-04-03 18:00:37 +00001243 const SourceRange *Beg, *End;
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001244 getRanges(Beg, End);
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001245 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001246
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001247 // Only add the statement itself as a range if we didn't specify any
1248 // special ranges for this report.
1249 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1250 Beg == End);
1251
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001252 for (; Beg != End; ++Beg)
1253 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001254
1255 return P;
1256}
1257
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001258void BugReport::getRanges(const SourceRange*& beg, const SourceRange*& end) {
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001259 if (const Expr* E = dyn_cast_or_null<Expr>(getStmt())) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001260 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001261 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001262 beg = &R;
1263 end = beg+1;
1264 }
1265 else
1266 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001267}
1268
Ted Kremenekcf118d42009-02-04 23:49:09 +00001269SourceLocation BugReport::getLocation() const {
1270 if (EndNode)
Ted Kremenek5f85e172009-07-22 22:35:28 +00001271 if (const Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001272 // For member expressions, return the location of the '.' or '->'.
Ted Kremenek5f85e172009-07-22 22:35:28 +00001273 if (const MemberExpr* ME = dyn_cast<MemberExpr>(S))
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001274 return ME->getMemberLoc();
1275
Ted Kremenekcf118d42009-02-04 23:49:09 +00001276 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001277 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001278
1279 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001280}
1281
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001282PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode* N,
1283 const ExplodedNode* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001284 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001285 return NULL;
1286}
1287
Ted Kremenekcf118d42009-02-04 23:49:09 +00001288//===----------------------------------------------------------------------===//
1289// Methods for BugReporter and subclasses.
1290//===----------------------------------------------------------------------===//
1291
1292BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001293 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001294}
1295
Zhongxing Xua2f4ec02009-09-05 06:06:49 +00001296GRBugReporter::~GRBugReporter() { }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001297BugReporterData::~BugReporterData() {}
1298
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001299ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001300
1301GRStateManager&
1302GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1303
1304BugReporter::~BugReporter() { FlushReports(); }
1305
1306void BugReporter::FlushReports() {
1307 if (BugTypes.isEmpty())
1308 return;
1309
1310 // First flush the warnings for each BugType. This may end up creating new
1311 // warnings and new BugTypes. Because ImmutableSet is a functional data
1312 // structure, we do not need to worry about the iterators being invalidated.
1313 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1314 const_cast<BugType*>(*I)->FlushReports(*this);
1315
1316 // Iterate through BugTypes a second time. BugTypes may have been updated
1317 // with new BugType objects and new warnings.
1318 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1319 BugType *BT = const_cast<BugType*>(*I);
1320
1321 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1322 SetTy& EQClasses = BT->EQClasses;
1323
1324 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1325 BugReportEquivClass& EQ = *EI;
1326 FlushReport(EQ);
1327 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001328
Zhongxing Xud9b401c2009-07-29 08:13:37 +00001329 // Delete the BugType object.
1330
1331 // FIXME: this will *not* delete the BugReportEquivClasses, since FoldingSet
1332 // only deletes the buckets, not the nodes themselves.
Ted Kremenekcf118d42009-02-04 23:49:09 +00001333 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001334 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001335
1336 // Remove all references to the BugType objects.
1337 BugTypes = F.GetEmptySet();
1338}
1339
1340//===----------------------------------------------------------------------===//
1341// PathDiagnostics generation.
1342//===----------------------------------------------------------------------===//
1343
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001344static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001345 std::pair<ExplodedNode*, unsigned> >
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001346MakeReportGraph(const ExplodedGraph* G,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001347 const ExplodedNode** NStart,
1348 const ExplodedNode** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001349
Ted Kremenekcf118d42009-02-04 23:49:09 +00001350 // Create the trimmed graph. It will contain the shortest paths from the
1351 // error nodes to the root. In the new graph we should only have one
1352 // error node unless there are two or more error nodes with the same minimum
1353 // path length.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001354 ExplodedGraph* GTrim;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001355 InterExplodedGraphMap* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001356
1357 llvm::DenseMap<const void*, const void*> InverseMap;
1358 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001359
1360 // Create owning pointers for GTrim and NMap just to ensure that they are
1361 // released when this function exists.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001362 llvm::OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001363 llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001364
1365 // Find the (first) error node in the trimmed graph. We just need to consult
1366 // the node map (NMap) which maps from nodes in the original graph to nodes
1367 // in the new graph.
Ted Kremenek938332c2009-05-16 01:11:58 +00001368
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001369 std::queue<const ExplodedNode*> WS;
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001370 typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
Ted Kremenek938332c2009-05-16 01:11:58 +00001371 IndexMapTy IndexMap;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001372
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001373 for (const ExplodedNode** I = NStart; I != NEnd; ++I)
1374 if (const ExplodedNode *N = NMap->getMappedNode(*I)) {
Ted Kremenek938332c2009-05-16 01:11:58 +00001375 unsigned NodeIndex = (I - NStart) / sizeof(*I);
1376 WS.push(N);
1377 IndexMap[*I] = NodeIndex;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001378 }
1379
Ted Kremenek938332c2009-05-16 01:11:58 +00001380 assert(!WS.empty() && "No error node found in the trimmed graph.");
Ted Kremenekcf118d42009-02-04 23:49:09 +00001381
1382 // Create a new (third!) graph with a single path. This is the graph
1383 // that will be returned to the caller.
Zhongxing Xucc025532009-08-25 03:33:41 +00001384 ExplodedGraph *GNew = new ExplodedGraph(GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001385
Ted Kremenek10aa5542009-03-12 23:41:59 +00001386 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001387 // to the root node, and then construct a new graph that contains only
1388 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001389 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001390
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001391 unsigned cnt = 0;
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001392 const ExplodedNode* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001393
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001394 while (!WS.empty()) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001395 const ExplodedNode* Node = WS.front();
Ted Kremenek10aa5542009-03-12 23:41:59 +00001396 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001397
1398 if (Visited.find(Node) != Visited.end())
1399 continue;
1400
1401 Visited[Node] = cnt++;
1402
1403 if (Node->pred_empty()) {
1404 Root = Node;
1405 break;
1406 }
1407
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001408 for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001409 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001410 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001411 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001412
Ted Kremenek938332c2009-05-16 01:11:58 +00001413 assert(Root);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001414
Ted Kremenek10aa5542009-03-12 23:41:59 +00001415 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001416 // with the lowest number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001417 ExplodedNode *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001418 NodeBackMap *BM = new NodeBackMap();
Ted Kremenek938332c2009-05-16 01:11:58 +00001419 unsigned NodeIndex = 0;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001420
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001421 for ( const ExplodedNode *N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001422 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001423 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek938332c2009-05-16 01:11:58 +00001424 assert(I != Visited.end());
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001425
1426 // Create the equivalent node in the new graph with the same state
1427 // and location.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001428 ExplodedNode* NewN = GNew->getNode(N->getLocation(), N->getState());
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001429
1430 // Store the mapping to the original node.
1431 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1432 assert(IMitr != InverseMap.end() && "No mapping to original node.");
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001433 (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001434
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001435 // Link up the new node with the previous node.
1436 if (Last)
1437 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001438
1439 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001440
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001441 // Are we at the final node?
Ted Kremenek938332c2009-05-16 01:11:58 +00001442 IndexMapTy::iterator IMI =
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001443 IndexMap.find((const ExplodedNode*)(IMitr->second));
Ted Kremenek938332c2009-05-16 01:11:58 +00001444 if (IMI != IndexMap.end()) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001445 First = NewN;
Ted Kremenek938332c2009-05-16 01:11:58 +00001446 NodeIndex = IMI->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001447 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001448 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001449
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001450 // Find the next successor node. We choose the node that is marked
1451 // with the lowest DFS number.
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001452 ExplodedNode::const_succ_iterator SI = N->succ_begin();
1453 ExplodedNode::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001454 N = 0;
1455
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001456 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001457
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001458 I = Visited.find(*SI);
1459
1460 if (I == Visited.end())
1461 continue;
1462
1463 if (!N || I->second < MinVal) {
1464 N = *SI;
1465 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001466 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001467 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001468
Ted Kremenek938332c2009-05-16 01:11:58 +00001469 assert(N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001470 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001471
Ted Kremenek938332c2009-05-16 01:11:58 +00001472 assert(First);
1473
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001474 return std::make_pair(std::make_pair(GNew, BM),
1475 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001476}
1477
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001478/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1479/// and collapses PathDiagosticPieces that are expanded by macros.
1480static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1481 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1482 MacroStackTy;
1483
1484 typedef std::vector<PathDiagnosticPiece*>
1485 PiecesTy;
1486
1487 MacroStackTy MacroStack;
1488 PiecesTy Pieces;
1489
1490 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1491 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001492 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001493
1494 // Determine the instantiation location, which is the location we group
1495 // related PathDiagnosticPieces.
1496 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1497 SM.getInstantiationLoc(Loc) :
1498 SourceLocation();
1499
1500 if (Loc.isFileID()) {
1501 MacroStack.clear();
1502 Pieces.push_back(&*I);
1503 continue;
1504 }
1505
1506 assert(Loc.isMacroID());
1507
1508 // Is the PathDiagnosticPiece within the same macro group?
1509 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1510 MacroStack.back().first->push_back(&*I);
1511 continue;
1512 }
1513
1514 // We aren't in the same group. Are we descending into a new macro
1515 // or are part of an old one?
1516 PathDiagnosticMacroPiece *MacroGroup = 0;
1517
1518 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1519 SM.getInstantiationLoc(Loc) :
1520 SourceLocation();
1521
1522 // Walk the entire macro stack.
1523 while (!MacroStack.empty()) {
1524 if (InstantiationLoc == MacroStack.back().second) {
1525 MacroGroup = MacroStack.back().first;
1526 break;
1527 }
1528
1529 if (ParentInstantiationLoc == MacroStack.back().second) {
1530 MacroGroup = MacroStack.back().first;
1531 break;
1532 }
1533
1534 MacroStack.pop_back();
1535 }
1536
1537 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1538 // Create a new macro group and add it to the stack.
1539 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1540
1541 if (MacroGroup)
1542 MacroGroup->push_back(NewGroup);
1543 else {
1544 assert(InstantiationLoc.isFileID());
1545 Pieces.push_back(NewGroup);
1546 }
1547
1548 MacroGroup = NewGroup;
1549 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1550 }
1551
1552 // Finally, add the PathDiagnosticPiece to the group.
1553 MacroGroup->push_back(&*I);
1554 }
1555
1556 // Now take the pieces and construct a new PathDiagnostic.
1557 PD.resetPath(false);
1558
1559 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1560 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1561 if (!MP->containsEvent()) {
1562 delete MP;
1563 continue;
1564 }
1565
1566 PD.push_back(*I);
1567 }
1568}
1569
Ted Kremenek7dc86642009-03-31 20:22:36 +00001570void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001571 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001572
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001573 std::vector<const ExplodedNode*> Nodes;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001574
Ted Kremenekcf118d42009-02-04 23:49:09 +00001575 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001576 const ExplodedNode* N = I->getEndNode();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001577 if (N) Nodes.push_back(N);
1578 }
1579
1580 if (Nodes.empty())
1581 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001582
1583 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001584 // node to a root.
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001585 const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001586 std::pair<ExplodedNode*, unsigned> >&
Ted Kremenek7dc86642009-03-31 20:22:36 +00001587 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001588
Ted Kremenekcf118d42009-02-04 23:49:09 +00001589 // Find the BugReport with the original location.
1590 BugReport *R = 0;
1591 unsigned i = 0;
1592 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1593 if (i == GPair.second.second) { R = *I; break; }
1594
1595 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001596
Zhongxing Xu38b02b92009-08-06 06:28:40 +00001597 llvm::OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001598 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001599 const ExplodedNode *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001600
Ted Kremenek8966bc12009-05-06 21:39:49 +00001601 // Start building the path diagnostic...
1602 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1603
1604 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001605 PD.push_back(Piece);
1606 else
1607 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001608
1609 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001610
Ted Kremenek7dc86642009-03-31 20:22:36 +00001611 switch (PDB.getGenerationScheme()) {
1612 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001613 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001614 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001615 case PathDiagnosticClient::Minimal:
1616 GenerateMinimalPathDiagnostic(PD, PDB, N);
1617 break;
1618 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001619}
1620
Ted Kremenekcf118d42009-02-04 23:49:09 +00001621void BugReporter::Register(BugType *BT) {
1622 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001623}
1624
Ted Kremenekcf118d42009-02-04 23:49:09 +00001625void BugReporter::EmitReport(BugReport* R) {
1626 // Compute the bug report's hash to determine its equivalence class.
1627 llvm::FoldingSetNodeID ID;
1628 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001629
Ted Kremenekcf118d42009-02-04 23:49:09 +00001630 // Lookup the equivance class. If there isn't one, create it.
1631 BugType& BT = R->getBugType();
1632 Register(&BT);
1633 void *InsertPos;
1634 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1635
1636 if (!EQ) {
1637 EQ = new BugReportEquivClass(R);
1638 BT.EQClasses.InsertNode(EQ, InsertPos);
1639 }
1640 else
1641 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001642}
1643
Ted Kremenekcf118d42009-02-04 23:49:09 +00001644void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1645 assert(!EQ.Reports.empty());
1646 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001647 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001648
1649 // FIXME: Make sure we use the 'R' for the path that was actually used.
1650 // Probably doesn't make a difference in practice.
1651 BugType& BT = R.getBugType();
1652
Ted Kremenekd49967f2009-04-29 21:58:13 +00001653 llvm::OwningPtr<PathDiagnostic>
1654 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001655 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001656 ? R.getDescription() : R.getShortDescription(),
1657 BT.getCategory()));
1658
Ted Kremenekcf118d42009-02-04 23:49:09 +00001659 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001660
1661 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001662 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001663 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001664
Ted Kremenek3148eb42009-01-24 00:55:43 +00001665 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001666 const SourceRange *Beg = 0, *End = 0;
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001667 R.getRanges(Beg, End);
Ted Kremenek3148eb42009-01-24 00:55:43 +00001668 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001669 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001670 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001671 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001672
Ted Kremenek3148eb42009-01-24 00:55:43 +00001673 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001674 default: assert(0 && "Don't handle this many ranges yet!");
1675 case 0: Diag.Report(L, ErrorDiag); break;
1676 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1677 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1678 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001679 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001680
1681 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1682 if (!PD)
1683 return;
1684
1685 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001686 PathDiagnosticPiece* piece =
1687 new PathDiagnosticEventPiece(L, R.getDescription());
1688
Ted Kremenek3148eb42009-01-24 00:55:43 +00001689 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1690 D->push_back(piece);
1691 }
1692
1693 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001694}
Ted Kremenek57202072008-07-14 17:40:50 +00001695
Ted Kremenek8c036c72008-09-20 04:23:38 +00001696void BugReporter::EmitBasicReport(const char* name, const char* str,
1697 SourceLocation Loc,
1698 SourceRange* RBeg, unsigned NumRanges) {
1699 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1700}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001701
Ted Kremenek8c036c72008-09-20 04:23:38 +00001702void BugReporter::EmitBasicReport(const char* name, const char* category,
1703 const char* str, SourceLocation Loc,
1704 SourceRange* RBeg, unsigned NumRanges) {
1705
Ted Kremenekcf118d42009-02-04 23:49:09 +00001706 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1707 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001708 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001709 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1710 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1711 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001712}