blob: 1a77ecb55f2f22b020864638ff1a11618d9059a5 [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
Zhongxing Xuf7a50a42009-08-19 12:50:00 +0000192 return FullSourceLoc(N->getLocationContext()->getDecl()->getBodyRBrace(),
193 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000194}
195
Ted Kremenek00605e02009-03-27 20:55:39 +0000196PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000197PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000198 const ExplodedNode* N) {
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000199
Ted Kremenek143ca222008-05-06 18:11:09 +0000200 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000201 if (os.str().empty())
202 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000203
Ted Kremenek00605e02009-03-27 20:55:39 +0000204 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000205
Ted Kremenek00605e02009-03-27 20:55:39 +0000206 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000207 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000208 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
209 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000210 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000211 os << "Execution jumps to the end of the "
Zhongxing Xuf7a50a42009-08-19 12:50:00 +0000212 << (isa<ObjCMethodDecl>(N->getLocationContext()->getDecl()) ?
213 "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000214
215 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000216}
217
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000218static bool IsNested(const Stmt *S, ParentMap &PM) {
219 if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
220 return true;
221
222 const Stmt *Parent = PM.getParentIgnoreParens(S);
223
224 if (Parent)
225 switch (Parent->getStmtClass()) {
226 case Stmt::ForStmtClass:
227 case Stmt::DoStmtClass:
228 case Stmt::WhileStmtClass:
229 return true;
230 default:
231 break;
232 }
233
234 return false;
235}
236
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000237PathDiagnosticLocation
238PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
239 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000240 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000241 SourceManager &SMgr = getSourceManager();
Ted Kremeneke88a1702009-05-11 22:19:32 +0000242
Ted Kremenekddb7bab2009-05-15 01:50:15 +0000243 while (IsNested(S, P)) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000244 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000245
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000246 if (!Parent)
247 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000248
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000249 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000250 case Stmt::BinaryOperatorClass: {
251 const BinaryOperator *B = cast<BinaryOperator>(Parent);
252 if (B->isLogicalOp())
253 return PathDiagnosticLocation(S, SMgr);
254 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000255 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000256 case Stmt::CompoundStmtClass:
257 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000258 return PathDiagnosticLocation(S, SMgr);
259 case Stmt::ChooseExprClass:
260 // Similar to '?' if we are referring to condition, just have the edge
261 // point to the entire choose expression.
262 if (cast<ChooseExpr>(Parent)->getCond() == S)
263 return PathDiagnosticLocation(Parent, SMgr);
264 else
265 return PathDiagnosticLocation(S, SMgr);
266 case Stmt::ConditionalOperatorClass:
267 // For '?', if we are referring to condition, just have the edge point
268 // to the entire '?' expression.
269 if (cast<ConditionalOperator>(Parent)->getCond() == S)
270 return PathDiagnosticLocation(Parent, SMgr);
271 else
272 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000273 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000274 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000275 case Stmt::ForStmtClass:
276 if (cast<ForStmt>(Parent)->getBody() == S)
277 return PathDiagnosticLocation(S, SMgr);
278 break;
279 case Stmt::IfStmtClass:
280 if (cast<IfStmt>(Parent)->getCond() != S)
281 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000282 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000283 case Stmt::ObjCForCollectionStmtClass:
284 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
285 return PathDiagnosticLocation(S, SMgr);
286 break;
287 case Stmt::WhileStmtClass:
288 if (cast<WhileStmt>(Parent)->getCond() != S)
289 return PathDiagnosticLocation(S, SMgr);
290 break;
291 default:
292 break;
293 }
294
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000295 S = Parent;
296 }
297
298 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
Ted Kremeneke88a1702009-05-11 22:19:32 +0000299
300 // Special case: DeclStmts can appear in for statement declarations, in which
301 // case the ForStmt is the context.
302 if (isa<DeclStmt>(S)) {
303 if (const Stmt *Parent = P.getParent(S)) {
304 switch (Parent->getStmtClass()) {
305 case Stmt::ForStmtClass:
306 case Stmt::ObjCForCollectionStmtClass:
307 return PathDiagnosticLocation(Parent, SMgr);
308 default:
309 break;
310 }
311 }
312 }
313 else if (isa<BinaryOperator>(S)) {
314 // Special case: the binary operator represents the initialization
315 // code in a for statement (this can happen when the variable being
316 // initialized is an old variable.
317 if (const ForStmt *FS =
318 dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
319 if (FS->getInit() == S)
320 return PathDiagnosticLocation(FS, SMgr);
321 }
322 }
323
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000324 return PathDiagnosticLocation(S, SMgr);
325}
326
Ted Kremenekcf118d42009-02-04 23:49:09 +0000327//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000328// ScanNotableSymbols: closure-like callback for scanning Store bindings.
329//===----------------------------------------------------------------------===//
330
331static const VarDecl*
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000332GetMostRecentVarDeclBinding(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000333 GRStateManager& VMgr, SVal X) {
334
335 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
336
337 ProgramPoint P = N->getLocation();
338
339 if (!isa<PostStmt>(P))
340 continue;
341
Ted Kremenek5f85e172009-07-22 22:35:28 +0000342 const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
Ted Kremenek31061982009-03-31 23:00:32 +0000343
344 if (!DR)
345 continue;
346
Ted Kremenek23ec48c2009-06-18 23:58:37 +0000347 SVal Y = N->getState()->getSVal(DR);
Ted Kremenek31061982009-03-31 23:00:32 +0000348
349 if (X != Y)
350 continue;
351
Ted Kremenek5f85e172009-07-22 22:35:28 +0000352 const VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
Ted Kremenek31061982009-03-31 23:00:32 +0000353
354 if (!VD)
355 continue;
356
357 return VD;
358 }
359
360 return 0;
361}
362
363namespace {
364class VISIBILITY_HIDDEN NotableSymbolHandler
365: public StoreManager::BindingsHandler {
366
367 SymbolRef Sym;
368 const GRState* PrevSt;
369 const Stmt* S;
370 GRStateManager& VMgr;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000371 const ExplodedNode* Pred;
Ted Kremenek31061982009-03-31 23:00:32 +0000372 PathDiagnostic& PD;
373 BugReporter& BR;
374
375public:
376
377 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000378 GRStateManager& vmgr, const ExplodedNode* pred,
Ted Kremenek31061982009-03-31 23:00:32 +0000379 PathDiagnostic& pd, BugReporter& br)
380 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
381
382 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
383 SVal V) {
384
385 SymbolRef ScanSym = V.getAsSymbol();
386
387 if (ScanSym != Sym)
388 return true;
389
390 // Check if the previous state has this binding.
Ted Kremenekdbc2afc2009-06-23 17:55:07 +0000391 SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
Ted Kremenek31061982009-03-31 23:00:32 +0000392
393 if (X == V) // Same binding?
394 return true;
395
396 // Different binding. Only handle assignments for now. We don't pull
397 // this check out of the loop because we will eventually handle other
398 // cases.
399
400 VarDecl *VD = 0;
401
402 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
403 if (!B->isAssignmentOp())
404 return true;
405
406 // What variable did we assign to?
407 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
408
409 if (!DR)
410 return true;
411
412 VD = dyn_cast<VarDecl>(DR->getDecl());
413 }
414 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
415 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
416 // assume that each DeclStmt has a single Decl. This invariant
417 // holds by contruction in the CFG.
418 VD = dyn_cast<VarDecl>(*DS->decl_begin());
419 }
420
421 if (!VD)
422 return true;
423
424 // What is the most recently referenced variable with this binding?
425 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
426
427 if (!MostRecent)
428 return true;
429
430 // Create the diagnostic.
431 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
432
433 if (Loc::IsLocType(VD->getType())) {
434 std::string msg = "'" + std::string(VD->getNameAsString()) +
435 "' now aliases '" + MostRecent->getNameAsString() + "'";
436
437 PD.push_front(new PathDiagnosticEventPiece(L, msg));
438 }
439
440 return true;
441 }
442};
443}
444
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000445static void HandleNotableSymbol(const ExplodedNode* N,
Ted Kremenek31061982009-03-31 23:00:32 +0000446 const Stmt* S,
447 SymbolRef Sym, BugReporter& BR,
448 PathDiagnostic& PD) {
449
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000450 const ExplodedNode* Pred = N->pred_empty() ? 0 : *N->pred_begin();
Ted Kremenek31061982009-03-31 23:00:32 +0000451 const GRState* PrevSt = Pred ? Pred->getState() : 0;
452
453 if (!PrevSt)
454 return;
455
456 // Look at the region bindings of the current state that map to the
457 // specified symbol. Are any of them not in the previous state?
458 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
459 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
460 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
461}
462
463namespace {
464class VISIBILITY_HIDDEN ScanNotableSymbols
465: public StoreManager::BindingsHandler {
466
467 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000468 const ExplodedNode* N;
Ted Kremenek5f85e172009-07-22 22:35:28 +0000469 const Stmt* S;
Ted Kremenek31061982009-03-31 23:00:32 +0000470 GRBugReporter& BR;
471 PathDiagnostic& PD;
472
473public:
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000474 ScanNotableSymbols(const ExplodedNode* n, const Stmt* s,
Ted Kremenek5f85e172009-07-22 22:35:28 +0000475 GRBugReporter& br, PathDiagnostic& pd)
Ted Kremenek31061982009-03-31 23:00:32 +0000476 : N(n), S(s), BR(br), PD(pd) {}
477
478 bool HandleBinding(StoreManager& SMgr, Store store,
479 const MemRegion* R, SVal V) {
480
481 SymbolRef ScanSym = V.getAsSymbol();
482
483 if (!ScanSym)
484 return true;
485
486 if (!BR.isNotable(ScanSym))
487 return true;
488
489 if (AlreadyProcessed.count(ScanSym))
490 return true;
491
492 AlreadyProcessed.insert(ScanSym);
493
494 HandleNotableSymbol(N, S, ScanSym, BR, PD);
495 return true;
496 }
497};
498} // end anonymous namespace
499
500//===----------------------------------------------------------------------===//
501// "Minimal" path diagnostic generation algorithm.
502//===----------------------------------------------------------------------===//
503
Ted Kremenek14856d72009-04-06 23:06:54 +0000504static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
505
Ted Kremenek31061982009-03-31 23:00:32 +0000506static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
507 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000508 const ExplodedNode *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000509
Ted Kremenek31061982009-03-31 23:00:32 +0000510 SourceManager& SMgr = PDB.getSourceManager();
Zhongxing Xuc5619d92009-08-06 01:32:16 +0000511 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek31061982009-03-31 23:00:32 +0000512 ? NULL : *(N->pred_begin());
513 while (NextNode) {
514 N = NextNode;
515 NextNode = GetPredecessorNode(N);
516
517 ProgramPoint P = N->getLocation();
518
519 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
520 CFGBlock* Src = BE->getSrc();
521 CFGBlock* Dst = BE->getDst();
522 Stmt* T = Src->getTerminator();
523
524 if (!T)
525 continue;
526
527 FullSourceLoc Start(T->getLocStart(), SMgr);
528
529 switch (T->getStmtClass()) {
530 default:
531 break;
532
533 case Stmt::GotoStmtClass:
534 case Stmt::IndirectGotoStmtClass: {
Ted Kremenek5f85e172009-07-22 22:35:28 +0000535 const Stmt* S = GetNextStmt(N);
Ted Kremenek31061982009-03-31 23:00:32 +0000536
537 if (!S)
538 continue;
539
540 std::string sbuf;
541 llvm::raw_string_ostream os(sbuf);
542 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
543
544 os << "Control jumps to line "
545 << End.asLocation().getInstantiationLineNumber();
546 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
547 os.str()));
548 break;
549 }
550
551 case Stmt::SwitchStmtClass: {
552 // Figure out what case arm we took.
553 std::string sbuf;
554 llvm::raw_string_ostream os(sbuf);
555
556 if (Stmt* S = Dst->getLabel()) {
557 PathDiagnosticLocation End(S, SMgr);
558
559 switch (S->getStmtClass()) {
560 default:
561 os << "No cases match in the switch statement. "
562 "Control jumps to line "
563 << End.asLocation().getInstantiationLineNumber();
564 break;
565 case Stmt::DefaultStmtClass:
566 os << "Control jumps to the 'default' case at line "
567 << End.asLocation().getInstantiationLineNumber();
568 break;
569
570 case Stmt::CaseStmtClass: {
571 os << "Control jumps to 'case ";
572 CaseStmt* Case = cast<CaseStmt>(S);
573 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
574
575 // Determine if it is an enum.
576 bool GetRawInt = true;
577
578 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
579 // FIXME: Maybe this should be an assertion. Are there cases
580 // were it is not an EnumConstantDecl?
581 EnumConstantDecl* D =
582 dyn_cast<EnumConstantDecl>(DR->getDecl());
583
584 if (D) {
585 GetRawInt = false;
586 os << D->getNameAsString();
587 }
588 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000589
590 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000591 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000592
Ted Kremenek31061982009-03-31 23:00:32 +0000593 os << ":' at line "
594 << End.asLocation().getInstantiationLineNumber();
595 break;
596 }
597 }
598 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
599 os.str()));
600 }
601 else {
602 os << "'Default' branch taken. ";
603 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
604 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
605 os.str()));
606 }
607
608 break;
609 }
610
611 case Stmt::BreakStmtClass:
612 case Stmt::ContinueStmtClass: {
613 std::string sbuf;
614 llvm::raw_string_ostream os(sbuf);
615 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
616 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
617 os.str()));
618 break;
619 }
620
621 // Determine control-flow for ternary '?'.
622 case Stmt::ConditionalOperatorClass: {
623 std::string sbuf;
624 llvm::raw_string_ostream os(sbuf);
625 os << "'?' condition is ";
626
627 if (*(Src->succ_begin()+1) == Dst)
628 os << "false";
629 else
630 os << "true";
631
632 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
633
634 if (const Stmt *S = End.asStmt())
635 End = PDB.getEnclosingStmtLocation(S);
636
637 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
638 os.str()));
639 break;
640 }
641
642 // Determine control-flow for short-circuited '&&' and '||'.
643 case Stmt::BinaryOperatorClass: {
644 if (!PDB.supportsLogicalOpControlFlow())
645 break;
646
647 BinaryOperator *B = cast<BinaryOperator>(T);
648 std::string sbuf;
649 llvm::raw_string_ostream os(sbuf);
650 os << "Left side of '";
651
652 if (B->getOpcode() == BinaryOperator::LAnd) {
653 os << "&&" << "' is ";
654
655 if (*(Src->succ_begin()+1) == Dst) {
656 os << "false";
657 PathDiagnosticLocation End(B->getLHS(), SMgr);
658 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
659 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
660 os.str()));
661 }
662 else {
663 os << "true";
664 PathDiagnosticLocation Start(B->getLHS(), SMgr);
665 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
666 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
667 os.str()));
668 }
669 }
670 else {
671 assert(B->getOpcode() == BinaryOperator::LOr);
672 os << "||" << "' is ";
673
674 if (*(Src->succ_begin()+1) == Dst) {
675 os << "false";
676 PathDiagnosticLocation Start(B->getLHS(), SMgr);
677 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
678 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
679 os.str()));
680 }
681 else {
682 os << "true";
683 PathDiagnosticLocation End(B->getLHS(), SMgr);
684 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
685 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
686 os.str()));
687 }
688 }
689
690 break;
691 }
692
693 case Stmt::DoStmtClass: {
694 if (*(Src->succ_begin()) == Dst) {
695 std::string sbuf;
696 llvm::raw_string_ostream os(sbuf);
697
698 os << "Loop condition is true. ";
699 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
700
701 if (const Stmt *S = End.asStmt())
702 End = PDB.getEnclosingStmtLocation(S);
703
704 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
705 os.str()));
706 }
707 else {
708 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
709
710 if (const Stmt *S = End.asStmt())
711 End = PDB.getEnclosingStmtLocation(S);
712
713 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
714 "Loop condition is false. Exiting loop"));
715 }
716
717 break;
718 }
719
720 case Stmt::WhileStmtClass:
721 case Stmt::ForStmtClass: {
722 if (*(Src->succ_begin()+1) == Dst) {
723 std::string sbuf;
724 llvm::raw_string_ostream os(sbuf);
725
726 os << "Loop condition is false. ";
727 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
728 if (const Stmt *S = End.asStmt())
729 End = PDB.getEnclosingStmtLocation(S);
730
731 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
732 os.str()));
733 }
734 else {
735 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
736 if (const Stmt *S = End.asStmt())
737 End = PDB.getEnclosingStmtLocation(S);
738
739 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000740 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000741 }
742
743 break;
744 }
745
746 case Stmt::IfStmtClass: {
747 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
748
749 if (const Stmt *S = End.asStmt())
750 End = PDB.getEnclosingStmtLocation(S);
751
752 if (*(Src->succ_begin()+1) == Dst)
753 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000754 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000755 else
756 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000757 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000758
759 break;
760 }
761 }
762 }
763
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000764 if (NextNode) {
765 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
766 E = PDB.visitor_end(); I!=E; ++I) {
767 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
768 PD.push_front(p);
769 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000770 }
Ted Kremenek31061982009-03-31 23:00:32 +0000771
772 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
773 // Scan the region bindings, and see if a "notable" symbol has a new
774 // lval binding.
775 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
776 PDB.getStateManager().iterBindings(N->getState(), SNS);
777 }
778 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000779
780 // After constructing the full PathDiagnostic, do a pass over it to compact
781 // PathDiagnosticPieces that occur within a macro.
782 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000783}
784
785//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000786// "Extensive" PathDiagnostic generation.
787//===----------------------------------------------------------------------===//
788
789static bool IsControlFlowExpr(const Stmt *S) {
790 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000791
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000792 if (!E)
793 return false;
794
795 E = E->IgnoreParenCasts();
796
797 if (isa<ConditionalOperator>(E))
798 return true;
799
800 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
801 if (B->isLogicalOp())
802 return true;
803
804 return false;
805}
806
Ted Kremenek14856d72009-04-06 23:06:54 +0000807namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000808class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
809 bool IsDead;
810public:
811 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
812 : PathDiagnosticLocation(L), IsDead(isdead) {}
813
814 void markDead() { IsDead = true; }
815 bool isDead() const { return IsDead; }
816};
817
Ted Kremenek14856d72009-04-06 23:06:54 +0000818class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000819 std::vector<ContextLocation> CLocs;
820 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000821 PathDiagnostic &PD;
822 PathDiagnosticBuilder &PDB;
823 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000824
825 bool IsConsumedExpr(const PathDiagnosticLocation &L);
826
Ted Kremenek14856d72009-04-06 23:06:54 +0000827 bool containsLocation(const PathDiagnosticLocation &Container,
828 const PathDiagnosticLocation &Containee);
829
830 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000831
Ted Kremenek9650cf32009-05-11 21:42:34 +0000832 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
833 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000834 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000835 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000836 while (1) {
837 // Adjust the location for some expressions that are best referenced
838 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000839 switch (S->getStmtClass()) {
840 default:
841 break;
842 case Stmt::ParenExprClass:
843 S = cast<ParenExpr>(S)->IgnoreParens();
844 firstCharOnly = true;
845 continue;
846 case Stmt::ConditionalOperatorClass:
847 S = cast<ConditionalOperator>(S)->getCond();
848 firstCharOnly = true;
849 continue;
850 case Stmt::ChooseExprClass:
851 S = cast<ChooseExpr>(S)->getCond();
852 firstCharOnly = true;
853 continue;
854 case Stmt::BinaryOperatorClass:
855 S = cast<BinaryOperator>(S)->getLHS();
856 firstCharOnly = true;
857 continue;
858 }
859
860 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000861 }
862
Ted Kremenek9650cf32009-05-11 21:42:34 +0000863 if (S != Original)
864 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000865 }
866
Ted Kremenek9650cf32009-05-11 21:42:34 +0000867 if (firstCharOnly)
868 L = PathDiagnosticLocation(L.asLocation());
869
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000870 return L;
871 }
872
Ted Kremenek14856d72009-04-06 23:06:54 +0000873 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000874 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000875 // For contexts, we only one the first character as the range.
Ted Kremenek07c015c2009-05-15 02:46:13 +0000876 rawAddEdge(cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000877 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000878 CLocs.pop_back();
879 }
880
881 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
882
883public:
884 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
885 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000886
887 // If the PathDiagnostic already has pieces, add the enclosing statement
888 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000889 if (!PD.empty()) {
890 PrevLoc = PD.begin()->getLocation();
891
892 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000893 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000894 }
895 }
896
897 ~EdgeBuilder() {
898 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000899
900 // Finally, add an initial edge from the start location of the first
901 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000902 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
903 if (const CompoundStmt *CS =
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000904 PDB.getCodeDecl().getCompoundBody())
Ted Kremeneka301a672009-04-22 18:16:20 +0000905 if (!CS->body_empty()) {
906 SourceLocation Loc = (*CS->body_begin())->getLocStart();
907 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
908 }
909
Ted Kremenek14856d72009-04-06 23:06:54 +0000910 }
911
912 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
913
914 void addEdge(const Stmt *S, bool alwaysAdd = false) {
915 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
916 }
917
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000918 void rawAddEdge(PathDiagnosticLocation NewLoc);
919
Ted Kremenek14856d72009-04-06 23:06:54 +0000920 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000921 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000922};
923} // end anonymous namespace
924
925
926PathDiagnosticLocation
927EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
928 if (const Stmt *S = L.asStmt()) {
929 if (IsControlFlowExpr(S))
930 return L;
931
932 return PDB.getEnclosingStmtLocation(S);
933 }
934
935 return L;
936}
937
938bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
939 const PathDiagnosticLocation &Containee) {
940
941 if (Container == Containee)
942 return true;
943
944 if (Container.asDecl())
945 return true;
946
947 if (const Stmt *S = Containee.asStmt())
948 if (const Stmt *ContainerS = Container.asStmt()) {
949 while (S) {
950 if (S == ContainerS)
951 return true;
952 S = PDB.getParent(S);
953 }
954 return false;
955 }
956
957 // Less accurate: compare using source ranges.
958 SourceRange ContainerR = Container.asRange();
959 SourceRange ContaineeR = Containee.asRange();
960
961 SourceManager &SM = PDB.getSourceManager();
962 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
963 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
964 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
965 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
966
967 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
968 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
969 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
970 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
971
972 assert(ContainerBegLine <= ContainerEndLine);
973 assert(ContaineeBegLine <= ContaineeEndLine);
974
975 return (ContainerBegLine <= ContaineeBegLine &&
976 ContainerEndLine >= ContaineeEndLine &&
977 (ContainerBegLine != ContaineeBegLine ||
978 SM.getInstantiationColumnNumber(ContainerRBeg) <=
979 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
980 (ContainerEndLine != ContaineeEndLine ||
981 SM.getInstantiationColumnNumber(ContainerREnd) >=
982 SM.getInstantiationColumnNumber(ContainerREnd)));
983}
984
985PathDiagnosticLocation
986EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
987 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
988 return PathDiagnosticLocation(E->IgnoreParenCasts(),
989 PDB.getSourceManager());
990 return L;
991}
992
993void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
994 if (!PrevLoc.isValid()) {
995 PrevLoc = NewLoc;
996 return;
997 }
998
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000999 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
1000 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
1001
1002 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +00001003 return;
1004
1005 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001006 if (NewLocClean.asLocation().getInstantiationLoc() ==
1007 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +00001008 return;
1009
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +00001010 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
1011 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +00001012}
1013
1014void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +00001015
1016 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
1017 return;
1018
Ted Kremenek14856d72009-04-06 23:06:54 +00001019 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
1020
1021 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001022 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +00001023
1024 // Is the top location context the same as the one for the new location?
1025 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001026 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001027 if (IsConsumedExpr(TopContextLoc) &&
1028 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001029 TopContextLoc.markDead();
1030
Ted Kremenek14856d72009-04-06 23:06:54 +00001031 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001032 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001033
1034 return;
1035 }
1036
1037 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001038 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001039 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001040
Ted Kremenek4c6f8d32009-05-04 18:15:17 +00001041 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001042 CLocs.push_back(ContextLocation(CLoc, true));
1043 return;
1044 }
1045 }
1046
Ted Kremenek14856d72009-04-06 23:06:54 +00001047 CLocs.push_back(CLoc);
1048 return;
1049 }
1050
1051 // Context does not contain the location. Flush it.
1052 popLocation();
1053 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001054
1055 // If we reach here, there is no enclosing context. Just add the edge.
1056 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001057}
1058
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001059bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1060 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1061 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1062
1063 return false;
1064}
1065
Ted Kremeneke1baed32009-05-05 23:13:38 +00001066void EdgeBuilder::addExtendedContext(const Stmt *S) {
1067 if (!S)
1068 return;
1069
1070 const Stmt *Parent = PDB.getParent(S);
1071 while (Parent) {
1072 if (isa<CompoundStmt>(Parent))
1073 Parent = PDB.getParent(Parent);
1074 else
1075 break;
1076 }
1077
1078 if (Parent) {
1079 switch (Parent->getStmtClass()) {
1080 case Stmt::DoStmtClass:
1081 case Stmt::ObjCAtSynchronizedStmtClass:
1082 addContext(Parent);
1083 default:
1084 break;
1085 }
1086 }
1087
1088 addContext(S);
1089}
1090
Ted Kremenek14856d72009-04-06 23:06:54 +00001091void EdgeBuilder::addContext(const Stmt *S) {
1092 if (!S)
1093 return;
1094
1095 PathDiagnosticLocation L(S, PDB.getSourceManager());
1096
1097 while (!CLocs.empty()) {
1098 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1099
1100 // Is the top location context the same as the one for the new location?
1101 if (TopContextLoc == L)
1102 return;
1103
1104 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001105 CLocs.push_back(L);
1106 return;
1107 }
1108
1109 // Context does not contain the location. Flush it.
1110 popLocation();
1111 }
1112
1113 CLocs.push_back(L);
1114}
1115
1116static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1117 PathDiagnosticBuilder &PDB,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001118 const ExplodedNode *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001119
1120
1121 EdgeBuilder EB(PD, PDB);
1122
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001123 const ExplodedNode* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001124 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001125 while (NextNode) {
1126 N = NextNode;
1127 NextNode = GetPredecessorNode(N);
1128 ProgramPoint P = N->getLocation();
1129
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001130 do {
1131 // Block edges.
1132 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1133 const CFGBlock &Blk = *BE->getSrc();
1134 const Stmt *Term = Blk.getTerminator();
1135
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001136 // Are we jumping to the head of a loop? Add a special diagnostic.
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001137 if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001138 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001139 const CompoundStmt *CS = NULL;
1140
1141 if (!Term) {
1142 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1143 CS = dyn_cast<CompoundStmt>(FS->getBody());
1144 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1145 CS = dyn_cast<CompoundStmt>(WS->getBody());
1146 }
1147
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001148 PathDiagnosticEventPiece *p =
1149 new PathDiagnosticEventPiece(L,
Ted Kremenek07c015c2009-05-15 02:46:13 +00001150 "Looping back to the head of the loop");
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001151
1152 EB.addEdge(p->getLocation(), true);
1153 PD.push_front(p);
1154
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001155 if (CS) {
Ted Kremenek07c015c2009-05-15 02:46:13 +00001156 PathDiagnosticLocation BL(CS->getRBracLoc(),
1157 PDB.getSourceManager());
1158 BL = PathDiagnosticLocation(BL.asLocation());
1159 EB.addEdge(BL);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001160 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001161 }
Ted Kremenekddb7bab2009-05-15 01:50:15 +00001162
1163 if (Term)
1164 EB.addContext(Term);
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001165
1166 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001167 }
1168
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001169 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1170 if (const Stmt* S = BE->getFirstStmt()) {
1171 if (IsControlFlowExpr(S)) {
1172 // Add the proper context for '&&', '||', and '?'.
1173 EB.addContext(S);
1174 }
1175 else
1176 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1177 }
1178
1179 break;
1180 }
1181 } while (0);
1182
1183 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001184 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001185
Ted Kremenek8966bc12009-05-06 21:39:49 +00001186 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1187 E = PDB.visitor_end(); I!=E; ++I) {
1188 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1189 const PathDiagnosticLocation &Loc = p->getLocation();
1190 EB.addEdge(Loc, true);
1191 PD.push_front(p);
1192 if (const Stmt *S = Loc.asStmt())
1193 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1194 }
1195 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001196 }
1197}
1198
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001199//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001200// Methods for BugType and subclasses.
1201//===----------------------------------------------------------------------===//
1202BugType::~BugType() {}
1203void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001204
Ted Kremenekcf118d42009-02-04 23:49:09 +00001205//===----------------------------------------------------------------------===//
1206// Methods for BugReport and subclasses.
1207//===----------------------------------------------------------------------===//
1208BugReport::~BugReport() {}
1209RangedBugReport::~RangedBugReport() {}
1210
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001211const Stmt* BugReport::getStmt() const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001212 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenek5f85e172009-07-22 22:35:28 +00001213 const Stmt *S = NULL;
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001214
Ted Kremenekcf118d42009-02-04 23:49:09 +00001215 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Zhongxing Xufafd3832009-08-20 01:23:34 +00001216 CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001217 if (BE->getBlock() == &Exit)
1218 S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001219 }
Ted Kremenek5f85e172009-07-22 22:35:28 +00001220 if (!S)
1221 S = GetStmt(ProgP);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001222
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001223 return S;
1224}
1225
1226PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001227BugReport::getEndPath(BugReporterContext& BRC,
Zhongxing Xuc5619d92009-08-06 01:32:16 +00001228 const ExplodedNode* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001229
Zhongxing Xu50d5bc42009-08-18 08:46:04 +00001230 const Stmt* S = getStmt();
Ted Kremenek61f3e052008-04-03 04:42:52 +00001231
1232 if (!S)
1233 return NULL;
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001234
Ted Kremenekde7161f2008-04-03 18:00:37 +00001235 const SourceRange *Beg, *End;
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001236 getRanges(Beg, End);
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001237 PathDiagnosticLocation L(S, BRC.getSourceManager());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001238
Ted Kremenek3ef538d2009-05-11 23:50:59 +00001239 // Only add the statement itself as a range if we didn't specify any
1240 // special ranges for this report.
1241 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription(),
1242 Beg == End);
1243
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001244 for (; Beg != End; ++Beg)
1245 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001246
1247 return P;
1248}
1249
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001250void BugReport::getRanges(const SourceRange*& beg, const SourceRange*& end) {
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;
Zhongxing Xu292a5c02009-08-18 08:58:41 +00001660 R.getRanges(Beg, End);
Ted Kremenek3148eb42009-01-24 00:55:43 +00001661 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}