blob: 5407cea4e2ca71e9ea7a8e1a66689aa4ee43d4e0 [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/AST/ASTContext.h"
18#include "clang/AST/CFG.h"
19#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 Kremenekb697b102009-02-23 22:44:26 +000043static inline Stmt* GetStmt(ProgramPoint P) {
44 if (const PostStmt* PS = dyn_cast<PostStmt>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000045 return PS->getStmt();
Ted Kremenekb697b102009-02-23 22:44:26 +000046 else if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P))
Ted Kremenek61f3e052008-04-03 04:42:52 +000047 return BE->getSrc()->getTerminator();
Ted Kremenek61f3e052008-04-03 04:42:52 +000048
Ted Kremenekb697b102009-02-23 22:44:26 +000049 return 0;
Ted Kremenek706e3cf2008-04-07 23:35:17 +000050}
51
Ted Kremenek3148eb42009-01-24 00:55:43 +000052static inline const ExplodedNode<GRState>*
Ted Kremenekb697b102009-02-23 22:44:26 +000053GetPredecessorNode(const ExplodedNode<GRState>* 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
Ted Kremenekb697b102009-02-23 22:44:26 +000057static inline const ExplodedNode<GRState>*
58GetSuccessorNode(const ExplodedNode<GRState>* N) {
59 return N->succ_empty() ? NULL : *(N->succ_begin());
Ted Kremenekbd7efa82008-04-17 23:44:37 +000060}
61
Ted Kremenekb697b102009-02-23 22:44:26 +000062static Stmt* GetPreviousStmt(const ExplodedNode<GRState>* N) {
63 for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
64 if (Stmt *S = GetStmt(N->getLocation()))
65 return S;
66
67 return 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +000068}
69
Ted Kremenekb697b102009-02-23 22:44:26 +000070static Stmt* GetNextStmt(const ExplodedNode<GRState>* N) {
71 for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000072 if (Stmt *S = GetStmt(N->getLocation())) {
73 // 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 Kremenekb697b102009-02-23 22:44:26 +000087 return S;
Ted Kremenekf5ab8e62009-03-28 17:33:57 +000088 }
Ted Kremenekb697b102009-02-23 22:44:26 +000089
90 return 0;
91}
92
93static inline Stmt* GetCurrentOrPreviousStmt(const ExplodedNode<GRState>* N) {
94 if (Stmt *S = GetStmt(N->getLocation()))
95 return S;
96
97 return GetPreviousStmt(N);
98}
99
100static inline Stmt* GetCurrentOrNextStmt(const ExplodedNode<GRState>* N) {
101 if (Stmt *S = GetStmt(N->getLocation()))
102 return S;
103
104 return GetNextStmt(N);
105}
106
107//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000108// PathDiagnosticBuilder and its associated routines and helper objects.
Ted Kremenekb697b102009-02-23 22:44:26 +0000109//===----------------------------------------------------------------------===//
Ted Kremenekb479dad2009-02-23 23:13:51 +0000110
Ted Kremenek7dc86642009-03-31 20:22:36 +0000111typedef llvm::DenseMap<const ExplodedNode<GRState>*,
112const ExplodedNode<GRState>*> NodeBackMap;
113
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000114namespace {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000115class VISIBILITY_HIDDEN NodeMapClosure : public BugReport::NodeResolver {
116 NodeBackMap& M;
117public:
118 NodeMapClosure(NodeBackMap *m) : M(*m) {}
119 ~NodeMapClosure() {}
120
121 const ExplodedNode<GRState>* getOriginalNode(const ExplodedNode<GRState>* N) {
122 NodeBackMap::iterator I = M.find(N);
123 return I == M.end() ? 0 : I->second;
124 }
125};
126
Ted Kremenek8966bc12009-05-06 21:39:49 +0000127class VISIBILITY_HIDDEN PathDiagnosticBuilder : public BugReporterContext {
Ted Kremenek7dc86642009-03-31 20:22:36 +0000128 BugReport *R;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000129 PathDiagnosticClient *PDC;
Ted Kremenek00605e02009-03-27 20:55:39 +0000130 llvm::OwningPtr<ParentMap> PM;
Ted Kremenek7dc86642009-03-31 20:22:36 +0000131 NodeMapClosure NMC;
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000132public:
Ted Kremenek8966bc12009-05-06 21:39:49 +0000133 PathDiagnosticBuilder(GRBugReporter &br,
Ted Kremenek7dc86642009-03-31 20:22:36 +0000134 BugReport *r, NodeBackMap *Backmap,
Ted Kremenek8966bc12009-05-06 21:39:49 +0000135 PathDiagnosticClient *pdc)
136 : BugReporterContext(br),
137 R(r), PDC(pdc), NMC(Backmap)
138 {
139 addVisitor(R);
140 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000141
Ted Kremenek00605e02009-03-27 20:55:39 +0000142 PathDiagnosticLocation ExecutionContinues(const ExplodedNode<GRState>* N);
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000143
Ted Kremenek00605e02009-03-27 20:55:39 +0000144 PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream& os,
145 const ExplodedNode<GRState>* N);
146
147 ParentMap& getParentMap() {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000148 if (PM.get() == 0)
149 PM.reset(new ParentMap(getCodeDecl().getBody(getASTContext())));
Ted Kremenek00605e02009-03-27 20:55:39 +0000150 return *PM.get();
151 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000152
Ted Kremenekc3f83ad2009-04-01 17:18:21 +0000153 const Stmt *getParent(const Stmt *S) {
154 return getParentMap().getParent(S);
155 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000156
157 virtual NodeMapClosure& getNodeResolver() { return NMC; }
Ted Kremenek7dc86642009-03-31 20:22:36 +0000158 BugReport& getReport() { return *R; }
Douglas Gregor72971342009-04-18 00:02:19 +0000159
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000160 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
161
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000162 PathDiagnosticLocation
163 getEnclosingStmtLocation(const PathDiagnosticLocation &L) {
164 if (const Stmt *S = L.asStmt())
165 return getEnclosingStmtLocation(S);
166
167 return L;
168 }
169
Ted Kremenek7dc86642009-03-31 20:22:36 +0000170 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
171 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
172 }
173
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000174 bool supportsLogicalOpControlFlow() const {
175 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
176 }
177};
178} // end anonymous namespace
179
Ted Kremenek00605e02009-03-27 20:55:39 +0000180PathDiagnosticLocation
181PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
182 if (Stmt *S = GetNextStmt(N))
Ted Kremenek8966bc12009-05-06 21:39:49 +0000183 return PathDiagnosticLocation(S, getSourceManager());
Ted Kremenek00605e02009-03-27 20:55:39 +0000184
Ted Kremenek8966bc12009-05-06 21:39:49 +0000185 return FullSourceLoc(getCodeDecl().getBodyRBrace(getASTContext()),
186 getSourceManager());
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000187}
188
Ted Kremenek00605e02009-03-27 20:55:39 +0000189PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000190PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
191 const ExplodedNode<GRState>* N) {
192
Ted Kremenek143ca222008-05-06 18:11:09 +0000193 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000194 if (os.str().empty())
195 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000196
Ted Kremenek00605e02009-03-27 20:55:39 +0000197 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000198
Ted Kremenek00605e02009-03-27 20:55:39 +0000199 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000200 os << "Execution continues on line "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000201 << getSourceManager().getInstantiationLineNumber(Loc.asLocation())
202 << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000203 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000204 os << "Execution jumps to the end of the "
Ted Kremenek8966bc12009-05-06 21:39:49 +0000205 << (isa<ObjCMethodDecl>(getCodeDecl()) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000206
207 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000208}
209
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000210PathDiagnosticLocation
211PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
212 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000213 ParentMap &P = getParentMap();
Ted Kremenek8966bc12009-05-06 21:39:49 +0000214 SourceManager &SMgr = getSourceManager();
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000215
Ted Kremenekc42e07e2009-05-05 22:19:17 +0000216 while (isa<Expr>(S) && P.isConsumedExpr(cast<Expr>(S))) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000217 const Stmt *Parent = P.getParentIgnoreParens(S);
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000218
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000219 if (!Parent)
220 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000221
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000222 switch (Parent->getStmtClass()) {
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000223 case Stmt::BinaryOperatorClass: {
224 const BinaryOperator *B = cast<BinaryOperator>(Parent);
225 if (B->isLogicalOp())
226 return PathDiagnosticLocation(S, SMgr);
227 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000228 }
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000229 case Stmt::CompoundStmtClass:
230 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000231 return PathDiagnosticLocation(S, SMgr);
232 case Stmt::ChooseExprClass:
233 // Similar to '?' if we are referring to condition, just have the edge
234 // point to the entire choose expression.
235 if (cast<ChooseExpr>(Parent)->getCond() == S)
236 return PathDiagnosticLocation(Parent, SMgr);
237 else
238 return PathDiagnosticLocation(S, SMgr);
239 case Stmt::ConditionalOperatorClass:
240 // For '?', if we are referring to condition, just have the edge point
241 // to the entire '?' expression.
242 if (cast<ConditionalOperator>(Parent)->getCond() == S)
243 return PathDiagnosticLocation(Parent, SMgr);
244 else
245 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000246 case Stmt::DoStmtClass:
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000247 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000248 case Stmt::ForStmtClass:
249 if (cast<ForStmt>(Parent)->getBody() == S)
250 return PathDiagnosticLocation(S, SMgr);
251 break;
252 case Stmt::IfStmtClass:
253 if (cast<IfStmt>(Parent)->getCond() != S)
254 return PathDiagnosticLocation(S, SMgr);
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000255 break;
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000256 case Stmt::ObjCForCollectionStmtClass:
257 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
258 return PathDiagnosticLocation(S, SMgr);
259 break;
260 case Stmt::WhileStmtClass:
261 if (cast<WhileStmt>(Parent)->getCond() != S)
262 return PathDiagnosticLocation(S, SMgr);
263 break;
264 default:
265 break;
266 }
267
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000268 S = Parent;
269 }
270
271 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
272 return PathDiagnosticLocation(S, SMgr);
273}
274
Ted Kremenekcf118d42009-02-04 23:49:09 +0000275//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000276// ScanNotableSymbols: closure-like callback for scanning Store bindings.
277//===----------------------------------------------------------------------===//
278
279static const VarDecl*
280GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
281 GRStateManager& VMgr, SVal X) {
282
283 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
284
285 ProgramPoint P = N->getLocation();
286
287 if (!isa<PostStmt>(P))
288 continue;
289
290 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
291
292 if (!DR)
293 continue;
294
295 SVal Y = VMgr.GetSVal(N->getState(), DR);
296
297 if (X != Y)
298 continue;
299
300 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
301
302 if (!VD)
303 continue;
304
305 return VD;
306 }
307
308 return 0;
309}
310
311namespace {
312class VISIBILITY_HIDDEN NotableSymbolHandler
313: public StoreManager::BindingsHandler {
314
315 SymbolRef Sym;
316 const GRState* PrevSt;
317 const Stmt* S;
318 GRStateManager& VMgr;
319 const ExplodedNode<GRState>* Pred;
320 PathDiagnostic& PD;
321 BugReporter& BR;
322
323public:
324
325 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
326 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
327 PathDiagnostic& pd, BugReporter& br)
328 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
329
330 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
331 SVal V) {
332
333 SymbolRef ScanSym = V.getAsSymbol();
334
335 if (ScanSym != Sym)
336 return true;
337
338 // Check if the previous state has this binding.
339 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
340
341 if (X == V) // Same binding?
342 return true;
343
344 // Different binding. Only handle assignments for now. We don't pull
345 // this check out of the loop because we will eventually handle other
346 // cases.
347
348 VarDecl *VD = 0;
349
350 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
351 if (!B->isAssignmentOp())
352 return true;
353
354 // What variable did we assign to?
355 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
356
357 if (!DR)
358 return true;
359
360 VD = dyn_cast<VarDecl>(DR->getDecl());
361 }
362 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
363 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
364 // assume that each DeclStmt has a single Decl. This invariant
365 // holds by contruction in the CFG.
366 VD = dyn_cast<VarDecl>(*DS->decl_begin());
367 }
368
369 if (!VD)
370 return true;
371
372 // What is the most recently referenced variable with this binding?
373 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
374
375 if (!MostRecent)
376 return true;
377
378 // Create the diagnostic.
379 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
380
381 if (Loc::IsLocType(VD->getType())) {
382 std::string msg = "'" + std::string(VD->getNameAsString()) +
383 "' now aliases '" + MostRecent->getNameAsString() + "'";
384
385 PD.push_front(new PathDiagnosticEventPiece(L, msg));
386 }
387
388 return true;
389 }
390};
391}
392
393static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
394 const Stmt* S,
395 SymbolRef Sym, BugReporter& BR,
396 PathDiagnostic& PD) {
397
398 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
399 const GRState* PrevSt = Pred ? Pred->getState() : 0;
400
401 if (!PrevSt)
402 return;
403
404 // Look at the region bindings of the current state that map to the
405 // specified symbol. Are any of them not in the previous state?
406 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
407 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
408 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
409}
410
411namespace {
412class VISIBILITY_HIDDEN ScanNotableSymbols
413: public StoreManager::BindingsHandler {
414
415 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
416 const ExplodedNode<GRState>* N;
417 Stmt* S;
418 GRBugReporter& BR;
419 PathDiagnostic& PD;
420
421public:
422 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
423 PathDiagnostic& pd)
424 : N(n), S(s), BR(br), PD(pd) {}
425
426 bool HandleBinding(StoreManager& SMgr, Store store,
427 const MemRegion* R, SVal V) {
428
429 SymbolRef ScanSym = V.getAsSymbol();
430
431 if (!ScanSym)
432 return true;
433
434 if (!BR.isNotable(ScanSym))
435 return true;
436
437 if (AlreadyProcessed.count(ScanSym))
438 return true;
439
440 AlreadyProcessed.insert(ScanSym);
441
442 HandleNotableSymbol(N, S, ScanSym, BR, PD);
443 return true;
444 }
445};
446} // end anonymous namespace
447
448//===----------------------------------------------------------------------===//
449// "Minimal" path diagnostic generation algorithm.
450//===----------------------------------------------------------------------===//
451
Ted Kremenek14856d72009-04-06 23:06:54 +0000452static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
453
Ted Kremenek31061982009-03-31 23:00:32 +0000454static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
455 PathDiagnosticBuilder &PDB,
456 const ExplodedNode<GRState> *N) {
Ted Kremenek8966bc12009-05-06 21:39:49 +0000457
Ted Kremenek31061982009-03-31 23:00:32 +0000458 SourceManager& SMgr = PDB.getSourceManager();
459 const ExplodedNode<GRState>* NextNode = N->pred_empty()
460 ? NULL : *(N->pred_begin());
461 while (NextNode) {
462 N = NextNode;
463 NextNode = GetPredecessorNode(N);
464
465 ProgramPoint P = N->getLocation();
466
467 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
468 CFGBlock* Src = BE->getSrc();
469 CFGBlock* Dst = BE->getDst();
470 Stmt* T = Src->getTerminator();
471
472 if (!T)
473 continue;
474
475 FullSourceLoc Start(T->getLocStart(), SMgr);
476
477 switch (T->getStmtClass()) {
478 default:
479 break;
480
481 case Stmt::GotoStmtClass:
482 case Stmt::IndirectGotoStmtClass: {
483 Stmt* S = GetNextStmt(N);
484
485 if (!S)
486 continue;
487
488 std::string sbuf;
489 llvm::raw_string_ostream os(sbuf);
490 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
491
492 os << "Control jumps to line "
493 << End.asLocation().getInstantiationLineNumber();
494 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
495 os.str()));
496 break;
497 }
498
499 case Stmt::SwitchStmtClass: {
500 // Figure out what case arm we took.
501 std::string sbuf;
502 llvm::raw_string_ostream os(sbuf);
503
504 if (Stmt* S = Dst->getLabel()) {
505 PathDiagnosticLocation End(S, SMgr);
506
507 switch (S->getStmtClass()) {
508 default:
509 os << "No cases match in the switch statement. "
510 "Control jumps to line "
511 << End.asLocation().getInstantiationLineNumber();
512 break;
513 case Stmt::DefaultStmtClass:
514 os << "Control jumps to the 'default' case at line "
515 << End.asLocation().getInstantiationLineNumber();
516 break;
517
518 case Stmt::CaseStmtClass: {
519 os << "Control jumps to 'case ";
520 CaseStmt* Case = cast<CaseStmt>(S);
521 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
522
523 // Determine if it is an enum.
524 bool GetRawInt = true;
525
526 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
527 // FIXME: Maybe this should be an assertion. Are there cases
528 // were it is not an EnumConstantDecl?
529 EnumConstantDecl* D =
530 dyn_cast<EnumConstantDecl>(DR->getDecl());
531
532 if (D) {
533 GetRawInt = false;
534 os << D->getNameAsString();
535 }
536 }
Eli Friedman9ec64d62009-04-26 19:04:51 +0000537
538 if (GetRawInt)
Ted Kremenek8966bc12009-05-06 21:39:49 +0000539 os << LHS->EvaluateAsInt(PDB.getASTContext());
Eli Friedman9ec64d62009-04-26 19:04:51 +0000540
Ted Kremenek31061982009-03-31 23:00:32 +0000541 os << ":' at line "
542 << End.asLocation().getInstantiationLineNumber();
543 break;
544 }
545 }
546 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
547 os.str()));
548 }
549 else {
550 os << "'Default' branch taken. ";
551 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
552 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
553 os.str()));
554 }
555
556 break;
557 }
558
559 case Stmt::BreakStmtClass:
560 case Stmt::ContinueStmtClass: {
561 std::string sbuf;
562 llvm::raw_string_ostream os(sbuf);
563 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
564 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
565 os.str()));
566 break;
567 }
568
569 // Determine control-flow for ternary '?'.
570 case Stmt::ConditionalOperatorClass: {
571 std::string sbuf;
572 llvm::raw_string_ostream os(sbuf);
573 os << "'?' condition is ";
574
575 if (*(Src->succ_begin()+1) == Dst)
576 os << "false";
577 else
578 os << "true";
579
580 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
581
582 if (const Stmt *S = End.asStmt())
583 End = PDB.getEnclosingStmtLocation(S);
584
585 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
586 os.str()));
587 break;
588 }
589
590 // Determine control-flow for short-circuited '&&' and '||'.
591 case Stmt::BinaryOperatorClass: {
592 if (!PDB.supportsLogicalOpControlFlow())
593 break;
594
595 BinaryOperator *B = cast<BinaryOperator>(T);
596 std::string sbuf;
597 llvm::raw_string_ostream os(sbuf);
598 os << "Left side of '";
599
600 if (B->getOpcode() == BinaryOperator::LAnd) {
601 os << "&&" << "' is ";
602
603 if (*(Src->succ_begin()+1) == Dst) {
604 os << "false";
605 PathDiagnosticLocation End(B->getLHS(), SMgr);
606 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
607 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
608 os.str()));
609 }
610 else {
611 os << "true";
612 PathDiagnosticLocation Start(B->getLHS(), SMgr);
613 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
614 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
615 os.str()));
616 }
617 }
618 else {
619 assert(B->getOpcode() == BinaryOperator::LOr);
620 os << "||" << "' is ";
621
622 if (*(Src->succ_begin()+1) == Dst) {
623 os << "false";
624 PathDiagnosticLocation Start(B->getLHS(), SMgr);
625 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
626 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
627 os.str()));
628 }
629 else {
630 os << "true";
631 PathDiagnosticLocation End(B->getLHS(), SMgr);
632 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
633 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
634 os.str()));
635 }
636 }
637
638 break;
639 }
640
641 case Stmt::DoStmtClass: {
642 if (*(Src->succ_begin()) == Dst) {
643 std::string sbuf;
644 llvm::raw_string_ostream os(sbuf);
645
646 os << "Loop condition is true. ";
647 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
648
649 if (const Stmt *S = End.asStmt())
650 End = PDB.getEnclosingStmtLocation(S);
651
652 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
653 os.str()));
654 }
655 else {
656 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
657
658 if (const Stmt *S = End.asStmt())
659 End = PDB.getEnclosingStmtLocation(S);
660
661 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
662 "Loop condition is false. Exiting loop"));
663 }
664
665 break;
666 }
667
668 case Stmt::WhileStmtClass:
669 case Stmt::ForStmtClass: {
670 if (*(Src->succ_begin()+1) == Dst) {
671 std::string sbuf;
672 llvm::raw_string_ostream os(sbuf);
673
674 os << "Loop condition is false. ";
675 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
676 if (const Stmt *S = End.asStmt())
677 End = PDB.getEnclosingStmtLocation(S);
678
679 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
680 os.str()));
681 }
682 else {
683 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
684 if (const Stmt *S = End.asStmt())
685 End = PDB.getEnclosingStmtLocation(S);
686
687 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000688 "Loop condition is true. Entering loop body"));
Ted Kremenek31061982009-03-31 23:00:32 +0000689 }
690
691 break;
692 }
693
694 case Stmt::IfStmtClass: {
695 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
696
697 if (const Stmt *S = End.asStmt())
698 End = PDB.getEnclosingStmtLocation(S);
699
700 if (*(Src->succ_begin()+1) == Dst)
701 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000702 "Taking false branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000703 else
704 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000705 "Taking true branch"));
Ted Kremenek31061982009-03-31 23:00:32 +0000706
707 break;
708 }
709 }
710 }
711
Ted Kremenekdd986cc2009-05-07 00:45:33 +0000712 if (NextNode) {
713 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
714 E = PDB.visitor_end(); I!=E; ++I) {
715 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB))
716 PD.push_front(p);
717 }
Ted Kremenek8966bc12009-05-06 21:39:49 +0000718 }
Ted Kremenek31061982009-03-31 23:00:32 +0000719
720 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
721 // Scan the region bindings, and see if a "notable" symbol has a new
722 // lval binding.
723 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
724 PDB.getStateManager().iterBindings(N->getState(), SNS);
725 }
726 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000727
728 // After constructing the full PathDiagnostic, do a pass over it to compact
729 // PathDiagnosticPieces that occur within a macro.
730 CompactPathDiagnostic(PD, PDB.getSourceManager());
Ted Kremenek31061982009-03-31 23:00:32 +0000731}
732
733//===----------------------------------------------------------------------===//
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000734// "Extensive" PathDiagnostic generation.
735//===----------------------------------------------------------------------===//
736
737static bool IsControlFlowExpr(const Stmt *S) {
738 const Expr *E = dyn_cast<Expr>(S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000739
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +0000740 if (!E)
741 return false;
742
743 E = E->IgnoreParenCasts();
744
745 if (isa<ConditionalOperator>(E))
746 return true;
747
748 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
749 if (B->isLogicalOp())
750 return true;
751
752 return false;
753}
754
Ted Kremenek14856d72009-04-06 23:06:54 +0000755namespace {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000756class VISIBILITY_HIDDEN ContextLocation : public PathDiagnosticLocation {
757 bool IsDead;
758public:
759 ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
760 : PathDiagnosticLocation(L), IsDead(isdead) {}
761
762 void markDead() { IsDead = true; }
763 bool isDead() const { return IsDead; }
764};
765
Ted Kremenek14856d72009-04-06 23:06:54 +0000766class VISIBILITY_HIDDEN EdgeBuilder {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000767 std::vector<ContextLocation> CLocs;
768 typedef std::vector<ContextLocation>::iterator iterator;
Ted Kremenek14856d72009-04-06 23:06:54 +0000769 PathDiagnostic &PD;
770 PathDiagnosticBuilder &PDB;
771 PathDiagnosticLocation PrevLoc;
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000772
773 bool IsConsumedExpr(const PathDiagnosticLocation &L);
774
Ted Kremenek14856d72009-04-06 23:06:54 +0000775 bool containsLocation(const PathDiagnosticLocation &Container,
776 const PathDiagnosticLocation &Containee);
777
778 PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
Ted Kremenek14856d72009-04-06 23:06:54 +0000779
Ted Kremenek9650cf32009-05-11 21:42:34 +0000780 PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
781 bool firstCharOnly = false) {
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000782 if (const Stmt *S = L.asStmt()) {
Ted Kremenek9650cf32009-05-11 21:42:34 +0000783 const Stmt *Original = S;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000784 while (1) {
785 // Adjust the location for some expressions that are best referenced
786 // by one of their subexpressions.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000787 switch (S->getStmtClass()) {
788 default:
789 break;
790 case Stmt::ParenExprClass:
791 S = cast<ParenExpr>(S)->IgnoreParens();
792 firstCharOnly = true;
793 continue;
794 case Stmt::ConditionalOperatorClass:
795 S = cast<ConditionalOperator>(S)->getCond();
796 firstCharOnly = true;
797 continue;
798 case Stmt::ChooseExprClass:
799 S = cast<ChooseExpr>(S)->getCond();
800 firstCharOnly = true;
801 continue;
802 case Stmt::BinaryOperatorClass:
803 S = cast<BinaryOperator>(S)->getLHS();
804 firstCharOnly = true;
805 continue;
806 }
807
808 break;
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000809 }
810
Ted Kremenek9650cf32009-05-11 21:42:34 +0000811 if (S != Original)
812 L = PathDiagnosticLocation(S, L.getManager());
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000813 }
814
Ted Kremenek9650cf32009-05-11 21:42:34 +0000815 if (firstCharOnly)
816 L = PathDiagnosticLocation(L.asLocation());
817
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000818 return L;
819 }
820
Ted Kremenek14856d72009-04-06 23:06:54 +0000821 void popLocation() {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000822 if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000823 // For contexts, we only one the first character as the range.
Ted Kremenek9650cf32009-05-11 21:42:34 +0000824 rawAddEdge( cleanUpLocation(CLocs.back(), true));
Ted Kremenek5c7168c2009-04-22 20:36:26 +0000825 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000826 CLocs.pop_back();
827 }
828
829 PathDiagnosticLocation IgnoreParens(const PathDiagnosticLocation &L);
830
831public:
832 EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
833 : PD(pd), PDB(pdb) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000834
835 // If the PathDiagnostic already has pieces, add the enclosing statement
836 // of the first piece as a context as well.
Ted Kremenek14856d72009-04-06 23:06:54 +0000837 if (!PD.empty()) {
838 PrevLoc = PD.begin()->getLocation();
839
840 if (const Stmt *S = PrevLoc.asStmt())
Ted Kremeneke1baed32009-05-05 23:13:38 +0000841 addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
Ted Kremenek14856d72009-04-06 23:06:54 +0000842 }
843 }
844
845 ~EdgeBuilder() {
846 while (!CLocs.empty()) popLocation();
Ted Kremeneka301a672009-04-22 18:16:20 +0000847
848 // Finally, add an initial edge from the start location of the first
849 // statement (if it doesn't already exist).
Sebastian Redld3a413d2009-04-26 20:35:05 +0000850 // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
851 if (const CompoundStmt *CS =
Ted Kremenek8966bc12009-05-06 21:39:49 +0000852 PDB.getCodeDecl().getCompoundBody(PDB.getASTContext()))
Ted Kremeneka301a672009-04-22 18:16:20 +0000853 if (!CS->body_empty()) {
854 SourceLocation Loc = (*CS->body_begin())->getLocStart();
855 rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
856 }
857
Ted Kremenek14856d72009-04-06 23:06:54 +0000858 }
859
860 void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
861
862 void addEdge(const Stmt *S, bool alwaysAdd = false) {
863 addEdge(PathDiagnosticLocation(S, PDB.getSourceManager()), alwaysAdd);
864 }
865
Ted Kremenek8bd4d032009-04-28 04:23:15 +0000866 void rawAddEdge(PathDiagnosticLocation NewLoc);
867
Ted Kremenek14856d72009-04-06 23:06:54 +0000868 void addContext(const Stmt *S);
Ted Kremeneke1baed32009-05-05 23:13:38 +0000869 void addExtendedContext(const Stmt *S);
Ted Kremenek14856d72009-04-06 23:06:54 +0000870};
871} // end anonymous namespace
872
873
874PathDiagnosticLocation
875EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
876 if (const Stmt *S = L.asStmt()) {
877 if (IsControlFlowExpr(S))
878 return L;
879
880 return PDB.getEnclosingStmtLocation(S);
881 }
882
883 return L;
884}
885
886bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
887 const PathDiagnosticLocation &Containee) {
888
889 if (Container == Containee)
890 return true;
891
892 if (Container.asDecl())
893 return true;
894
895 if (const Stmt *S = Containee.asStmt())
896 if (const Stmt *ContainerS = Container.asStmt()) {
897 while (S) {
898 if (S == ContainerS)
899 return true;
900 S = PDB.getParent(S);
901 }
902 return false;
903 }
904
905 // Less accurate: compare using source ranges.
906 SourceRange ContainerR = Container.asRange();
907 SourceRange ContaineeR = Containee.asRange();
908
909 SourceManager &SM = PDB.getSourceManager();
910 SourceLocation ContainerRBeg = SM.getInstantiationLoc(ContainerR.getBegin());
911 SourceLocation ContainerREnd = SM.getInstantiationLoc(ContainerR.getEnd());
912 SourceLocation ContaineeRBeg = SM.getInstantiationLoc(ContaineeR.getBegin());
913 SourceLocation ContaineeREnd = SM.getInstantiationLoc(ContaineeR.getEnd());
914
915 unsigned ContainerBegLine = SM.getInstantiationLineNumber(ContainerRBeg);
916 unsigned ContainerEndLine = SM.getInstantiationLineNumber(ContainerREnd);
917 unsigned ContaineeBegLine = SM.getInstantiationLineNumber(ContaineeRBeg);
918 unsigned ContaineeEndLine = SM.getInstantiationLineNumber(ContaineeREnd);
919
920 assert(ContainerBegLine <= ContainerEndLine);
921 assert(ContaineeBegLine <= ContaineeEndLine);
922
923 return (ContainerBegLine <= ContaineeBegLine &&
924 ContainerEndLine >= ContaineeEndLine &&
925 (ContainerBegLine != ContaineeBegLine ||
926 SM.getInstantiationColumnNumber(ContainerRBeg) <=
927 SM.getInstantiationColumnNumber(ContaineeRBeg)) &&
928 (ContainerEndLine != ContaineeEndLine ||
929 SM.getInstantiationColumnNumber(ContainerREnd) >=
930 SM.getInstantiationColumnNumber(ContainerREnd)));
931}
932
933PathDiagnosticLocation
934EdgeBuilder::IgnoreParens(const PathDiagnosticLocation &L) {
935 if (const Expr* E = dyn_cast_or_null<Expr>(L.asStmt()))
936 return PathDiagnosticLocation(E->IgnoreParenCasts(),
937 PDB.getSourceManager());
938 return L;
939}
940
941void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
942 if (!PrevLoc.isValid()) {
943 PrevLoc = NewLoc;
944 return;
945 }
946
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000947 const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
948 const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
949
950 if (NewLocClean.asLocation() == PrevLocClean.asLocation())
Ted Kremenek14856d72009-04-06 23:06:54 +0000951 return;
952
953 // FIXME: Ignore intra-macro edges for now.
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000954 if (NewLocClean.asLocation().getInstantiationLoc() ==
955 PrevLocClean.asLocation().getInstantiationLoc())
Ted Kremenek14856d72009-04-06 23:06:54 +0000956 return;
957
Ted Kremenek8c8b0ad2009-05-11 19:50:47 +0000958 PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
959 PrevLoc = NewLoc;
Ted Kremenek14856d72009-04-06 23:06:54 +0000960}
961
962void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
Ted Kremeneka301a672009-04-22 18:16:20 +0000963
964 if (!alwaysAdd && NewLoc.asLocation().isMacroID())
965 return;
966
Ted Kremenek14856d72009-04-06 23:06:54 +0000967 const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
968
969 while (!CLocs.empty()) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000970 ContextLocation &TopContextLoc = CLocs.back();
Ted Kremenek14856d72009-04-06 23:06:54 +0000971
972 // Is the top location context the same as the one for the new location?
973 if (TopContextLoc == CLoc) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000974 if (alwaysAdd) {
Ted Kremenek4c6f8d32009-05-04 18:15:17 +0000975 if (IsConsumedExpr(TopContextLoc) &&
976 !IsControlFlowExpr(TopContextLoc.asStmt()))
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000977 TopContextLoc.markDead();
978
Ted Kremenek14856d72009-04-06 23:06:54 +0000979 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000980 }
Ted Kremenek14856d72009-04-06 23:06:54 +0000981
982 return;
983 }
984
985 if (containsLocation(TopContextLoc, CLoc)) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000986 if (alwaysAdd) {
Ted Kremenek14856d72009-04-06 23:06:54 +0000987 rawAddEdge(NewLoc);
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000988
Ted Kremenek4c6f8d32009-05-04 18:15:17 +0000989 if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
Ted Kremenek8f9b1b32009-05-01 16:08:09 +0000990 CLocs.push_back(ContextLocation(CLoc, true));
991 return;
992 }
993 }
994
Ted Kremenek14856d72009-04-06 23:06:54 +0000995 CLocs.push_back(CLoc);
996 return;
997 }
998
999 // Context does not contain the location. Flush it.
1000 popLocation();
1001 }
Ted Kremenek5c7168c2009-04-22 20:36:26 +00001002
1003 // If we reach here, there is no enclosing context. Just add the edge.
1004 rawAddEdge(NewLoc);
Ted Kremenek14856d72009-04-06 23:06:54 +00001005}
1006
Ted Kremenek8f9b1b32009-05-01 16:08:09 +00001007bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
1008 if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
1009 return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
1010
1011 return false;
1012}
1013
Ted Kremeneke1baed32009-05-05 23:13:38 +00001014void EdgeBuilder::addExtendedContext(const Stmt *S) {
1015 if (!S)
1016 return;
1017
1018 const Stmt *Parent = PDB.getParent(S);
1019 while (Parent) {
1020 if (isa<CompoundStmt>(Parent))
1021 Parent = PDB.getParent(Parent);
1022 else
1023 break;
1024 }
1025
1026 if (Parent) {
1027 switch (Parent->getStmtClass()) {
1028 case Stmt::DoStmtClass:
1029 case Stmt::ObjCAtSynchronizedStmtClass:
1030 addContext(Parent);
1031 default:
1032 break;
1033 }
1034 }
1035
1036 addContext(S);
1037}
1038
Ted Kremenek14856d72009-04-06 23:06:54 +00001039void EdgeBuilder::addContext(const Stmt *S) {
1040 if (!S)
1041 return;
1042
1043 PathDiagnosticLocation L(S, PDB.getSourceManager());
1044
1045 while (!CLocs.empty()) {
1046 const PathDiagnosticLocation &TopContextLoc = CLocs.back();
1047
1048 // Is the top location context the same as the one for the new location?
1049 if (TopContextLoc == L)
1050 return;
1051
1052 if (containsLocation(TopContextLoc, L)) {
Ted Kremenek14856d72009-04-06 23:06:54 +00001053 CLocs.push_back(L);
1054 return;
1055 }
1056
1057 // Context does not contain the location. Flush it.
1058 popLocation();
1059 }
1060
1061 CLocs.push_back(L);
1062}
1063
1064static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
1065 PathDiagnosticBuilder &PDB,
1066 const ExplodedNode<GRState> *N) {
1067
1068
1069 EdgeBuilder EB(PD, PDB);
1070
1071 const ExplodedNode<GRState>* NextNode = N->pred_empty()
1072 ? NULL : *(N->pred_begin());
Ted Kremenek14856d72009-04-06 23:06:54 +00001073 while (NextNode) {
1074 N = NextNode;
1075 NextNode = GetPredecessorNode(N);
1076 ProgramPoint P = N->getLocation();
1077
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001078 do {
1079 // Block edges.
1080 if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
1081 const CFGBlock &Blk = *BE->getSrc();
1082 const Stmt *Term = Blk.getTerminator();
1083
1084 if (Term)
1085 EB.addContext(Term);
Ted Kremenek14856d72009-04-06 23:06:54 +00001086
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001087 // Are we jumping to the head of a loop? Add a special diagnostic.
1088 if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
1089
1090 PathDiagnosticLocation L(Loop, PDB.getSourceManager());
1091 PathDiagnosticEventPiece *p =
1092 new PathDiagnosticEventPiece(L,
1093 "Looping back to the head of the loop");
1094
1095 EB.addEdge(p->getLocation(), true);
1096 PD.push_front(p);
1097
1098 if (!Term) {
1099 const CompoundStmt *CS = NULL;
1100 if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
1101 CS = dyn_cast<CompoundStmt>(FS->getBody());
1102 else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
1103 CS = dyn_cast<CompoundStmt>(WS->getBody());
1104
1105 if (CS)
1106 EB.rawAddEdge(PathDiagnosticLocation(CS->getRBracLoc(),
1107 PDB.getSourceManager()));
1108 }
Ted Kremenek8bd4d032009-04-28 04:23:15 +00001109 }
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001110
1111 break;
Ted Kremenek14856d72009-04-06 23:06:54 +00001112 }
1113
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001114 if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
1115 if (const Stmt* S = BE->getFirstStmt()) {
1116 if (IsControlFlowExpr(S)) {
1117 // Add the proper context for '&&', '||', and '?'.
1118 EB.addContext(S);
1119 }
1120 else
1121 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1122 }
1123
1124 break;
1125 }
1126 } while (0);
1127
1128 if (!NextNode)
Ted Kremenek14856d72009-04-06 23:06:54 +00001129 continue;
Ted Kremenek14856d72009-04-06 23:06:54 +00001130
Ted Kremenek8966bc12009-05-06 21:39:49 +00001131 for (BugReporterContext::visitor_iterator I = PDB.visitor_begin(),
1132 E = PDB.visitor_end(); I!=E; ++I) {
1133 if (PathDiagnosticPiece* p = (*I)->VisitNode(N, NextNode, PDB)) {
1134 const PathDiagnosticLocation &Loc = p->getLocation();
1135 EB.addEdge(Loc, true);
1136 PD.push_front(p);
1137 if (const Stmt *S = Loc.asStmt())
1138 EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
1139 }
1140 }
Ted Kremenek14856d72009-04-06 23:06:54 +00001141 }
1142}
1143
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001144//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +00001145// Methods for BugType and subclasses.
1146//===----------------------------------------------------------------------===//
1147BugType::~BugType() {}
1148void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001149
Ted Kremenekcf118d42009-02-04 23:49:09 +00001150//===----------------------------------------------------------------------===//
1151// Methods for BugReport and subclasses.
1152//===----------------------------------------------------------------------===//
1153BugReport::~BugReport() {}
1154RangedBugReport::~RangedBugReport() {}
1155
1156Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +00001157 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001158 Stmt *S = NULL;
1159
Ted Kremenekcf118d42009-02-04 23:49:09 +00001160 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +00001161 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001162 }
1163 if (!S) S = GetStmt(ProgP);
1164
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001165 return S;
1166}
1167
1168PathDiagnosticPiece*
Ted Kremenek8966bc12009-05-06 21:39:49 +00001169BugReport::getEndPath(BugReporterContext& BRC,
Ted Kremenek3148eb42009-01-24 00:55:43 +00001170 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001171
Ted Kremenek8966bc12009-05-06 21:39:49 +00001172 Stmt* S = getStmt(BRC.getBugReporter());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001173
1174 if (!S)
1175 return NULL;
1176
Ted Kremenek8966bc12009-05-06 21:39:49 +00001177 FullSourceLoc L(S->getLocStart(), BRC.getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001178 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001179
Ted Kremenekde7161f2008-04-03 18:00:37 +00001180 const SourceRange *Beg, *End;
Ted Kremenek8966bc12009-05-06 21:39:49 +00001181 getRanges(BRC.getBugReporter(), Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001182
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001183 for (; Beg != End; ++Beg)
1184 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001185
1186 return P;
1187}
1188
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001189void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
1190 const SourceRange*& end) {
1191
1192 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
1193 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001194 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +00001195 beg = &R;
1196 end = beg+1;
1197 }
1198 else
1199 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +00001200}
1201
Ted Kremenekcf118d42009-02-04 23:49:09 +00001202SourceLocation BugReport::getLocation() const {
1203 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001204 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
1205 // For member expressions, return the location of the '.' or '->'.
1206 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
1207 return ME->getMemberLoc();
1208
Ted Kremenekcf118d42009-02-04 23:49:09 +00001209 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +00001210 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001211
1212 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +00001213}
1214
Ted Kremenek3148eb42009-01-24 00:55:43 +00001215PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
1216 const ExplodedNode<GRState>* PrevN,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001217 BugReporterContext &BRC) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +00001218 return NULL;
1219}
1220
Ted Kremenekcf118d42009-02-04 23:49:09 +00001221//===----------------------------------------------------------------------===//
1222// Methods for BugReporter and subclasses.
1223//===----------------------------------------------------------------------===//
1224
1225BugReportEquivClass::~BugReportEquivClass() {
Ted Kremenek8966bc12009-05-06 21:39:49 +00001226 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001227}
1228
1229GRBugReporter::~GRBugReporter() { FlushReports(); }
1230BugReporterData::~BugReporterData() {}
1231
1232ExplodedGraph<GRState>&
1233GRBugReporter::getGraph() { return Eng.getGraph(); }
1234
1235GRStateManager&
1236GRBugReporter::getStateManager() { return Eng.getStateManager(); }
1237
1238BugReporter::~BugReporter() { FlushReports(); }
1239
1240void BugReporter::FlushReports() {
1241 if (BugTypes.isEmpty())
1242 return;
1243
1244 // First flush the warnings for each BugType. This may end up creating new
1245 // warnings and new BugTypes. Because ImmutableSet is a functional data
1246 // structure, we do not need to worry about the iterators being invalidated.
1247 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
1248 const_cast<BugType*>(*I)->FlushReports(*this);
1249
1250 // Iterate through BugTypes a second time. BugTypes may have been updated
1251 // with new BugType objects and new warnings.
1252 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
1253 BugType *BT = const_cast<BugType*>(*I);
1254
1255 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
1256 SetTy& EQClasses = BT->EQClasses;
1257
1258 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
1259 BugReportEquivClass& EQ = *EI;
1260 FlushReport(EQ);
1261 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001262
Ted Kremenekcf118d42009-02-04 23:49:09 +00001263 // Delete the BugType object. This will also delete the equivalence
1264 // classes.
1265 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +00001266 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001267
1268 // Remove all references to the BugType objects.
1269 BugTypes = F.GetEmptySet();
1270}
1271
1272//===----------------------------------------------------------------------===//
1273// PathDiagnostics generation.
1274//===----------------------------------------------------------------------===//
1275
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001276static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +00001277 std::pair<ExplodedNode<GRState>*, unsigned> >
1278MakeReportGraph(const ExplodedGraph<GRState>* G,
1279 const ExplodedNode<GRState>** NStart,
1280 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +00001281
Ted Kremenekcf118d42009-02-04 23:49:09 +00001282 // Create the trimmed graph. It will contain the shortest paths from the
1283 // error nodes to the root. In the new graph we should only have one
1284 // error node unless there are two or more error nodes with the same minimum
1285 // path length.
1286 ExplodedGraph<GRState>* GTrim;
1287 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001288
1289 llvm::DenseMap<const void*, const void*> InverseMap;
1290 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001291
1292 // Create owning pointers for GTrim and NMap just to ensure that they are
1293 // released when this function exists.
1294 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
1295 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
1296
1297 // Find the (first) error node in the trimmed graph. We just need to consult
1298 // the node map (NMap) which maps from nodes in the original graph to nodes
1299 // in the new graph.
1300 const ExplodedNode<GRState>* N = 0;
1301 unsigned NodeIndex = 0;
1302
1303 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
1304 if ((N = NMap->getMappedNode(*I))) {
1305 NodeIndex = (I - NStart) / sizeof(*I);
1306 break;
1307 }
1308
1309 assert(N && "No error node found in the trimmed graph.");
1310
1311 // Create a new (third!) graph with a single path. This is the graph
1312 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001313 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001314 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
1315 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +00001316
Ted Kremenek10aa5542009-03-12 23:41:59 +00001317 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001318 // to the root node, and then construct a new graph that contains only
1319 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001320 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +00001321 std::queue<const ExplodedNode<GRState>*> WS;
1322 WS.push(N);
1323
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001324 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +00001325 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001326
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001327 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +00001328 const ExplodedNode<GRState>* Node = WS.front();
1329 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001330
1331 if (Visited.find(Node) != Visited.end())
1332 continue;
1333
1334 Visited[Node] = cnt++;
1335
1336 if (Node->pred_empty()) {
1337 Root = Node;
1338 break;
1339 }
1340
Ted Kremenek3148eb42009-01-24 00:55:43 +00001341 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001342 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +00001343 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001344 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001345
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001346 assert (Root);
1347
Ted Kremenek10aa5542009-03-12 23:41:59 +00001348 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001349 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001350 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001351 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001352
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001353 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001354 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001355 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001356 assert (I != Visited.end());
1357
1358 // Create the equivalent node in the new graph with the same state
1359 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +00001360 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001361 GNew->getNode(N->getLocation(), N->getState());
1362
1363 // Store the mapping to the original node.
1364 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
1365 assert(IMitr != InverseMap.end() && "No mapping to original node.");
1366 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001367
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001368 // Link up the new node with the previous node.
1369 if (Last)
1370 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001371
1372 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +00001373
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001374 // Are we at the final node?
1375 if (I->second == 0) {
1376 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001377 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001378 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001379
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001380 // Find the next successor node. We choose the node that is marked
1381 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001382 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
1383 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +00001384 N = 0;
1385
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001386 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +00001387
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001388 I = Visited.find(*SI);
1389
1390 if (I == Visited.end())
1391 continue;
1392
1393 if (!N || I->second < MinVal) {
1394 N = *SI;
1395 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +00001396 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001397 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001398
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001399 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001400 }
Ted Kremenekcf118d42009-02-04 23:49:09 +00001401
Ted Kremenek331b0ac2008-06-18 05:34:07 +00001402 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001403 return std::make_pair(std::make_pair(GNew, BM),
1404 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001405}
1406
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001407/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
1408/// and collapses PathDiagosticPieces that are expanded by macros.
1409static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
1410 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
1411 MacroStackTy;
1412
1413 typedef std::vector<PathDiagnosticPiece*>
1414 PiecesTy;
1415
1416 MacroStackTy MacroStack;
1417 PiecesTy Pieces;
1418
1419 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
1420 // Get the location of the PathDiagnosticPiece.
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001421 const FullSourceLoc Loc = I->getLocation().asLocation();
Ted Kremenek0e5c8d42009-03-10 05:16:17 +00001422
1423 // Determine the instantiation location, which is the location we group
1424 // related PathDiagnosticPieces.
1425 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1426 SM.getInstantiationLoc(Loc) :
1427 SourceLocation();
1428
1429 if (Loc.isFileID()) {
1430 MacroStack.clear();
1431 Pieces.push_back(&*I);
1432 continue;
1433 }
1434
1435 assert(Loc.isMacroID());
1436
1437 // Is the PathDiagnosticPiece within the same macro group?
1438 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1439 MacroStack.back().first->push_back(&*I);
1440 continue;
1441 }
1442
1443 // We aren't in the same group. Are we descending into a new macro
1444 // or are part of an old one?
1445 PathDiagnosticMacroPiece *MacroGroup = 0;
1446
1447 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1448 SM.getInstantiationLoc(Loc) :
1449 SourceLocation();
1450
1451 // Walk the entire macro stack.
1452 while (!MacroStack.empty()) {
1453 if (InstantiationLoc == MacroStack.back().second) {
1454 MacroGroup = MacroStack.back().first;
1455 break;
1456 }
1457
1458 if (ParentInstantiationLoc == MacroStack.back().second) {
1459 MacroGroup = MacroStack.back().first;
1460 break;
1461 }
1462
1463 MacroStack.pop_back();
1464 }
1465
1466 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1467 // Create a new macro group and add it to the stack.
1468 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1469
1470 if (MacroGroup)
1471 MacroGroup->push_back(NewGroup);
1472 else {
1473 assert(InstantiationLoc.isFileID());
1474 Pieces.push_back(NewGroup);
1475 }
1476
1477 MacroGroup = NewGroup;
1478 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1479 }
1480
1481 // Finally, add the PathDiagnosticPiece to the group.
1482 MacroGroup->push_back(&*I);
1483 }
1484
1485 // Now take the pieces and construct a new PathDiagnostic.
1486 PD.resetPath(false);
1487
1488 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1489 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1490 if (!MP->containsEvent()) {
1491 delete MP;
1492 continue;
1493 }
1494
1495 PD.push_back(*I);
1496 }
1497}
1498
Ted Kremenek7dc86642009-03-31 20:22:36 +00001499void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
Ted Kremenek8966bc12009-05-06 21:39:49 +00001500 BugReportEquivClass& EQ) {
Ted Kremenek7dc86642009-03-31 20:22:36 +00001501
1502 std::vector<const ExplodedNode<GRState>*> Nodes;
1503
Ted Kremenekcf118d42009-02-04 23:49:09 +00001504 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1505 const ExplodedNode<GRState>* N = I->getEndNode();
1506 if (N) Nodes.push_back(N);
1507 }
1508
1509 if (Nodes.empty())
1510 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001511
1512 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001513 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001514 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001515 std::pair<ExplodedNode<GRState>*, unsigned> >&
1516 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001517
Ted Kremenekcf118d42009-02-04 23:49:09 +00001518 // Find the BugReport with the original location.
1519 BugReport *R = 0;
1520 unsigned i = 0;
1521 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1522 if (i == GPair.second.second) { R = *I; break; }
1523
1524 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001525
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001526 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1527 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001528 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001529
Ted Kremenek8966bc12009-05-06 21:39:49 +00001530 // Start building the path diagnostic...
1531 PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
1532
1533 if (PathDiagnosticPiece* Piece = R->getEndPath(PDB, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001534 PD.push_back(Piece);
1535 else
1536 return;
Ted Kremenekdd986cc2009-05-07 00:45:33 +00001537
1538 R->registerInitialVisitors(PDB, N);
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001539
Ted Kremenek7dc86642009-03-31 20:22:36 +00001540 switch (PDB.getGenerationScheme()) {
1541 case PathDiagnosticClient::Extensive:
Ted Kremenek8966bc12009-05-06 21:39:49 +00001542 GenerateExtensivePathDiagnostic(PD, PDB, N);
Ted Kremenek5fb5dfb2009-04-01 06:13:56 +00001543 break;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001544 case PathDiagnosticClient::Minimal:
1545 GenerateMinimalPathDiagnostic(PD, PDB, N);
1546 break;
1547 }
Ted Kremenek7dc86642009-03-31 20:22:36 +00001548}
1549
Ted Kremenekcf118d42009-02-04 23:49:09 +00001550void BugReporter::Register(BugType *BT) {
1551 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001552}
1553
Ted Kremenekcf118d42009-02-04 23:49:09 +00001554void BugReporter::EmitReport(BugReport* R) {
1555 // Compute the bug report's hash to determine its equivalence class.
1556 llvm::FoldingSetNodeID ID;
1557 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001558
Ted Kremenekcf118d42009-02-04 23:49:09 +00001559 // Lookup the equivance class. If there isn't one, create it.
1560 BugType& BT = R->getBugType();
1561 Register(&BT);
1562 void *InsertPos;
1563 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1564
1565 if (!EQ) {
1566 EQ = new BugReportEquivClass(R);
1567 BT.EQClasses.InsertNode(EQ, InsertPos);
1568 }
1569 else
1570 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001571}
1572
Ted Kremenekcf118d42009-02-04 23:49:09 +00001573void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1574 assert(!EQ.Reports.empty());
1575 BugReport &R = **EQ.begin();
Ted Kremenekd49967f2009-04-29 21:58:13 +00001576 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001577
1578 // FIXME: Make sure we use the 'R' for the path that was actually used.
1579 // Probably doesn't make a difference in practice.
1580 BugType& BT = R.getBugType();
1581
Ted Kremenekd49967f2009-04-29 21:58:13 +00001582 llvm::OwningPtr<PathDiagnostic>
1583 D(new PathDiagnostic(R.getBugType().getName(),
Ted Kremenekda0e8422009-04-29 22:05:03 +00001584 !PD || PD->useVerboseDescription()
Ted Kremenekd49967f2009-04-29 21:58:13 +00001585 ? R.getDescription() : R.getShortDescription(),
1586 BT.getCategory()));
1587
Ted Kremenekcf118d42009-02-04 23:49:09 +00001588 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001589
1590 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001591 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001592 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001593
Ted Kremenek3148eb42009-01-24 00:55:43 +00001594 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenek3148eb42009-01-24 00:55:43 +00001595 const SourceRange *Beg = 0, *End = 0;
1596 R.getRanges(*this, Beg, End);
1597 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001598 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001599 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
Ted Kremenekeaedfea2009-05-10 05:11:21 +00001600 R.getShortDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001601
Ted Kremenek3148eb42009-01-24 00:55:43 +00001602 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001603 default: assert(0 && "Don't handle this many ranges yet!");
1604 case 0: Diag.Report(L, ErrorDiag); break;
1605 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1606 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1607 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001608 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001609
1610 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1611 if (!PD)
1612 return;
1613
1614 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001615 PathDiagnosticPiece* piece =
1616 new PathDiagnosticEventPiece(L, R.getDescription());
1617
Ted Kremenek3148eb42009-01-24 00:55:43 +00001618 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1619 D->push_back(piece);
1620 }
1621
1622 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001623}
Ted Kremenek57202072008-07-14 17:40:50 +00001624
Ted Kremenek8c036c72008-09-20 04:23:38 +00001625void BugReporter::EmitBasicReport(const char* name, const char* str,
1626 SourceLocation Loc,
1627 SourceRange* RBeg, unsigned NumRanges) {
1628 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1629}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001630
Ted Kremenek8c036c72008-09-20 04:23:38 +00001631void BugReporter::EmitBasicReport(const char* name, const char* category,
1632 const char* str, SourceLocation Loc,
1633 SourceRange* RBeg, unsigned NumRanges) {
1634
Ted Kremenekcf118d42009-02-04 23:49:09 +00001635 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1636 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001637 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001638 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1639 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1640 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001641}