blob: 7e7132aaab70086204e089d9b244fdd01a55872a [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
11// PathDiagnostics for analyses based on GRSimpleVals.
12//
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/Basic/SourceManager.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CFG.h"
21#include "clang/AST/Expr.h"
Ted Kremenek00605e02009-03-27 20:55:39 +000022#include "clang/AST/ParentMap.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 Kremenekcf118d42009-02-04 23:49:09 +000033//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +000034// Helper routines for walking the ExplodedGraph and fetching statements.
Ted Kremenekcf118d42009-02-04 23:49:09 +000035//===----------------------------------------------------------------------===//
Ted Kremenek61f3e052008-04-03 04:42:52 +000036
Ted Kremenekb697b102009-02-23 22:44:26 +000037static inline Stmt* GetStmt(ProgramPoint P) {
38 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000039 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000040 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000041 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000042
Ted Kremenekb697b102009-02-23 22:44:26 +000043 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000044}
45
Ted Kremenek3148eb42009-01-24 00:55:43 +000046static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000047GetPredecessorNode(const ExplodedNode<GRState>* N) {
Ted Kremenekbd7efa82008-04-17 23:44:37 +000048 return N->pred_empty() ? NULL : *(N->pred_begin());
49}
Ted Kremenek2673c9f2008-04-25 19:01:27 +000050
Ted Kremenekb697b102009-02-23 22:44:26 +000051static inline const ExplodedNode<GRState>*
52GetSuccessorNode(const ExplodedNode<GRState>* N) {
53 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000054}
55
Ted Kremenekb697b102009-02-23 22:44:26 +000056static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
57 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
58 if (Stmt *S = GetStmt(N->getLocation()))
59 return S;
60
61 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000062}
63
Ted Kremenekb697b102009-02-23 22:44:26 +000064static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
65 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000066 if (Stmt *S = GetStmt(N->getLocation())) {
67 // Check if the statement is '?' or '&&'/'||'. These are "merges",
68 // not actual statement points.
69 switch (S->getStmtClass()) {
70 case Stmt::ChooseExprClass:
71 case Stmt::ConditionalOperatorClass: continue;
72 case Stmt::BinaryOperatorClass: {
73 BinaryOperator::Opcode Op = cast<BinaryOperator>(S)->getOpcode();
74 if (Op == BinaryOperator::LAnd || Op == BinaryOperator::LOr)
75 continue;
76 break;
77 }
78 default:
79 break;
80 }
Ted Kremenekb697b102009-02-23 22:44:26 +000081 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000082 }
Ted Kremenekb697b102009-02-23 22:44:26 +000083
84 return 0;
85}
86
87static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
88 if (Stmt *S = GetStmt(N->getLocation()))
89 return S;
90
91 return GetPreviousStmt(N);
92}
93
94static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
95 if (Stmt *S = GetStmt(N->getLocation()))
96 return S;
97
98 return GetNextStmt(N);
99}
100
101//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000102// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000103//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000104
Ted Kremenek7dc86642009-03-31 20:22:36 +0000105typedef llvm::DenseMap<const ExplodedNode<GRState>*,
106const ExplodedNode<GRState>*> NodeBackMap;
107
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000108namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000109class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
110 NodeBackMap& M;
111public:
112 NodeMapClosure(NodeBackMap *m) : M(*m) {}
113 ~NodeMapClosure() {}
114
115 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
116 NodeBackMap::iterator I = M.find(N);
117 return I == M.end() ? 0 : I->second;
118 }
119};
120
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000121class VISIBILITY_HIDDEN PathDiagnosticBuilder {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000122 GRBugReporter &BR;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000123 SourceManager &SMgr;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000124 ExplodedGraph<GRState> *ReportGraph;
125 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000126 const Decl& CodeDecl;
127 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000128 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000129 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000130public:
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 PathDiagnosticBuilder(GRBugReporter &br, ExplodedGraph<GRState> *reportGraph,
132 BugReport *r, NodeBackMap *Backmap,
133 const Decl& codedecl, PathDiagnosticClient *pdc)
134 : BR(br), SMgr(BR.getSourceManager()), ReportGraph(reportGraph), R(r),
135 CodeDecl(codedecl), PDC(pdc), NMC(Backmap) {}
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000136
Ted Kremenek00605e02009-03-27 20:55:39 +0000137 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000138
Ted Kremenek00605e02009-03-27 20:55:39 +0000139 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
140 const ExplodedNode<GRState>* N);
141
142 ParentMap& getParentMap() {
Douglas Gregor72971342009-04-18 00:02:19 +0000143 if (PM.get() == 0) PM.reset(new ParentMap(CodeDecl.getBody(getContext())));
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 return *PM.get();
145 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000146
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000147 const Stmt *getParent(const Stmt *S) {
148 return getParentMap().getParent(S);
149 }
150
Ted Kremenek51a735c2009-04-01 17:52:26 +0000151 const CFG& getCFG() {
152 return *BR.getCFG();
153 }
154
155 const Decl& getCodeDecl() {
156 return BR.getStateManager().getCodeDecl();
157 }
158
Ted Kremenek7dc86642009-03-31 20:22:36 +0000159 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
160 NodeMapClosure& getNodeMapClosure() { return NMC; }
161 ASTContext& getContext() { return BR.getContext(); }
162 SourceManager& getSourceManager() { return SMgr; }
163 BugReport& getReport() { return *R; }
164 GRBugReporter& getBugReporter() { return BR; }
165 GRStateManager& getStateManager() { return BR.getStateManager(); }
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
188PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
189 if (Stmt *S = GetNextStmt(N))
190 return PathDiagnosticLocation(S, SMgr);
191
Douglas Gregor72971342009-04-18 00:02:19 +0000192 return FullSourceLoc(CodeDecl.getBody(getContext())->getRBracLoc(), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000193}
194
Ted Kremenek00605e02009-03-27 20:55:39 +0000195PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000196PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
197 const ExplodedNode<GRState>* N) {
198
Ted Kremenek143ca222008-05-06 18:11:09 +0000199 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 if (os.str().empty())
201 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000202
Ted Kremenek00605e02009-03-27 20:55:39 +0000203 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000204
Ted Kremenek00605e02009-03-27 20:55:39 +0000205 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000206 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000207 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000208 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000209 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000210 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000211
212 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000213}
214
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000215PathDiagnosticLocation
216PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
217 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
218 ParentMap &P = getParentMap();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000219
220 while (isa<DeclStmt>(S) || isa<Expr>(S)) {
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000221 const Stmt *Parent = P.getParent(S);
222
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000223 if (!Parent)
224 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000225
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000226 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000227 case Stmt::BinaryOperatorClass: {
228 const BinaryOperator *B = cast<BinaryOperator>(Parent);
229 if (B->isLogicalOp())
230 return PathDiagnosticLocation(S, SMgr);
231 break;
232 }
233
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000234 case Stmt::CompoundStmtClass:
235 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000236 return PathDiagnosticLocation(S, SMgr);
237 case Stmt::ChooseExprClass:
238 // Similar to '?' if we are referring to condition, just have the edge
239 // point to the entire choose expression.
240 if (cast<ChooseExpr>(Parent)->getCond() == S)
241 return PathDiagnosticLocation(Parent, SMgr);
242 else
243 return PathDiagnosticLocation(S, SMgr);
244 case Stmt::ConditionalOperatorClass:
245 // For '?', if we are referring to condition, just have the edge point
246 // to the entire '?' expression.
247 if (cast<ConditionalOperator>(Parent)->getCond() == S)
248 return PathDiagnosticLocation(Parent, SMgr);
249 else
250 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000251 case Stmt::DoStmtClass:
252 if (cast<DoStmt>(Parent)->getCond() != S)
253 return PathDiagnosticLocation(S, SMgr);
254 break;
255 case Stmt::ForStmtClass:
256 if (cast<ForStmt>(Parent)->getBody() == S)
257 return PathDiagnosticLocation(S, SMgr);
258 break;
259 case Stmt::IfStmtClass:
260 if (cast<IfStmt>(Parent)->getCond() != S)
261 return PathDiagnosticLocation(S, SMgr);
262 break;
263 case Stmt::ObjCForCollectionStmtClass:
264 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
265 return PathDiagnosticLocation(S, SMgr);
266 break;
267 case Stmt::WhileStmtClass:
268 if (cast<WhileStmt>(Parent)->getCond() != S)
269 return PathDiagnosticLocation(S, SMgr);
270 break;
271 default:
272 break;
273 }
274
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000275 S = Parent;
276 }
277
278 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
279 return PathDiagnosticLocation(S, SMgr);
280}
281
Ted Kremenekcf118d42009-02-04 23:49:09 +0000282//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000283// ScanNotableSymbols: closure-like callback for scanning Store bindings.
284//===----------------------------------------------------------------------===//
285
286static const VarDecl*
287GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
288 GRStateManager& VMgr, SVal X) {
289
290 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
291
292 ProgramPoint P = N->getLocation();
293
294 if (!isa<PostStmt>(P))
295 continue;
296
297 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
298
299 if (!DR)
300 continue;
301
302 SVal Y = VMgr.GetSVal(N->getState(), DR);
303
304 if (X != Y)
305 continue;
306
307 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
308
309 if (!VD)
310 continue;
311
312 return VD;
313 }
314
315 return 0;
316}
317
318namespace {
319class VISIBILITY_HIDDEN NotableSymbolHandler
320: public StoreManager::BindingsHandler {
321
322 SymbolRef Sym;
323 const GRState* PrevSt;
324 const Stmt* S;
325 GRStateManager& VMgr;
326 const ExplodedNode<GRState>* Pred;
327 PathDiagnostic& PD;
328 BugReporter& BR;
329
330public:
331
332 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
333 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
334 PathDiagnostic& pd, BugReporter& br)
335 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
336
337 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
338 SVal V) {
339
340 SymbolRef ScanSym = V.getAsSymbol();
341
342 if (ScanSym != Sym)
343 return true;
344
345 // Check if the previous state has this binding.
346 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
347
348 if (X == V) // Same binding?
349 return true;
350
351 // Different binding. Only handle assignments for now. We don't pull
352 // this check out of the loop because we will eventually handle other
353 // cases.
354
355 VarDecl *VD = 0;
356
357 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
358 if (!B->isAssignmentOp())
359 return true;
360
361 // What variable did we assign to?
362 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
363
364 if (!DR)
365 return true;
366
367 VD = dyn_cast<VarDecl>(DR->getDecl());
368 }
369 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
370 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
371 // assume that each DeclStmt has a single Decl. This invariant
372 // holds by contruction in the CFG.
373 VD = dyn_cast<VarDecl>(*DS->decl_begin());
374 }
375
376 if (!VD)
377 return true;
378
379 // What is the most recently referenced variable with this binding?
380 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
381
382 if (!MostRecent)
383 return true;
384
385 // Create the diagnostic.
386 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
387
388 if (Loc::IsLocType(VD->getType())) {
389 std::string msg = "'" + std::string(VD->getNameAsString()) +
390 "' now aliases '" + MostRecent->getNameAsString() + "'";
391
392 PD.push_front(new PathDiagnosticEventPiece(L, msg));
393 }
394
395 return true;
396 }
397};
398}
399
400static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
401 const Stmt* S,
402 SymbolRef Sym, BugReporter& BR,
403 PathDiagnostic& PD) {
404
405 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
406 const GRState* PrevSt = Pred ? Pred->getState() : 0;
407
408 if (!PrevSt)
409 return;
410
411 // Look at the region bindings of the current state that map to the
412 // specified symbol. Are any of them not in the previous state?
413 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
414 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
415 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
416}
417
418namespace {
419class VISIBILITY_HIDDEN ScanNotableSymbols
420: public StoreManager::BindingsHandler {
421
422 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
423 const ExplodedNode<GRState>* N;
424 Stmt* S;
425 GRBugReporter& BR;
426 PathDiagnostic& PD;
427
428public:
429 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
430 PathDiagnostic& pd)
431 : N(n), S(s), BR(br), PD(pd) {}
432
433 bool HandleBinding(StoreManager& SMgr, Store store,
434 const MemRegion* R, SVal V) {
435
436 SymbolRef ScanSym = V.getAsSymbol();
437
438 if (!ScanSym)
439 return true;
440
441 if (!BR.isNotable(ScanSym))
442 return true;
443
444 if (AlreadyProcessed.count(ScanSym))
445 return true;
446
447 AlreadyProcessed.insert(ScanSym);
448
449 HandleNotableSymbol(N, S, ScanSym, BR, PD);
450 return true;
451 }
452};
453} // end anonymous namespace
454
455//===----------------------------------------------------------------------===//
456// "Minimal" path diagnostic generation algorithm.
457//===----------------------------------------------------------------------===//
458
Ted Kremenek14856d72009-04-06 23:06:54 +0000459static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
460
Ted Kremenek31061982009-03-31 23:00:32 +0000461static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
462 PathDiagnosticBuilder &PDB,
463 const ExplodedNode<GRState> *N) {
464 ASTContext& Ctx = PDB.getContext();
465 SourceManager& SMgr = PDB.getSourceManager();
466 const ExplodedNode<GRState>* NextNode = N->pred_empty()
467 ? NULL : *(N->pred_begin());
468 while (NextNode) {
469 N = NextNode;
470 NextNode = GetPredecessorNode(N);
471
472 ProgramPoint P = N->getLocation();
473
474 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
475 CFGBlock* Src = BE->getSrc();
476 CFGBlock* Dst = BE->getDst();
477 Stmt* T = Src->getTerminator();
478
479 if (!T)
480 continue;
481
482 FullSourceLoc Start(T->getLocStart(), SMgr);
483
484 switch (T->getStmtClass()) {
485 default:
486 break;
487
488 case Stmt::GotoStmtClass:
489 case Stmt::IndirectGotoStmtClass: {
490 Stmt* S = GetNextStmt(N);
491
492 if (!S)
493 continue;
494
495 std::string sbuf;
496 llvm::raw_string_ostream os(sbuf);
497 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
498
499 os << "Control jumps to line "
500 << End.asLocation().getInstantiationLineNumber();
501 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
502 os.str()));
503 break;
504 }
505
506 case Stmt::SwitchStmtClass: {
507 // Figure out what case arm we took.
508 std::string sbuf;
509 llvm::raw_string_ostream os(sbuf);
510
511 if (Stmt* S = Dst->getLabel()) {
512 PathDiagnosticLocation End(S, SMgr);
513
514 switch (S->getStmtClass()) {
515 default:
516 os << "No cases match in the switch statement. "
517 "Control jumps to line "
518 << End.asLocation().getInstantiationLineNumber();
519 break;
520 case Stmt::DefaultStmtClass:
521 os << "Control jumps to the 'default' case at line "
522 << End.asLocation().getInstantiationLineNumber();
523 break;
524
525 case Stmt::CaseStmtClass: {
526 os << "Control jumps to 'case ";
527 CaseStmt* Case = cast<CaseStmt>(S);
528 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
529
530 // Determine if it is an enum.
531 bool GetRawInt = true;
532
533 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
534 // FIXME: Maybe this should be an assertion. Are there cases
535 // were it is not an EnumConstantDecl?
536 EnumConstantDecl* D =
537 dyn_cast<EnumConstantDecl>(DR->getDecl());
538
539 if (D) {
540 GetRawInt = false;
541 os << D->getNameAsString();
542 }
543 }
544
545 if (GetRawInt) {
546
547 // Not an enum.
548 Expr* CondE = cast<SwitchStmt>(T)->getCond();
549 unsigned bits = Ctx.getTypeSize(CondE->getType());
550 llvm::APSInt V(bits, false);
551
552 if (!LHS->isIntegerConstantExpr(V, Ctx, 0, true)) {
553 assert (false && "Case condition must be constant.");
554 continue;
555 }
556
557 os << V;
558 }
559
560 os << ":' at line "
561 << End.asLocation().getInstantiationLineNumber();
562 break;
563 }
564 }
565 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
566 os.str()));
567 }
568 else {
569 os << "'Default' branch taken. ";
570 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
571 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
572 os.str()));
573 }
574
575 break;
576 }
577
578 case Stmt::BreakStmtClass:
579 case Stmt::ContinueStmtClass: {
580 std::string sbuf;
581 llvm::raw_string_ostream os(sbuf);
582 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
583 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
584 os.str()));
585 break;
586 }
587
588 // Determine control-flow for ternary '?'.
589 case Stmt::ConditionalOperatorClass: {
590 std::string sbuf;
591 llvm::raw_string_ostream os(sbuf);
592 os << "'?' condition is ";
593
594 if (*(Src->succ_begin()+1) == Dst)
595 os << "false";
596 else
597 os << "true";
598
599 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
600
601 if (const Stmt *S = End.asStmt())
602 End = PDB.getEnclosingStmtLocation(S);
603
604 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
605 os.str()));
606 break;
607 }
608
609 // Determine control-flow for short-circuited '&&' and '||'.
610 case Stmt::BinaryOperatorClass: {
611 if (!PDB.supportsLogicalOpControlFlow())
612 break;
613
614 BinaryOperator *B = cast<BinaryOperator>(T);
615 std::string sbuf;
616 llvm::raw_string_ostream os(sbuf);
617 os << "Left side of '";
618
619 if (B->getOpcode() == BinaryOperator::LAnd) {
620 os << "&&" << "' is ";
621
622 if (*(Src->succ_begin()+1) == Dst) {
623 os << "false";
624 PathDiagnosticLocation End(B->getLHS(), SMgr);
625 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
626 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
627 os.str()));
628 }
629 else {
630 os << "true";
631 PathDiagnosticLocation Start(B->getLHS(), SMgr);
632 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
633 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
634 os.str()));
635 }
636 }
637 else {
638 assert(B->getOpcode() == BinaryOperator::LOr);
639 os << "||" << "' is ";
640
641 if (*(Src->succ_begin()+1) == Dst) {
642 os << "false";
643 PathDiagnosticLocation Start(B->getLHS(), SMgr);
644 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
645 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
646 os.str()));
647 }
648 else {
649 os << "true";
650 PathDiagnosticLocation End(B->getLHS(), SMgr);
651 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
652 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
653 os.str()));
654 }
655 }
656
657 break;
658 }
659
660 case Stmt::DoStmtClass: {
661 if (*(Src->succ_begin()) == Dst) {
662 std::string sbuf;
663 llvm::raw_string_ostream os(sbuf);
664
665 os << "Loop condition is true. ";
666 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
667
668 if (const Stmt *S = End.asStmt())
669 End = PDB.getEnclosingStmtLocation(S);
670
671 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
672 os.str()));
673 }
674 else {
675 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
676
677 if (const Stmt *S = End.asStmt())
678 End = PDB.getEnclosingStmtLocation(S);
679
680 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
681 "Loop condition is false. Exiting loop"));
682 }
683
684 break;
685 }
686
687 case Stmt::WhileStmtClass:
688 case Stmt::ForStmtClass: {
689 if (*(Src->succ_begin()+1) == Dst) {
690 std::string sbuf;
691 llvm::raw_string_ostream os(sbuf);
692
693 os << "Loop condition is false. ";
694 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
695 if (const Stmt *S = End.asStmt())
696 End = PDB.getEnclosingStmtLocation(S);
697
698 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
699 os.str()));
700 }
701 else {
702 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
703 if (const Stmt *S = End.asStmt())
704 End = PDB.getEnclosingStmtLocation(S);
705
706 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000707 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000708 }
709
710 break;
711 }
712
713 case Stmt::IfStmtClass: {
714 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
715
716 if (const Stmt *S = End.asStmt())
717 End = PDB.getEnclosingStmtLocation(S);
718
719 if (*(Src->succ_begin()+1) == Dst)
720 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000721 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000722 else
723 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000724 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000725
726 break;
727 }
728 }
729 }
730
731 if (PathDiagnosticPiece* p =
732 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
733 PDB.getBugReporter(),
734 PDB.getNodeMapClosure())) {
735 PD.push_front(p);
736 }
737
738 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
739 // Scan the region bindings, and see if a "notable" symbol has a new
740 // lval binding.
741 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
742 PDB.getStateManager().iterBindings(N->getState(), SNS);
743 }
744 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000745
746 // After constructing the full PathDiagnostic, do a pass over it to compact
747 // PathDiagnosticPieces that occur within a macro.
748 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000749}
750
751//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000752// "Extensive" PathDiagnostic generation.
753//===----------------------------------------------------------------------===//
754
755static bool IsControlFlowExpr(const Stmt *S) {
756 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000757
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000758 if (!E)
759 return false;
760
761 E = E->IgnoreParenCasts();
762
763 if (isa<ConditionalOperator>(E))
764 return true;
765
766 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
767 if (B->isLogicalOp())
768 return true;
769
770 return false;
771}
772
Ted Kremenek14856d72009-04-06 23:06:54 +0000773#if 1
774
775namespace {
776class VISIBILITY_HIDDEN EdgeBuilder {
777 std::vector<PathDiagnosticLocation> CLocs;
778 typedef std::vector<PathDiagnosticLocation>::iterator iterator;
779 PathDiagnostic &PD;
780 PathDiagnosticBuilder &PDB;
781 PathDiagnosticLocation PrevLoc;
782
783 bool containsLocation(const PathDiagnosticLocation &Container,
784 const PathDiagnosticLocation &Containee);
785
786 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
787 void rawAddEdge(PathDiagnosticLocation NewLoc);
788
789 void popLocation() {
790 rawAddEdge(CLocs.back());
791 CLocs.pop_back();
792 }
793
794 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
795
796public:
797 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
798 : PD(pd), PDB(pdb) {
799 CLocs.push_back(PathDiagnosticLocation(&PDB.getCodeDecl(),
800 PDB.getSourceManager()));
801 if (!PD.empty()) {
802 PrevLoc = PD.begin()->getLocation();
803
804 if (const Stmt *S = PrevLoc.asStmt())
805 addContext(PDB.getEnclosingStmtLocation(S).asStmt());
806 }
807 }
808
809 ~EdgeBuilder() {
810 while (!CLocs.empty()) popLocation();
811 }
812
813 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
814
815 void addEdge(const Stmt *S, bool alwaysAdd = false) {
816 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
817 }
818
819 void addContext(const Stmt *S);
820};
821} // end anonymous namespace
822
823
824PathDiagnosticLocation
825EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
826 if (const Stmt *S = L.asStmt()) {
827 if (IsControlFlowExpr(S))
828 return L;
829
830 return PDB.getEnclosingStmtLocation(S);
831 }
832
833 return L;
834}
835
836bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
837 const PathDiagnosticLocation &Containee) {
838
839 if (Container == Containee)
840 return true;
841
842 if (Container.asDecl())
843 return true;
844
845 if (const Stmt *S = Containee.asStmt())
846 if (const Stmt *ContainerS = Container.asStmt()) {
847 while (S) {
848 if (S == ContainerS)
849 return true;
850 S = PDB.getParent(S);
851 }
852 return false;
853 }
854
855 // Less accurate: compare using source ranges.
856 SourceRange ContainerR = Container.asRange();
857 SourceRange ContaineeR = Containee.asRange();
858
859 SourceManager &SM = PDB.getSourceManager();
860 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
861 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
862 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
863 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
864
865 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
866 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
867 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
868 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
869
870 assert(ContainerBegLine <= ContainerEndLine);
871 assert(ContaineeBegLine <= ContaineeEndLine);
872
873 return (ContainerBegLine <= ContaineeBegLine &&
874 ContainerEndLine >= ContaineeEndLine &&
875 (ContainerBegLine != ContaineeBegLine ||
876 SM.getInstantiationColumnNumber(ContainerRBeg) <=
877 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
878 (ContainerEndLine != ContaineeEndLine ||
879 SM.getInstantiationColumnNumber(ContainerREnd) >=
880 SM.getInstantiationColumnNumber(ContainerREnd)));
881}
882
883PathDiagnosticLocation
884EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
885 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
886 return PathDiagnosticLocation(E->IgnoreParenCasts(),
887 PDB.getSourceManager());
888 return L;
889}
890
891void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
892 if (!PrevLoc.isValid()) {
893 PrevLoc = NewLoc;
894 return;
895 }
896
897 if (NewLoc.asLocation() == PrevLoc.asLocation())
898 return;
899
900 // FIXME: Ignore intra-macro edges for now.
901 if (NewLoc.asLocation().getInstantiationLoc() ==
902 PrevLoc.asLocation().getInstantiationLoc())
903 return;
904
905 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
906 PrevLoc = NewLoc;
907}
908
909void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
910 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
911
912 while (!CLocs.empty()) {
913 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
914
915 // Is the top location context the same as the one for the new location?
916 if (TopContextLoc == CLoc) {
Ted Kremeneke97386f2009-04-07 00:11:40 +0000917 if (alwaysAdd)
Ted Kremenek14856d72009-04-06 23:06:54 +0000918 rawAddEdge(NewLoc);
919
920 return;
921 }
922
923 if (containsLocation(TopContextLoc, CLoc)) {
924 if (alwaysAdd)
925 rawAddEdge(NewLoc);
926
927 CLocs.push_back(CLoc);
928 return;
929 }
930
931 // Context does not contain the location. Flush it.
932 popLocation();
933 }
934
935 assert(0 && "addEdge should never pop the top context");
936}
937
938void EdgeBuilder::addContext(const Stmt *S) {
939 if (!S)
940 return;
941
942 PathDiagnosticLocation L(S, PDB.getSourceManager());
943
944 while (!CLocs.empty()) {
945 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
946
947 // Is the top location context the same as the one for the new location?
948 if (TopContextLoc == L)
949 return;
950
951 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +0000952 CLocs.push_back(L);
953 return;
954 }
955
956 // Context does not contain the location. Flush it.
957 popLocation();
958 }
959
960 CLocs.push_back(L);
961}
962
963static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
964 PathDiagnosticBuilder &PDB,
965 const ExplodedNode<GRState> *N) {
966
967
968 EdgeBuilder EB(PD, PDB);
969
970 const ExplodedNode<GRState>* NextNode = N->pred_empty()
971 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +0000972 while (NextNode) {
973 N = NextNode;
974 NextNode = GetPredecessorNode(N);
975 ProgramPoint P = N->getLocation();
976
977 // Block edges.
978 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
979 const CFGBlock &Blk = *BE->getSrc();
980
981 if (const Stmt *Term = Blk.getTerminator())
982 EB.addContext(Term);
983
Ted Kremenek14856d72009-04-06 23:06:54 +0000984 continue;
985 }
986
987 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
988 if (const Stmt* S = BE->getFirstStmt()) {
989 if (IsControlFlowExpr(S))
990 EB.addContext(S);
991 else
Ted Kremenek581329c2009-04-07 04:53:35 +0000992 EB.addContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000993 }
994
995 continue;
996 }
997
998 PathDiagnosticPiece* p =
Ted Kremenek581329c2009-04-07 04:53:35 +0000999 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
1000 PDB.getBugReporter(), PDB.getNodeMapClosure());
Ted Kremenek14856d72009-04-06 23:06:54 +00001001
1002 if (p) {
1003 EB.addEdge(p->getLocation(), true);
1004 PD.push_front(p);
1005 }
1006 }
1007}
1008
1009
1010#else
1011
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001012static void GenExtAddEdge(PathDiagnostic& PD,
1013 PathDiagnosticBuilder &PDB,
1014 PathDiagnosticLocation NewLoc,
1015 PathDiagnosticLocation &PrevLoc,
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001016 bool allowBlockJump = false) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001017
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001018 if (const Stmt *S = NewLoc.asStmt()) {
1019 if (IsControlFlowExpr(S))
1020 return;
1021 }
1022
1023
1024 if (!PrevLoc.isValid()) {
1025 PrevLoc = NewLoc;
1026 return;
1027 }
1028
1029 if (NewLoc == PrevLoc)
1030 return;
Ted Kremenek14856d72009-04-06 23:06:54 +00001031
Ted Kremenek0dc65be2009-04-01 19:43:28 +00001032 // Are we jumping between statements within the same compound statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001033 if (!allowBlockJump)
1034 if (const Stmt *PS = PrevLoc.asStmt())
1035 if (const Stmt *NS = NewLoc.asStmt()) {
1036 const Stmt *parentPS = PDB.getParent(PS);
Ted Kremenek28de78b2009-04-02 03:30:55 +00001037 if (parentPS && isa<CompoundStmt>(parentPS) &&
1038 parentPS == PDB.getParent(NS))
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001039 return;
1040 }
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001041
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001042 // Add an extra edge when jumping between contexts.
1043 while (1) {
1044 if (const Stmt *PS = PrevLoc.asStmt())
1045 if (const Stmt *NS = NewLoc.asStmt()) {
1046 PathDiagnosticLocation X = PDB.getEnclosingStmtLocation(PS);
1047 // FIXME: We need a version of getParent that ignores '()' and casts.
1048 const Stmt *parentX = PDB.getParent(X.asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001049
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001050 const PathDiagnosticLocation &Y = PDB.getEnclosingStmtLocation(NS);
1051 // FIXME: We need a version of getParent that ignores '()' and casts.
1052 const Stmt *parentY = PDB.getParent(Y.asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +00001053
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001054 if (parentX && IsControlFlowExpr(parentX)) {
1055 if (parentX == parentY)
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001056 break;
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001057 else {
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001058 if (const Stmt *grandparentX = PDB.getParent(parentX)) {
1059 const PathDiagnosticLocation &W =
Ted Kremenek14856d72009-04-06 23:06:54 +00001060 PDB.getEnclosingStmtLocation(grandparentX);
Ted Kremenek0ddaff32009-04-02 03:44:00 +00001061
1062 if (W != Y) X = W;
1063 }
Ted Kremenek9e2d98d2009-04-01 21:12:06 +00001064 }
1065 }
1066
1067 if (X != Y && PrevLoc.asLocation() != X.asLocation()) {
1068 PD.push_front(new PathDiagnosticControlFlowPiece(X, PrevLoc));
1069 PrevLoc = X;
1070 }
1071 }
1072 break;
1073 }
1074
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001075 PD.push_front(new PathDiagnosticControlFlowPiece(NewLoc, PrevLoc));
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001076 PrevLoc = NewLoc;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001077}
1078
1079static bool IsNestedDeclStmt(const Stmt *S, ParentMap &PM) {
1080 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +00001081
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001082 if (!DS)
1083 return false;
1084
1085 const Stmt *Parent = PM.getParent(DS);
1086 if (!Parent)
1087 return false;
1088
1089 if (const ForStmt *FS = dyn_cast<ForStmt>(Parent))
1090 return FS->getInit() == DS;
Ted Kremenek14856d72009-04-06 23:06:54 +00001091
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001092 // FIXME: In the future IfStmt/WhileStmt may contain DeclStmts in their
1093 // condition.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001094
1095 return false;
1096}
1097
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001098static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1099 PathDiagnosticBuilder &PDB,
1100 const ExplodedNode<GRState> *N) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001101
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001102 SourceManager& SMgr = PDB.getSourceManager();
1103 const ExplodedNode<GRState>* NextNode = N->pred_empty()
Ted Kremenek14856d72009-04-06 23:06:54 +00001104 ? NULL : *(N->pred_begin());
1105
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001106 PathDiagnosticLocation PrevLoc;
1107
1108 while (NextNode) {
1109 N = NextNode;
1110 NextNode = GetPredecessorNode(N);
1111 ProgramPoint P = N->getLocation();
1112
1113 // Block edges.
1114 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1115 const CFGBlock &Blk = *BE->getSrc();
Ted Kremenek14856d72009-04-06 23:06:54 +00001116
Ted Kremenek51a735c2009-04-01 17:52:26 +00001117 // Add a special edge for the entrance into the function/method.
1118 if (&Blk == &PDB.getCFG().getEntry()) {
1119 FullSourceLoc L = FullSourceLoc(PDB.getCodeDecl().getLocation(), SMgr);
1120 GenExtAddEdge(PD, PDB, L.getSpellingLoc(), PrevLoc);
1121 continue;
1122 }
1123
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001124 if (const Stmt *Term = Blk.getTerminator()) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001125 const Stmt *Cond = Blk.getTerminatorCondition();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001126 if (!Cond || !IsControlFlowExpr(Cond)) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001127 // For terminators that are control-flow expressions like '&&', '?',
1128 // have the condition be the anchor point for the control-flow edge
1129 // instead of the terminator.
1130 const Stmt *X = isa<Expr>(Term) ? (Cond ? Cond : Term) : Term;
1131 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(X, SMgr), PrevLoc,true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001132 continue;
1133 }
1134 }
1135
1136 // Only handle blocks with more than 1 statement here, as the blocks
1137 // with one statement are handled at BlockEntrances.
1138 if (Blk.size() > 1) {
1139 const Stmt *S = *Blk.rbegin();
1140
1141 // We don't add control-flow edges for DeclStmt's that appear in
1142 // the condition of if/while/for or are control-flow merge expressions.
1143 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
1144 GenExtAddEdge(PD, PDB, PathDiagnosticLocation(S, SMgr), PrevLoc);
1145 }
1146 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001147
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001148 continue;
1149 }
1150
1151 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1152 if (const Stmt* S = BE->getFirstStmt()) {
1153 if (!IsControlFlowExpr(S) && !IsNestedDeclStmt(S, PDB.getParentMap())) {
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001154 if (PrevLoc.isValid()) {
Ted Kremenek51a735c2009-04-01 17:52:26 +00001155 // Are we jumping within the same enclosing statement?
Ted Kremenekc3f83ad2009-04-01 17:18:21 +00001156 if (PDB.getEnclosingStmtLocation(S) ==
1157 PDB.getEnclosingStmtLocation(PrevLoc))
Ted Kremenek14856d72009-04-06 23:06:54 +00001158 continue;
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001159 }
1160
1161 GenExtAddEdge(PD, PDB, PDB.getEnclosingStmtLocation(S), PrevLoc);
1162 }
1163 }
1164
1165 continue;
1166 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001167
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001168 PathDiagnosticPiece* p =
Ted Kremenek14856d72009-04-06 23:06:54 +00001169 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
1170 PDB.getBugReporter(), PDB.getNodeMapClosure());
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001171
1172 if (p) {
Ted Kremeneka42c4c92009-04-01 18:48:52 +00001173 GenExtAddEdge(PD, PDB, p->getLocation(), PrevLoc, true);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001174 PD.push_front(p);
1175 }
1176 }
1177}
Ted Kremenek14856d72009-04-06 23:06:54 +00001178#endif
1179
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001180//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001181// Methods for BugType and subclasses.
1182//===----------------------------------------------------------------------===//
1183BugType::~BugType() {}
1184void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001185
Ted Kremenekcf118d42009-02-04 23:49:09 +00001186//===----------------------------------------------------------------------===//
1187// Methods for BugReport and subclasses.
1188//===----------------------------------------------------------------------===//
1189BugReport::~BugReport() {}
1190RangedBugReport::~RangedBugReport() {}
1191
1192Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001193 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001194 Stmt *S = NULL;
1195
Ted Kremenekcf118d42009-02-04 23:49:09 +00001196 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001197 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001198 }
1199 if (!S) S = GetStmt(ProgP);
1200
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001201 return S;
1202}
1203
1204PathDiagnosticPiece*
1205BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001206 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001207
1208 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001209
1210 if (!S)
1211 return NULL;
1212
Ted Kremenekc9fa2f72008-05-01 23:13:35 +00001213 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001214 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001215
Ted Kremenekde7161f2008-04-03 18:00:37 +00001216 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001217 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001218
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001219 for (; Beg != End; ++Beg)
1220 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001221
1222 return P;
1223}
1224
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001225void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1226 const SourceRange*& end) {
1227
1228 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1229 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001230 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001231 beg = &R;
1232 end = beg+1;
1233 }
1234 else
1235 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001236}
1237
Ted Kremenekcf118d42009-02-04 23:49:09 +00001238SourceLocation BugReport::getLocation() const {
1239 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001240 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1241 // For member expressions, return the location of the '.' or '->'.
1242 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1243 return ME->getMemberLoc();
1244
Ted Kremenekcf118d42009-02-04 23:49:09 +00001245 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001246 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001247
1248 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001249}
1250
Ted Kremenek3148eb42009-01-24 00:55:43 +00001251PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1252 const ExplodedNode<GRState>* PrevN,
1253 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001254 BugReporter& BR,
1255 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001256 return NULL;
1257}
1258
Ted Kremenekcf118d42009-02-04 23:49:09 +00001259//===----------------------------------------------------------------------===//
1260// Methods for BugReporter and subclasses.
1261//===----------------------------------------------------------------------===//
1262
1263BugReportEquivClass::~BugReportEquivClass() {
1264 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
1265}
1266
1267GRBugReporter::~GRBugReporter() { FlushReports(); }
1268BugReporterData::~BugReporterData() {}
1269
1270ExplodedGraph<GRState>&
1271GRBugReporter::getGraph() { return Eng.getGraph(); }
1272
1273GRStateManager&
1274GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1275
1276BugReporter::~BugReporter() { FlushReports(); }
1277
1278void BugReporter::FlushReports() {
1279 if (BugTypes.isEmpty())
1280 return;
1281
1282 // First flush the warnings for each BugType. This may end up creating new
1283 // warnings and new BugTypes. Because ImmutableSet is a functional data
1284 // structure, we do not need to worry about the iterators being invalidated.
1285 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1286 const_cast<BugType*>(*I)->FlushReports(*this);
1287
1288 // Iterate through BugTypes a second time. BugTypes may have been updated
1289 // with new BugType objects and new warnings.
1290 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1291 BugType *BT = const_cast<BugType*>(*I);
1292
1293 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1294 SetTy& EQClasses = BT->EQClasses;
1295
1296 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1297 BugReportEquivClass& EQ = *EI;
1298 FlushReport(EQ);
1299 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001300
Ted Kremenekcf118d42009-02-04 23:49:09 +00001301 // Delete the BugType object. This will also delete the equivalence
1302 // classes.
1303 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001304 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001305
1306 // Remove all references to the BugType objects.
1307 BugTypes = F.GetEmptySet();
1308}
1309
1310//===----------------------------------------------------------------------===//
1311// PathDiagnostics generation.
1312//===----------------------------------------------------------------------===//
1313
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001314static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001315 std::pair<ExplodedNode<GRState>*, unsigned> >
1316MakeReportGraph(const ExplodedGraph<GRState>* G,
1317 const ExplodedNode<GRState>** NStart,
1318 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001319
Ted Kremenekcf118d42009-02-04 23:49:09 +00001320 // Create the trimmed graph. It will contain the shortest paths from the
1321 // error nodes to the root. In the new graph we should only have one
1322 // error node unless there are two or more error nodes with the same minimum
1323 // path length.
1324 ExplodedGraph<GRState>* GTrim;
1325 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001326
1327 llvm::DenseMap<const void*, const void*> InverseMap;
1328 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001329
1330 // Create owning pointers for GTrim and NMap just to ensure that they are
1331 // released when this function exists.
1332 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1333 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1334
1335 // Find the (first) error node in the trimmed graph. We just need to consult
1336 // the node map (NMap) which maps from nodes in the original graph to nodes
1337 // in the new graph.
1338 const ExplodedNode<GRState>* N = 0;
1339 unsigned NodeIndex = 0;
1340
1341 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1342 if ((N = NMap->getMappedNode(*I))) {
1343 NodeIndex = (I - NStart) / sizeof(*I);
1344 break;
1345 }
1346
1347 assert(N && "No error node found in the trimmed graph.");
1348
1349 // Create a new (third!) graph with a single path. This is the graph
1350 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001351 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001352 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1353 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001354
Ted Kremenek10aa5542009-03-12 23:41:59 +00001355 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001356 // to the root node, and then construct a new graph that contains only
1357 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001358 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001359 std::queue<const ExplodedNode<GRState>*> WS;
1360 WS.push(N);
1361
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001362 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001363 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001364
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001365 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001366 const ExplodedNode<GRState>* Node = WS.front();
1367 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001368
1369 if (Visited.find(Node) != Visited.end())
1370 continue;
1371
1372 Visited[Node] = cnt++;
1373
1374 if (Node->pred_empty()) {
1375 Root = Node;
1376 break;
1377 }
1378
Ted Kremenek3148eb42009-01-24 00:55:43 +00001379 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001380 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001381 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001382 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001383
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001384 assert (Root);
1385
Ted Kremenek10aa5542009-03-12 23:41:59 +00001386 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001387 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001388 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001389 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001390
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001391 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001392 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001393 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001394 assert (I != Visited.end());
1395
1396 // Create the equivalent node in the new graph with the same state
1397 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001398 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001399 GNew->getNode(N->getLocation(), N->getState());
1400
1401 // Store the mapping to the original node.
1402 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1403 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1404 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001405
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001406 // Link up the new node with the previous node.
1407 if (Last)
1408 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001409
1410 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001411
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001412 // Are we at the final node?
1413 if (I->second == 0) {
1414 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001415 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001416 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001417
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001418 // Find the next successor node. We choose the node that is marked
1419 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001420 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1421 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001422 N = 0;
1423
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001424 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001425
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001426 I = Visited.find(*SI);
1427
1428 if (I == Visited.end())
1429 continue;
1430
1431 if (!N || I->second < MinVal) {
1432 N = *SI;
1433 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001434 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001435 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001436
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001437 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001438 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001439
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001440 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001441 return std::make_pair(std::make_pair(GNew, BM),
1442 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001443}
1444
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001445/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1446/// and collapses PathDiagosticPieces that are expanded by macros.
1447static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1448 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1449 MacroStackTy;
1450
1451 typedef std::vector<PathDiagnosticPiece*>
1452 PiecesTy;
1453
1454 MacroStackTy MacroStack;
1455 PiecesTy Pieces;
1456
1457 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1458 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001459 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001460
1461 // Determine the instantiation location, which is the location we group
1462 // related PathDiagnosticPieces.
1463 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1464 SM.getInstantiationLoc(Loc) :
1465 SourceLocation();
1466
1467 if (Loc.isFileID()) {
1468 MacroStack.clear();
1469 Pieces.push_back(&*I);
1470 continue;
1471 }
1472
1473 assert(Loc.isMacroID());
1474
1475 // Is the PathDiagnosticPiece within the same macro group?
1476 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1477 MacroStack.back().first->push_back(&*I);
1478 continue;
1479 }
1480
1481 // We aren't in the same group. Are we descending into a new macro
1482 // or are part of an old one?
1483 PathDiagnosticMacroPiece *MacroGroup = 0;
1484
1485 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1486 SM.getInstantiationLoc(Loc) :
1487 SourceLocation();
1488
1489 // Walk the entire macro stack.
1490 while (!MacroStack.empty()) {
1491 if (InstantiationLoc == MacroStack.back().second) {
1492 MacroGroup = MacroStack.back().first;
1493 break;
1494 }
1495
1496 if (ParentInstantiationLoc == MacroStack.back().second) {
1497 MacroGroup = MacroStack.back().first;
1498 break;
1499 }
1500
1501 MacroStack.pop_back();
1502 }
1503
1504 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1505 // Create a new macro group and add it to the stack.
1506 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1507
1508 if (MacroGroup)
1509 MacroGroup->push_back(NewGroup);
1510 else {
1511 assert(InstantiationLoc.isFileID());
1512 Pieces.push_back(NewGroup);
1513 }
1514
1515 MacroGroup = NewGroup;
1516 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1517 }
1518
1519 // Finally, add the PathDiagnosticPiece to the group.
1520 MacroGroup->push_back(&*I);
1521 }
1522
1523 // Now take the pieces and construct a new PathDiagnostic.
1524 PD.resetPath(false);
1525
1526 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1527 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1528 if (!MP->containsEvent()) {
1529 delete MP;
1530 continue;
1531 }
1532
1533 PD.push_back(*I);
1534 }
1535}
1536
Ted Kremenek7dc86642009-03-31 20:22:36 +00001537void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1538 BugReportEquivClass& EQ) {
1539
1540 std::vector<const ExplodedNode<GRState>*> Nodes;
1541
Ted Kremenekcf118d42009-02-04 23:49:09 +00001542 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1543 const ExplodedNode<GRState>* N = I->getEndNode();
1544 if (N) Nodes.push_back(N);
1545 }
1546
1547 if (Nodes.empty())
1548 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001549
1550 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001551 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001552 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001553 std::pair<ExplodedNode<GRState>*, unsigned> >&
1554 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001555
Ted Kremenekcf118d42009-02-04 23:49:09 +00001556 // Find the BugReport with the original location.
1557 BugReport *R = 0;
1558 unsigned i = 0;
1559 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1560 if (i == GPair.second.second) { R = *I; break; }
1561
1562 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001563
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001564 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1565 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001566 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001567
Ted Kremenekcf118d42009-02-04 23:49:09 +00001568 // Start building the path diagnostic...
1569 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001570 PD.push_back(Piece);
1571 else
1572 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001573
1574 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1575 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001576 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001577
Ted Kremenek7dc86642009-03-31 20:22:36 +00001578 switch (PDB.getGenerationScheme()) {
1579 case PathDiagnosticClient::Extensive:
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001580 GenerateExtensivePathDiagnostic(PD,PDB, N);
1581 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001582 case PathDiagnosticClient::Minimal:
1583 GenerateMinimalPathDiagnostic(PD, PDB, N);
1584 break;
1585 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001586}
1587
Ted Kremenekcf118d42009-02-04 23:49:09 +00001588void BugReporter::Register(BugType *BT) {
1589 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001590}
1591
Ted Kremenekcf118d42009-02-04 23:49:09 +00001592void BugReporter::EmitReport(BugReport* R) {
1593 // Compute the bug report's hash to determine its equivalence class.
1594 llvm::FoldingSetNodeID ID;
1595 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001596
Ted Kremenekcf118d42009-02-04 23:49:09 +00001597 // Lookup the equivance class. If there isn't one, create it.
1598 BugType& BT = R->getBugType();
1599 Register(&BT);
1600 void *InsertPos;
1601 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1602
1603 if (!EQ) {
1604 EQ = new BugReportEquivClass(R);
1605 BT.EQClasses.InsertNode(EQ, InsertPos);
1606 }
1607 else
1608 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001609}
1610
Ted Kremenekcf118d42009-02-04 23:49:09 +00001611void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1612 assert(!EQ.Reports.empty());
1613 BugReport &R = **EQ.begin();
1614
1615 // FIXME: Make sure we use the 'R' for the path that was actually used.
1616 // Probably doesn't make a difference in practice.
1617 BugType& BT = R.getBugType();
1618
1619 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1620 R.getDescription(),
1621 BT.getCategory()));
1622 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001623
1624 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001625 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001626 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001627
Ted Kremenek3148eb42009-01-24 00:55:43 +00001628 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001629 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001630 const SourceRange *Beg = 0, *End = 0;
1631 R.getRanges(*this, Beg, End);
1632 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001633 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001634 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1635 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001636
Ted Kremenek3148eb42009-01-24 00:55:43 +00001637 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001638 default: assert(0 && "Don't handle this many ranges yet!");
1639 case 0: Diag.Report(L, ErrorDiag); break;
1640 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1641 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1642 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001643 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001644
1645 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1646 if (!PD)
1647 return;
1648
1649 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001650 PathDiagnosticPiece* piece =
1651 new PathDiagnosticEventPiece(L, R.getDescription());
1652
Ted Kremenek3148eb42009-01-24 00:55:43 +00001653 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1654 D->push_back(piece);
1655 }
1656
1657 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001658}
Ted Kremenek57202072008-07-14 17:40:50 +00001659
Ted Kremenek8c036c72008-09-20 04:23:38 +00001660void BugReporter::EmitBasicReport(const char* name, const char* str,
1661 SourceLocation Loc,
1662 SourceRange* RBeg, unsigned NumRanges) {
1663 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1664}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001665
Ted Kremenek8c036c72008-09-20 04:23:38 +00001666void BugReporter::EmitBasicReport(const char* name, const char* category,
1667 const char* str, SourceLocation Loc,
1668 SourceRange* RBeg, unsigned NumRanges) {
1669
Ted Kremenekcf118d42009-02-04 23:49:09 +00001670 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1671 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001672 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001673 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1674 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1675 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001676}