blob: 1d1c2fa7d00a49850cb9d2a193410ddee59d990f [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() {
143 if (PM.get() == 0) PM.reset(new ParentMap(CodeDecl.getBody()));
144 return *PM.get();
145 }
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000146
Ted Kremenek7dc86642009-03-31 20:22:36 +0000147 ExplodedGraph<GRState>& getGraph() { return *ReportGraph; }
148 NodeMapClosure& getNodeMapClosure() { return NMC; }
149 ASTContext& getContext() { return BR.getContext(); }
150 SourceManager& getSourceManager() { return SMgr; }
151 BugReport& getReport() { return *R; }
152 GRBugReporter& getBugReporter() { return BR; }
153 GRStateManager& getStateManager() { return BR.getStateManager(); }
154
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000155 PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
156
Ted Kremenek7dc86642009-03-31 20:22:36 +0000157 PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
158 return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
159 }
160
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000161 bool supportsLogicalOpControlFlow() const {
162 return PDC ? PDC->supportsLogicalOpControlFlow() : true;
163 }
164};
165} // end anonymous namespace
166
Ted Kremenek00605e02009-03-27 20:55:39 +0000167PathDiagnosticLocation
168PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode<GRState>* N) {
169 if (Stmt *S = GetNextStmt(N))
170 return PathDiagnosticLocation(S, SMgr);
171
172 return FullSourceLoc(CodeDecl.getBody()->getRBracLoc(), SMgr);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000173}
174
Ted Kremenek00605e02009-03-27 20:55:39 +0000175PathDiagnosticLocation
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000176PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream& os,
177 const ExplodedNode<GRState>* N) {
178
Ted Kremenek143ca222008-05-06 18:11:09 +0000179 // Slow, but probably doesn't matter.
Ted Kremenekb697b102009-02-23 22:44:26 +0000180 if (os.str().empty())
181 os << ' ';
Ted Kremenek143ca222008-05-06 18:11:09 +0000182
Ted Kremenek00605e02009-03-27 20:55:39 +0000183 const PathDiagnosticLocation &Loc = ExecutionContinues(N);
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000184
Ted Kremenek00605e02009-03-27 20:55:39 +0000185 if (Loc.asStmt())
Ted Kremenekb697b102009-02-23 22:44:26 +0000186 os << "Execution continues on line "
Ted Kremenek00605e02009-03-27 20:55:39 +0000187 << SMgr.getInstantiationLineNumber(Loc.asLocation()) << '.';
Ted Kremenekb697b102009-02-23 22:44:26 +0000188 else
Ted Kremenekb479dad2009-02-23 23:13:51 +0000189 os << "Execution jumps to the end of the "
Ted Kremenekbabdd7b2009-03-27 05:06:10 +0000190 << (isa<ObjCMethodDecl>(CodeDecl) ? "method" : "function") << '.';
Ted Kremenek082cb8d2009-03-12 18:41:53 +0000191
192 return Loc;
Ted Kremenek143ca222008-05-06 18:11:09 +0000193}
194
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000195PathDiagnosticLocation
196PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
197 assert(S && "Null Stmt* passed to getEnclosingStmtLocation");
198 ParentMap &P = getParentMap();
199 while (isa<Expr>(S)) {
200 const Stmt *Parent = P.getParent(S);
201
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000202 if (!Parent)
203 break;
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000204
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000205 switch (Parent->getStmtClass()) {
206 case Stmt::CompoundStmtClass:
207 case Stmt::StmtExprClass:
Ted Kremenek1d9a23a2009-03-28 04:08:14 +0000208 return PathDiagnosticLocation(S, SMgr);
209 case Stmt::ChooseExprClass:
210 // Similar to '?' if we are referring to condition, just have the edge
211 // point to the entire choose expression.
212 if (cast<ChooseExpr>(Parent)->getCond() == S)
213 return PathDiagnosticLocation(Parent, SMgr);
214 else
215 return PathDiagnosticLocation(S, SMgr);
216 case Stmt::ConditionalOperatorClass:
217 // For '?', if we are referring to condition, just have the edge point
218 // to the entire '?' expression.
219 if (cast<ConditionalOperator>(Parent)->getCond() == S)
220 return PathDiagnosticLocation(Parent, SMgr);
221 else
222 return PathDiagnosticLocation(S, SMgr);
Ted Kremenekaf3e3d52009-03-28 03:37:59 +0000223 case Stmt::DoStmtClass:
224 if (cast<DoStmt>(Parent)->getCond() != S)
225 return PathDiagnosticLocation(S, SMgr);
226 break;
227 case Stmt::ForStmtClass:
228 if (cast<ForStmt>(Parent)->getBody() == S)
229 return PathDiagnosticLocation(S, SMgr);
230 break;
231 case Stmt::IfStmtClass:
232 if (cast<IfStmt>(Parent)->getCond() != S)
233 return PathDiagnosticLocation(S, SMgr);
234 break;
235 case Stmt::ObjCForCollectionStmtClass:
236 if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
237 return PathDiagnosticLocation(S, SMgr);
238 break;
239 case Stmt::WhileStmtClass:
240 if (cast<WhileStmt>(Parent)->getCond() != S)
241 return PathDiagnosticLocation(S, SMgr);
242 break;
243 default:
244 break;
245 }
246
Ted Kremenekd8c938b2009-03-27 21:16:25 +0000247 S = Parent;
248 }
249
250 assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
251 return PathDiagnosticLocation(S, SMgr);
252}
253
Ted Kremenekcf118d42009-02-04 23:49:09 +0000254//===----------------------------------------------------------------------===//
Ted Kremenek31061982009-03-31 23:00:32 +0000255// ScanNotableSymbols: closure-like callback for scanning Store bindings.
256//===----------------------------------------------------------------------===//
257
258static const VarDecl*
259GetMostRecentVarDeclBinding(const ExplodedNode<GRState>* N,
260 GRStateManager& VMgr, SVal X) {
261
262 for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
263
264 ProgramPoint P = N->getLocation();
265
266 if (!isa<PostStmt>(P))
267 continue;
268
269 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
270
271 if (!DR)
272 continue;
273
274 SVal Y = VMgr.GetSVal(N->getState(), DR);
275
276 if (X != Y)
277 continue;
278
279 VarDecl* VD = dyn_cast<VarDecl>(DR->getDecl());
280
281 if (!VD)
282 continue;
283
284 return VD;
285 }
286
287 return 0;
288}
289
290namespace {
291class VISIBILITY_HIDDEN NotableSymbolHandler
292: public StoreManager::BindingsHandler {
293
294 SymbolRef Sym;
295 const GRState* PrevSt;
296 const Stmt* S;
297 GRStateManager& VMgr;
298 const ExplodedNode<GRState>* Pred;
299 PathDiagnostic& PD;
300 BugReporter& BR;
301
302public:
303
304 NotableSymbolHandler(SymbolRef sym, const GRState* prevst, const Stmt* s,
305 GRStateManager& vmgr, const ExplodedNode<GRState>* pred,
306 PathDiagnostic& pd, BugReporter& br)
307 : Sym(sym), PrevSt(prevst), S(s), VMgr(vmgr), Pred(pred), PD(pd), BR(br) {}
308
309 bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
310 SVal V) {
311
312 SymbolRef ScanSym = V.getAsSymbol();
313
314 if (ScanSym != Sym)
315 return true;
316
317 // Check if the previous state has this binding.
318 SVal X = VMgr.GetSVal(PrevSt, loc::MemRegionVal(R));
319
320 if (X == V) // Same binding?
321 return true;
322
323 // Different binding. Only handle assignments for now. We don't pull
324 // this check out of the loop because we will eventually handle other
325 // cases.
326
327 VarDecl *VD = 0;
328
329 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
330 if (!B->isAssignmentOp())
331 return true;
332
333 // What variable did we assign to?
334 DeclRefExpr* DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
335
336 if (!DR)
337 return true;
338
339 VD = dyn_cast<VarDecl>(DR->getDecl());
340 }
341 else if (const DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
342 // FIXME: Eventually CFGs won't have DeclStmts. Right now we
343 // assume that each DeclStmt has a single Decl. This invariant
344 // holds by contruction in the CFG.
345 VD = dyn_cast<VarDecl>(*DS->decl_begin());
346 }
347
348 if (!VD)
349 return true;
350
351 // What is the most recently referenced variable with this binding?
352 const VarDecl* MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
353
354 if (!MostRecent)
355 return true;
356
357 // Create the diagnostic.
358 FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
359
360 if (Loc::IsLocType(VD->getType())) {
361 std::string msg = "'" + std::string(VD->getNameAsString()) +
362 "' now aliases '" + MostRecent->getNameAsString() + "'";
363
364 PD.push_front(new PathDiagnosticEventPiece(L, msg));
365 }
366
367 return true;
368 }
369};
370}
371
372static void HandleNotableSymbol(const ExplodedNode<GRState>* N,
373 const Stmt* S,
374 SymbolRef Sym, BugReporter& BR,
375 PathDiagnostic& PD) {
376
377 const ExplodedNode<GRState>* Pred = N->pred_empty() ? 0 : *N->pred_begin();
378 const GRState* PrevSt = Pred ? Pred->getState() : 0;
379
380 if (!PrevSt)
381 return;
382
383 // Look at the region bindings of the current state that map to the
384 // specified symbol. Are any of them not in the previous state?
385 GRStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
386 NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
387 cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
388}
389
390namespace {
391class VISIBILITY_HIDDEN ScanNotableSymbols
392: public StoreManager::BindingsHandler {
393
394 llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
395 const ExplodedNode<GRState>* N;
396 Stmt* S;
397 GRBugReporter& BR;
398 PathDiagnostic& PD;
399
400public:
401 ScanNotableSymbols(const ExplodedNode<GRState>* n, Stmt* s, GRBugReporter& br,
402 PathDiagnostic& pd)
403 : N(n), S(s), BR(br), PD(pd) {}
404
405 bool HandleBinding(StoreManager& SMgr, Store store,
406 const MemRegion* R, SVal V) {
407
408 SymbolRef ScanSym = V.getAsSymbol();
409
410 if (!ScanSym)
411 return true;
412
413 if (!BR.isNotable(ScanSym))
414 return true;
415
416 if (AlreadyProcessed.count(ScanSym))
417 return true;
418
419 AlreadyProcessed.insert(ScanSym);
420
421 HandleNotableSymbol(N, S, ScanSym, BR, PD);
422 return true;
423 }
424};
425} // end anonymous namespace
426
427//===----------------------------------------------------------------------===//
428// "Minimal" path diagnostic generation algorithm.
429//===----------------------------------------------------------------------===//
430
431static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
432 PathDiagnosticBuilder &PDB,
433 const ExplodedNode<GRState> *N) {
434 ASTContext& Ctx = PDB.getContext();
435 SourceManager& SMgr = PDB.getSourceManager();
436 const ExplodedNode<GRState>* NextNode = N->pred_empty()
437 ? NULL : *(N->pred_begin());
438 while (NextNode) {
439 N = NextNode;
440 NextNode = GetPredecessorNode(N);
441
442 ProgramPoint P = N->getLocation();
443
444 if (const BlockEdge* BE = dyn_cast<BlockEdge>(&P)) {
445 CFGBlock* Src = BE->getSrc();
446 CFGBlock* Dst = BE->getDst();
447 Stmt* T = Src->getTerminator();
448
449 if (!T)
450 continue;
451
452 FullSourceLoc Start(T->getLocStart(), SMgr);
453
454 switch (T->getStmtClass()) {
455 default:
456 break;
457
458 case Stmt::GotoStmtClass:
459 case Stmt::IndirectGotoStmtClass: {
460 Stmt* S = GetNextStmt(N);
461
462 if (!S)
463 continue;
464
465 std::string sbuf;
466 llvm::raw_string_ostream os(sbuf);
467 const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
468
469 os << "Control jumps to line "
470 << End.asLocation().getInstantiationLineNumber();
471 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
472 os.str()));
473 break;
474 }
475
476 case Stmt::SwitchStmtClass: {
477 // Figure out what case arm we took.
478 std::string sbuf;
479 llvm::raw_string_ostream os(sbuf);
480
481 if (Stmt* S = Dst->getLabel()) {
482 PathDiagnosticLocation End(S, SMgr);
483
484 switch (S->getStmtClass()) {
485 default:
486 os << "No cases match in the switch statement. "
487 "Control jumps to line "
488 << End.asLocation().getInstantiationLineNumber();
489 break;
490 case Stmt::DefaultStmtClass:
491 os << "Control jumps to the 'default' case at line "
492 << End.asLocation().getInstantiationLineNumber();
493 break;
494
495 case Stmt::CaseStmtClass: {
496 os << "Control jumps to 'case ";
497 CaseStmt* Case = cast<CaseStmt>(S);
498 Expr* LHS = Case->getLHS()->IgnoreParenCasts();
499
500 // Determine if it is an enum.
501 bool GetRawInt = true;
502
503 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(LHS)) {
504 // FIXME: Maybe this should be an assertion. Are there cases
505 // were it is not an EnumConstantDecl?
506 EnumConstantDecl* D =
507 dyn_cast<EnumConstantDecl>(DR->getDecl());
508
509 if (D) {
510 GetRawInt = false;
511 os << D->getNameAsString();
512 }
513 }
514
515 if (GetRawInt) {
516
517 // Not an enum.
518 Expr* CondE = cast<SwitchStmt>(T)->getCond();
519 unsigned bits = Ctx.getTypeSize(CondE->getType());
520 llvm::APSInt V(bits, false);
521
522 if (!LHS->isIntegerConstantExpr(V, Ctx, 0, true)) {
523 assert (false && "Case condition must be constant.");
524 continue;
525 }
526
527 os << V;
528 }
529
530 os << ":' at line "
531 << End.asLocation().getInstantiationLineNumber();
532 break;
533 }
534 }
535 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
536 os.str()));
537 }
538 else {
539 os << "'Default' branch taken. ";
540 const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
541 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
542 os.str()));
543 }
544
545 break;
546 }
547
548 case Stmt::BreakStmtClass:
549 case Stmt::ContinueStmtClass: {
550 std::string sbuf;
551 llvm::raw_string_ostream os(sbuf);
552 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
553 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
554 os.str()));
555 break;
556 }
557
558 // Determine control-flow for ternary '?'.
559 case Stmt::ConditionalOperatorClass: {
560 std::string sbuf;
561 llvm::raw_string_ostream os(sbuf);
562 os << "'?' condition is ";
563
564 if (*(Src->succ_begin()+1) == Dst)
565 os << "false";
566 else
567 os << "true";
568
569 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
570
571 if (const Stmt *S = End.asStmt())
572 End = PDB.getEnclosingStmtLocation(S);
573
574 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
575 os.str()));
576 break;
577 }
578
579 // Determine control-flow for short-circuited '&&' and '||'.
580 case Stmt::BinaryOperatorClass: {
581 if (!PDB.supportsLogicalOpControlFlow())
582 break;
583
584 BinaryOperator *B = cast<BinaryOperator>(T);
585 std::string sbuf;
586 llvm::raw_string_ostream os(sbuf);
587 os << "Left side of '";
588
589 if (B->getOpcode() == BinaryOperator::LAnd) {
590 os << "&&" << "' is ";
591
592 if (*(Src->succ_begin()+1) == Dst) {
593 os << "false";
594 PathDiagnosticLocation End(B->getLHS(), SMgr);
595 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
596 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
597 os.str()));
598 }
599 else {
600 os << "true";
601 PathDiagnosticLocation Start(B->getLHS(), SMgr);
602 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
603 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
604 os.str()));
605 }
606 }
607 else {
608 assert(B->getOpcode() == BinaryOperator::LOr);
609 os << "||" << "' is ";
610
611 if (*(Src->succ_begin()+1) == Dst) {
612 os << "false";
613 PathDiagnosticLocation Start(B->getLHS(), SMgr);
614 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
615 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
616 os.str()));
617 }
618 else {
619 os << "true";
620 PathDiagnosticLocation End(B->getLHS(), SMgr);
621 PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
622 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
623 os.str()));
624 }
625 }
626
627 break;
628 }
629
630 case Stmt::DoStmtClass: {
631 if (*(Src->succ_begin()) == Dst) {
632 std::string sbuf;
633 llvm::raw_string_ostream os(sbuf);
634
635 os << "Loop condition is true. ";
636 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
637
638 if (const Stmt *S = End.asStmt())
639 End = PDB.getEnclosingStmtLocation(S);
640
641 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
642 os.str()));
643 }
644 else {
645 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
646
647 if (const Stmt *S = End.asStmt())
648 End = PDB.getEnclosingStmtLocation(S);
649
650 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
651 "Loop condition is false. Exiting loop"));
652 }
653
654 break;
655 }
656
657 case Stmt::WhileStmtClass:
658 case Stmt::ForStmtClass: {
659 if (*(Src->succ_begin()+1) == Dst) {
660 std::string sbuf;
661 llvm::raw_string_ostream os(sbuf);
662
663 os << "Loop condition is false. ";
664 PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
665 if (const Stmt *S = End.asStmt())
666 End = PDB.getEnclosingStmtLocation(S);
667
668 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
669 os.str()));
670 }
671 else {
672 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
673 if (const Stmt *S = End.asStmt())
674 End = PDB.getEnclosingStmtLocation(S);
675
676 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
677 "Loop condition is true. Entering loop body"));
678 }
679
680 break;
681 }
682
683 case Stmt::IfStmtClass: {
684 PathDiagnosticLocation End = PDB.ExecutionContinues(N);
685
686 if (const Stmt *S = End.asStmt())
687 End = PDB.getEnclosingStmtLocation(S);
688
689 if (*(Src->succ_begin()+1) == Dst)
690 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
691 "Taking false branch"));
692 else
693 PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
694 "Taking true branch"));
695
696 break;
697 }
698 }
699 }
700
701 if (PathDiagnosticPiece* p =
702 PDB.getReport().VisitNode(N, NextNode, PDB.getGraph(),
703 PDB.getBugReporter(),
704 PDB.getNodeMapClosure())) {
705 PD.push_front(p);
706 }
707
708 if (const PostStmt* PS = dyn_cast<PostStmt>(&P)) {
709 // Scan the region bindings, and see if a "notable" symbol has a new
710 // lval binding.
711 ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
712 PDB.getStateManager().iterBindings(N->getState(), SNS);
713 }
714 }
715}
716
717//===----------------------------------------------------------------------===//
Ted Kremenekcf118d42009-02-04 23:49:09 +0000718// Methods for BugType and subclasses.
719//===----------------------------------------------------------------------===//
720BugType::~BugType() {}
721void BugType::FlushReports(BugReporter &BR) {}
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000722
Ted Kremenekcf118d42009-02-04 23:49:09 +0000723//===----------------------------------------------------------------------===//
724// Methods for BugReport and subclasses.
725//===----------------------------------------------------------------------===//
726BugReport::~BugReport() {}
727RangedBugReport::~RangedBugReport() {}
728
729Stmt* BugReport::getStmt(BugReporter& BR) const {
Ted Kremenek200ed922008-05-02 23:21:21 +0000730 ProgramPoint ProgP = EndNode->getLocation();
Ted Kremenekbd7efa82008-04-17 23:44:37 +0000731 Stmt *S = NULL;
732
Ted Kremenekcf118d42009-02-04 23:49:09 +0000733 if (BlockEntrance* BE = dyn_cast<BlockEntrance>(&ProgP)) {
Ted Kremenekb697b102009-02-23 22:44:26 +0000734 if (BE->getBlock() == &BR.getCFG()->getExit()) S = GetPreviousStmt(EndNode);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000735 }
736 if (!S) S = GetStmt(ProgP);
737
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000738 return S;
739}
740
741PathDiagnosticPiece*
742BugReport::getEndPath(BugReporter& BR,
Ted Kremenek3148eb42009-01-24 00:55:43 +0000743 const ExplodedNode<GRState>* EndPathNode) {
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000744
745 Stmt* S = getStmt(BR);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000746
747 if (!S)
748 return NULL;
749
Ted Kremenekc9fa2f72008-05-01 23:13:35 +0000750 FullSourceLoc L(S->getLocStart(), BR.getContext().getSourceManager());
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +0000751 PathDiagnosticPiece* P = new PathDiagnosticEventPiece(L, getDescription());
Ted Kremenek61f3e052008-04-03 04:42:52 +0000752
Ted Kremenekde7161f2008-04-03 18:00:37 +0000753 const SourceRange *Beg, *End;
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000754 getRanges(BR, Beg, End);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000755
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000756 for (; Beg != End; ++Beg)
757 P->addRange(*Beg);
Ted Kremenek61f3e052008-04-03 04:42:52 +0000758
759 return P;
760}
761
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000762void BugReport::getRanges(BugReporter& BR, const SourceRange*& beg,
763 const SourceRange*& end) {
764
765 if (Expr* E = dyn_cast_or_null<Expr>(getStmt(BR))) {
766 R = E->getSourceRange();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000767 assert(R.isValid());
Ted Kremenekbb77e9b2008-05-01 22:50:36 +0000768 beg = &R;
769 end = beg+1;
770 }
771 else
772 beg = end = 0;
Ted Kremenekf1ae7052008-04-03 17:57:38 +0000773}
774
Ted Kremenekcf118d42009-02-04 23:49:09 +0000775SourceLocation BugReport::getLocation() const {
776 if (EndNode)
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000777 if (Stmt* S = GetCurrentOrPreviousStmt(EndNode)) {
778 // For member expressions, return the location of the '.' or '->'.
779 if (MemberExpr* ME = dyn_cast<MemberExpr>(S))
780 return ME->getMemberLoc();
781
Ted Kremenekcf118d42009-02-04 23:49:09 +0000782 return S->getLocStart();
Ted Kremenek9b5e5052009-02-27 20:05:10 +0000783 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000784
785 return FullSourceLoc();
Ted Kremenekd2f642b2008-04-14 17:39:48 +0000786}
787
Ted Kremenek3148eb42009-01-24 00:55:43 +0000788PathDiagnosticPiece* BugReport::VisitNode(const ExplodedNode<GRState>* N,
789 const ExplodedNode<GRState>* PrevN,
790 const ExplodedGraph<GRState>& G,
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000791 BugReporter& BR,
792 NodeResolver &NR) {
Ted Kremenek50a6d0c2008-04-09 21:41:14 +0000793 return NULL;
794}
795
Ted Kremenekcf118d42009-02-04 23:49:09 +0000796//===----------------------------------------------------------------------===//
797// Methods for BugReporter and subclasses.
798//===----------------------------------------------------------------------===//
799
800BugReportEquivClass::~BugReportEquivClass() {
801 for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
802}
803
804GRBugReporter::~GRBugReporter() { FlushReports(); }
805BugReporterData::~BugReporterData() {}
806
807ExplodedGraph<GRState>&
808GRBugReporter::getGraph() { return Eng.getGraph(); }
809
810GRStateManager&
811GRBugReporter::getStateManager() { return Eng.getStateManager(); }
812
813BugReporter::~BugReporter() { FlushReports(); }
814
815void BugReporter::FlushReports() {
816 if (BugTypes.isEmpty())
817 return;
818
819 // First flush the warnings for each BugType. This may end up creating new
820 // warnings and new BugTypes. Because ImmutableSet is a functional data
821 // structure, we do not need to worry about the iterators being invalidated.
822 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
823 const_cast<BugType*>(*I)->FlushReports(*this);
824
825 // Iterate through BugTypes a second time. BugTypes may have been updated
826 // with new BugType objects and new warnings.
827 for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I) {
828 BugType *BT = const_cast<BugType*>(*I);
829
830 typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
831 SetTy& EQClasses = BT->EQClasses;
832
833 for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
834 BugReportEquivClass& EQ = *EI;
835 FlushReport(EQ);
836 }
Ted Kremeneka43a1eb2008-04-23 23:02:12 +0000837
Ted Kremenekcf118d42009-02-04 23:49:09 +0000838 // Delete the BugType object. This will also delete the equivalence
839 // classes.
840 delete BT;
Ted Kremenek94826a72008-04-03 04:59:14 +0000841 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000842
843 // Remove all references to the BugType objects.
844 BugTypes = F.GetEmptySet();
845}
846
847//===----------------------------------------------------------------------===//
848// PathDiagnostics generation.
849//===----------------------------------------------------------------------===//
850
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000851static std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenekcf118d42009-02-04 23:49:09 +0000852 std::pair<ExplodedNode<GRState>*, unsigned> >
853MakeReportGraph(const ExplodedGraph<GRState>* G,
854 const ExplodedNode<GRState>** NStart,
855 const ExplodedNode<GRState>** NEnd) {
Ted Kremenek94826a72008-04-03 04:59:14 +0000856
Ted Kremenekcf118d42009-02-04 23:49:09 +0000857 // Create the trimmed graph. It will contain the shortest paths from the
858 // error nodes to the root. In the new graph we should only have one
859 // error node unless there are two or more error nodes with the same minimum
860 // path length.
861 ExplodedGraph<GRState>* GTrim;
862 InterExplodedGraphMap<GRState>* NMap;
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000863
864 llvm::DenseMap<const void*, const void*> InverseMap;
865 llvm::tie(GTrim, NMap) = G->Trim(NStart, NEnd, &InverseMap);
Ted Kremenekcf118d42009-02-04 23:49:09 +0000866
867 // Create owning pointers for GTrim and NMap just to ensure that they are
868 // released when this function exists.
869 llvm::OwningPtr<ExplodedGraph<GRState> > AutoReleaseGTrim(GTrim);
870 llvm::OwningPtr<InterExplodedGraphMap<GRState> > AutoReleaseNMap(NMap);
871
872 // Find the (first) error node in the trimmed graph. We just need to consult
873 // the node map (NMap) which maps from nodes in the original graph to nodes
874 // in the new graph.
875 const ExplodedNode<GRState>* N = 0;
876 unsigned NodeIndex = 0;
877
878 for (const ExplodedNode<GRState>** I = NStart; I != NEnd; ++I)
879 if ((N = NMap->getMappedNode(*I))) {
880 NodeIndex = (I - NStart) / sizeof(*I);
881 break;
882 }
883
884 assert(N && "No error node found in the trimmed graph.");
885
886 // Create a new (third!) graph with a single path. This is the graph
887 // that will be returned to the caller.
Ted Kremenek3148eb42009-01-24 00:55:43 +0000888 ExplodedGraph<GRState> *GNew =
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000889 new ExplodedGraph<GRState>(GTrim->getCFG(), GTrim->getCodeDecl(),
890 GTrim->getContext());
Ted Kremenekcf118d42009-02-04 23:49:09 +0000891
Ted Kremenek10aa5542009-03-12 23:41:59 +0000892 // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000893 // to the root node, and then construct a new graph that contains only
894 // a single path.
Ted Kremenek3148eb42009-01-24 00:55:43 +0000895 llvm::DenseMap<const void*,unsigned> Visited;
Ted Kremenek10aa5542009-03-12 23:41:59 +0000896 std::queue<const ExplodedNode<GRState>*> WS;
897 WS.push(N);
898
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000899 unsigned cnt = 0;
Ted Kremenek3148eb42009-01-24 00:55:43 +0000900 const ExplodedNode<GRState>* Root = 0;
Ted Kremenekc1da4412008-06-17 19:14:06 +0000901
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000902 while (!WS.empty()) {
Ted Kremenek10aa5542009-03-12 23:41:59 +0000903 const ExplodedNode<GRState>* Node = WS.front();
904 WS.pop();
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000905
906 if (Visited.find(Node) != Visited.end())
907 continue;
908
909 Visited[Node] = cnt++;
910
911 if (Node->pred_empty()) {
912 Root = Node;
913 break;
914 }
915
Ted Kremenek3148eb42009-01-24 00:55:43 +0000916 for (ExplodedNode<GRState>::const_pred_iterator I=Node->pred_begin(),
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000917 E=Node->pred_end(); I!=E; ++I)
Ted Kremenek10aa5542009-03-12 23:41:59 +0000918 WS.push(*I);
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000919 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000920
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000921 assert (Root);
922
Ted Kremenek10aa5542009-03-12 23:41:59 +0000923 // Now walk from the root down the BFS path, always taking the successor
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000924 // with the lowest number.
Ted Kremenek4adc81e2008-08-13 04:27:00 +0000925 ExplodedNode<GRState> *Last = 0, *First = 0;
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000926 NodeBackMap *BM = new NodeBackMap();
Ted Kremenekcf118d42009-02-04 23:49:09 +0000927
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000928 for ( N = Root ;;) {
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000929 // Lookup the number associated with the current node.
Ted Kremenek3148eb42009-01-24 00:55:43 +0000930 llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000931 assert (I != Visited.end());
932
933 // Create the equivalent node in the new graph with the same state
934 // and location.
Ted Kremenek4adc81e2008-08-13 04:27:00 +0000935 ExplodedNode<GRState>* NewN =
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000936 GNew->getNode(N->getLocation(), N->getState());
937
938 // Store the mapping to the original node.
939 llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
940 assert(IMitr != InverseMap.end() && "No mapping to original node.");
941 (*BM)[NewN] = (const ExplodedNode<GRState>*) IMitr->second;
Ted Kremenekcf118d42009-02-04 23:49:09 +0000942
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000943 // Link up the new node with the previous node.
944 if (Last)
945 NewN->addPredecessor(Last);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +0000946
947 Last = NewN;
Ted Kremenekcf118d42009-02-04 23:49:09 +0000948
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000949 // Are we at the final node?
950 if (I->second == 0) {
951 First = NewN;
Ted Kremenekc1da4412008-06-17 19:14:06 +0000952 break;
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000953 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000954
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000955 // Find the next successor node. We choose the node that is marked
956 // with the lowest DFS number.
Ted Kremenek3148eb42009-01-24 00:55:43 +0000957 ExplodedNode<GRState>::const_succ_iterator SI = N->succ_begin();
958 ExplodedNode<GRState>::const_succ_iterator SE = N->succ_end();
Ted Kremenekc1da4412008-06-17 19:14:06 +0000959 N = 0;
960
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000961 for (unsigned MinVal = 0; SI != SE; ++SI) {
Ted Kremenekcf118d42009-02-04 23:49:09 +0000962
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000963 I = Visited.find(*SI);
964
965 if (I == Visited.end())
966 continue;
967
968 if (!N || I->second < MinVal) {
969 N = *SI;
970 MinVal = I->second;
Ted Kremenekc1da4412008-06-17 19:14:06 +0000971 }
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000972 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000973
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000974 assert (N);
Ted Kremeneka43a1eb2008-04-23 23:02:12 +0000975 }
Ted Kremenekcf118d42009-02-04 23:49:09 +0000976
Ted Kremenek331b0ac2008-06-18 05:34:07 +0000977 assert (First);
Ted Kremenekfe9e5432009-02-18 03:48:14 +0000978 return std::make_pair(std::make_pair(GNew, BM),
979 std::make_pair(First, NodeIndex));
Ted Kremeneka43a1eb2008-04-23 23:02:12 +0000980}
981
Ted Kremenek0e5c8d42009-03-10 05:16:17 +0000982/// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
983/// and collapses PathDiagosticPieces that are expanded by macros.
984static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
985 typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
986 MacroStackTy;
987
988 typedef std::vector<PathDiagnosticPiece*>
989 PiecesTy;
990
991 MacroStackTy MacroStack;
992 PiecesTy Pieces;
993
994 for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
995 // Get the location of the PathDiagnosticPiece.
996 const FullSourceLoc Loc = I->getLocation();
997
998 // Determine the instantiation location, which is the location we group
999 // related PathDiagnosticPieces.
1000 SourceLocation InstantiationLoc = Loc.isMacroID() ?
1001 SM.getInstantiationLoc(Loc) :
1002 SourceLocation();
1003
1004 if (Loc.isFileID()) {
1005 MacroStack.clear();
1006 Pieces.push_back(&*I);
1007 continue;
1008 }
1009
1010 assert(Loc.isMacroID());
1011
1012 // Is the PathDiagnosticPiece within the same macro group?
1013 if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
1014 MacroStack.back().first->push_back(&*I);
1015 continue;
1016 }
1017
1018 // We aren't in the same group. Are we descending into a new macro
1019 // or are part of an old one?
1020 PathDiagnosticMacroPiece *MacroGroup = 0;
1021
1022 SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
1023 SM.getInstantiationLoc(Loc) :
1024 SourceLocation();
1025
1026 // Walk the entire macro stack.
1027 while (!MacroStack.empty()) {
1028 if (InstantiationLoc == MacroStack.back().second) {
1029 MacroGroup = MacroStack.back().first;
1030 break;
1031 }
1032
1033 if (ParentInstantiationLoc == MacroStack.back().second) {
1034 MacroGroup = MacroStack.back().first;
1035 break;
1036 }
1037
1038 MacroStack.pop_back();
1039 }
1040
1041 if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
1042 // Create a new macro group and add it to the stack.
1043 PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
1044
1045 if (MacroGroup)
1046 MacroGroup->push_back(NewGroup);
1047 else {
1048 assert(InstantiationLoc.isFileID());
1049 Pieces.push_back(NewGroup);
1050 }
1051
1052 MacroGroup = NewGroup;
1053 MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
1054 }
1055
1056 // Finally, add the PathDiagnosticPiece to the group.
1057 MacroGroup->push_back(&*I);
1058 }
1059
1060 // Now take the pieces and construct a new PathDiagnostic.
1061 PD.resetPath(false);
1062
1063 for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
1064 if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
1065 if (!MP->containsEvent()) {
1066 delete MP;
1067 continue;
1068 }
1069
1070 PD.push_back(*I);
1071 }
1072}
1073
Ted Kremenek7dc86642009-03-31 20:22:36 +00001074void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
1075 BugReportEquivClass& EQ) {
1076
1077 std::vector<const ExplodedNode<GRState>*> Nodes;
1078
Ted Kremenekcf118d42009-02-04 23:49:09 +00001079 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
1080 const ExplodedNode<GRState>* N = I->getEndNode();
1081 if (N) Nodes.push_back(N);
1082 }
1083
1084 if (Nodes.empty())
1085 return;
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001086
1087 // Construct a new graph that contains only a single path from the error
Ted Kremenekcf118d42009-02-04 23:49:09 +00001088 // node to a root.
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001089 const std::pair<std::pair<ExplodedGraph<GRState>*, NodeBackMap*>,
Ted Kremenek7dc86642009-03-31 20:22:36 +00001090 std::pair<ExplodedNode<GRState>*, unsigned> >&
1091 GPair = MakeReportGraph(&getGraph(), &Nodes[0], &Nodes[0] + Nodes.size());
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001092
Ted Kremenekcf118d42009-02-04 23:49:09 +00001093 // Find the BugReport with the original location.
1094 BugReport *R = 0;
1095 unsigned i = 0;
1096 for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I, ++i)
1097 if (i == GPair.second.second) { R = *I; break; }
1098
1099 assert(R && "No original report found for sliced graph.");
Ted Kremeneka43a1eb2008-04-23 23:02:12 +00001100
Ted Kremenekfe9e5432009-02-18 03:48:14 +00001101 llvm::OwningPtr<ExplodedGraph<GRState> > ReportGraph(GPair.first.first);
1102 llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001103 const ExplodedNode<GRState> *N = GPair.second.first;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001104
Ted Kremenekcf118d42009-02-04 23:49:09 +00001105 // Start building the path diagnostic...
1106 if (PathDiagnosticPiece* Piece = R->getEndPath(*this, N))
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001107 PD.push_back(Piece);
1108 else
1109 return;
Ted Kremenek7dc86642009-03-31 20:22:36 +00001110
1111 PathDiagnosticBuilder PDB(*this, ReportGraph.get(), R, BackMap.get(),
1112 getStateManager().getCodeDecl(),
Ted Kremenekbabdd7b2009-03-27 05:06:10 +00001113 getPathDiagnosticClient());
Ted Kremenekbd7efa82008-04-17 23:44:37 +00001114
Ted Kremenek7dc86642009-03-31 20:22:36 +00001115 switch (PDB.getGenerationScheme()) {
1116 case PathDiagnosticClient::Extensive:
1117 case PathDiagnosticClient::Minimal:
1118 GenerateMinimalPathDiagnostic(PD, PDB, N);
1119 break;
1120 }
1121
1122 // After constructing the full PathDiagnostic, do a pass over it to compact
1123 // PathDiagnosticPieces that occur within a macro.
1124 CompactPathDiagnostic(PD, PDB.getSourceManager());
1125}
1126
Ted Kremenekcf118d42009-02-04 23:49:09 +00001127void BugReporter::Register(BugType *BT) {
1128 BugTypes = F.Add(BugTypes, BT);
Ted Kremenek76d90c82008-05-16 18:33:14 +00001129}
1130
Ted Kremenekcf118d42009-02-04 23:49:09 +00001131void BugReporter::EmitReport(BugReport* R) {
1132 // Compute the bug report's hash to determine its equivalence class.
1133 llvm::FoldingSetNodeID ID;
1134 R->Profile(ID);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001135
Ted Kremenekcf118d42009-02-04 23:49:09 +00001136 // Lookup the equivance class. If there isn't one, create it.
1137 BugType& BT = R->getBugType();
1138 Register(&BT);
1139 void *InsertPos;
1140 BugReportEquivClass* EQ = BT.EQClasses.FindNodeOrInsertPos(ID, InsertPos);
1141
1142 if (!EQ) {
1143 EQ = new BugReportEquivClass(R);
1144 BT.EQClasses.InsertNode(EQ, InsertPos);
1145 }
1146 else
1147 EQ->AddReport(R);
Ted Kremenek61f3e052008-04-03 04:42:52 +00001148}
1149
Ted Kremenekcf118d42009-02-04 23:49:09 +00001150void BugReporter::FlushReport(BugReportEquivClass& EQ) {
1151 assert(!EQ.Reports.empty());
1152 BugReport &R = **EQ.begin();
1153
1154 // FIXME: Make sure we use the 'R' for the path that was actually used.
1155 // Probably doesn't make a difference in practice.
1156 BugType& BT = R.getBugType();
1157
1158 llvm::OwningPtr<PathDiagnostic> D(new PathDiagnostic(R.getBugType().getName(),
1159 R.getDescription(),
1160 BT.getCategory()));
1161 GeneratePathDiagnostic(*D.get(), EQ);
Ted Kremenek072192b2008-04-30 23:47:44 +00001162
1163 // Get the meta data.
Ted Kremenek072192b2008-04-30 23:47:44 +00001164 std::pair<const char**, const char**> Meta = R.getExtraDescriptiveText();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001165 for (const char** s = Meta.first; s != Meta.second; ++s) D->addMeta(*s);
Ted Kremenek75840e12008-04-18 01:56:37 +00001166
Ted Kremenek3148eb42009-01-24 00:55:43 +00001167 // Emit a summary diagnostic to the regular Diagnostics engine.
Ted Kremenekc0959972008-07-02 21:24:01 +00001168 PathDiagnosticClient* PD = getPathDiagnosticClient();
Ted Kremenek3148eb42009-01-24 00:55:43 +00001169 const SourceRange *Beg = 0, *End = 0;
1170 R.getRanges(*this, Beg, End);
1171 Diagnostic& Diag = getDiagnostic();
Ted Kremenekcf118d42009-02-04 23:49:09 +00001172 FullSourceLoc L(R.getLocation(), getSourceManager());
Ted Kremenekd90e7082009-02-07 22:36:41 +00001173 unsigned ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning,
1174 R.getDescription().c_str());
Ted Kremenek57202072008-07-14 17:40:50 +00001175
Ted Kremenek3148eb42009-01-24 00:55:43 +00001176 switch (End-Beg) {
Chris Lattner0a14eee2008-11-18 07:04:44 +00001177 default: assert(0 && "Don't handle this many ranges yet!");
1178 case 0: Diag.Report(L, ErrorDiag); break;
1179 case 1: Diag.Report(L, ErrorDiag) << Beg[0]; break;
1180 case 2: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1]; break;
1181 case 3: Diag.Report(L, ErrorDiag) << Beg[0] << Beg[1] << Beg[2]; break;
Ted Kremenek2f0e89e2008-04-18 22:56:53 +00001182 }
Ted Kremenek3148eb42009-01-24 00:55:43 +00001183
1184 // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
1185 if (!PD)
1186 return;
1187
1188 if (D->empty()) {
Ted Kremenek1fbfd5b2009-03-06 23:58:11 +00001189 PathDiagnosticPiece* piece =
1190 new PathDiagnosticEventPiece(L, R.getDescription());
1191
Ted Kremenek3148eb42009-01-24 00:55:43 +00001192 for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
1193 D->push_back(piece);
1194 }
1195
1196 PD->HandlePathDiagnostic(D.take());
Ted Kremenek61f3e052008-04-03 04:42:52 +00001197}
Ted Kremenek57202072008-07-14 17:40:50 +00001198
Ted Kremenek8c036c72008-09-20 04:23:38 +00001199void BugReporter::EmitBasicReport(const char* name, const char* str,
1200 SourceLocation Loc,
1201 SourceRange* RBeg, unsigned NumRanges) {
1202 EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
1203}
Ted Kremenekcf118d42009-02-04 23:49:09 +00001204
Ted Kremenek8c036c72008-09-20 04:23:38 +00001205void BugReporter::EmitBasicReport(const char* name, const char* category,
1206 const char* str, SourceLocation Loc,
1207 SourceRange* RBeg, unsigned NumRanges) {
1208
Ted Kremenekcf118d42009-02-04 23:49:09 +00001209 // 'BT' will be owned by BugReporter as soon as we call 'EmitReport'.
1210 BugType *BT = new BugType(name, category);
Chris Lattner0a14eee2008-11-18 07:04:44 +00001211 FullSourceLoc L = getContext().getFullLoc(Loc);
Ted Kremenekcf118d42009-02-04 23:49:09 +00001212 RangedBugReport *R = new DiagBugReport(*BT, str, L);
1213 for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
1214 EmitReport(R);
Ted Kremenek57202072008-07-14 17:40:50 +00001215}