PathDiagnostic.cpp revision b490c4bb01a5a3a86947851fa66823dda32ed012
1//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- 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 the PathDiagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/AST/StmtCXX.h"
21#include "llvm/ADT/SmallString.h"
22
23using namespace clang;
24using namespace ento;
25
26bool PathDiagnosticMacroPiece::containsEvent() const {
27  for (const_iterator I = begin(), E = end(); I!=E; ++I) {
28    if (isa<PathDiagnosticEventPiece>(*I))
29      return true;
30
31    if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
32      if (MP->containsEvent())
33        return true;
34  }
35
36  return false;
37}
38
39static StringRef StripTrailingDots(StringRef s) {
40  for (StringRef::size_type i = s.size(); i != 0; --i)
41    if (s[i - 1] != '.')
42      return s.substr(0, i);
43  return "";
44}
45
46PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
47                                         Kind k, DisplayHint hint)
48  : str(StripTrailingDots(s)), kind(k), Hint(hint) {}
49
50PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
51  : kind(k), Hint(hint) {}
52
53PathDiagnosticPiece::~PathDiagnosticPiece() {}
54PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
55PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
56
57PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {
58  for (iterator I = begin(), E = end(); I != E; ++I) delete *I;
59}
60
61PathDiagnostic::PathDiagnostic() : Size(0) {}
62
63PathDiagnostic::~PathDiagnostic() {
64  for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
65}
66
67void PathDiagnostic::resetPath(bool deletePieces) {
68  Size = 0;
69
70  if (deletePieces)
71    for (iterator I=begin(), E=end(); I!=E; ++I)
72      delete &*I;
73
74  path.clear();
75}
76
77
78PathDiagnostic::PathDiagnostic(StringRef bugtype, StringRef desc,
79                               StringRef category)
80  : Size(0),
81    BugType(StripTrailingDots(bugtype)),
82    Desc(StripTrailingDots(desc)),
83    Category(StripTrailingDots(category)) {}
84
85void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
86                                            const DiagnosticInfo &Info) {
87  // Default implementation (Warnings/errors count).
88  DiagnosticClient::HandleDiagnostic(DiagLevel, Info);
89
90  // Create a PathDiagnostic with a single piece.
91
92  PathDiagnostic* D = new PathDiagnostic();
93
94  const char *LevelStr;
95  switch (DiagLevel) {
96  default:
97  case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
98  case Diagnostic::Note:    LevelStr = "note: "; break;
99  case Diagnostic::Warning: LevelStr = "warning: "; break;
100  case Diagnostic::Error:   LevelStr = "error: "; break;
101  case Diagnostic::Fatal:   LevelStr = "fatal error: "; break;
102  }
103
104  llvm::SmallString<100> StrC;
105  StrC += LevelStr;
106  Info.FormatDiagnostic(StrC);
107
108  PathDiagnosticPiece *P =
109    new PathDiagnosticEventPiece(FullSourceLoc(Info.getLocation(),
110                                               Info.getSourceManager()),
111                                 StrC.str());
112
113  for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
114    P->addRange(Info.getRange(i).getAsRange());
115  for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i)
116    P->addFixItHint(Info.getFixItHint(i));
117  D->push_front(P);
118
119  HandlePathDiagnostic(D);
120}
121
122void PathDiagnosticClient::HandlePathDiagnostic(const PathDiagnostic *D) {
123  // For now this simply forwards to HandlePathDiagnosticImpl.  In the future
124  // we can use this indirection to control for multi-threaded access to
125  // the PathDiagnosticClient from multiple bug reporters.
126  HandlePathDiagnosticImpl(D);
127}
128
129//===----------------------------------------------------------------------===//
130// PathDiagnosticLocation methods.
131//===----------------------------------------------------------------------===//
132
133static SourceLocation getValidSourceLocation(const Stmt* S,
134                                             const ParentMap &PM) {
135  SourceLocation L = S->getLocStart();
136
137  // S might be a temporary statement that does not have a location in the
138  // source code, so find an enclosing statement and use it's location.
139  while (!L.isValid()) {
140    S = PM.getParent(S);
141    L = S->getLocStart();
142  }
143
144  return L;
145}
146
147PathDiagnosticLocation::PathDiagnosticLocation(const Stmt *s,
148                                               const SourceManager &sm,
149                                               const LocationContext *lc)
150  : K(StmtK), S(s), D(0), SM(&sm), LC(lc)
151{
152  const ParentMap* PM = 0;
153  if (lc)
154    PM = &lc->getParentMap();
155
156  Loc = genLocation(PM);
157  Range = genRange(PM);
158}
159
160PathDiagnosticLocation
161  PathDiagnosticLocation::createBeginStmt(const Stmt *S,
162                                          const SourceManager &SM,
163                                          const LocationContext *LC) {
164  return PathDiagnosticLocation(getValidSourceLocation(S, LC->getParentMap()),
165                                SM, SingleLocK);
166}
167
168PathDiagnosticLocation
169  PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
170                                            const SourceManager &SM) {
171  return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
172}
173
174PathDiagnosticLocation
175  PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
176                                           const SourceManager &SM) {
177  SourceLocation L = CS->getLBracLoc();
178  return PathDiagnosticLocation(L, SM, SingleLocK);
179}
180
181PathDiagnosticLocation
182  PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
183                                         const SourceManager &SM) {
184  SourceLocation L = CS->getRBracLoc();
185  return PathDiagnosticLocation(L, SM, SingleLocK);
186}
187
188PathDiagnosticLocation
189  PathDiagnosticLocation::createDeclBegin(const LocationContext *LC,
190                                          const SourceManager &SM) {
191  // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
192  if (const CompoundStmt *CS =
193        dyn_cast_or_null<CompoundStmt>(LC->getDecl()->getBody()))
194    if (!CS->body_empty()) {
195      SourceLocation Loc = (*CS->body_begin())->getLocStart();
196      return PathDiagnosticLocation(Loc, SM, SingleLocK);
197    }
198
199  return PathDiagnosticLocation();
200}
201
202PathDiagnosticLocation
203  PathDiagnosticLocation::createDeclEnd(const LocationContext *LC,
204                                        const SourceManager &SM) {
205  SourceLocation L = LC->getDecl()->getBodyRBrace();
206  return PathDiagnosticLocation(L, SM, SingleLocK);
207}
208
209PathDiagnosticLocation
210  PathDiagnosticLocation::create(const ProgramPoint& P,
211                                 const SourceManager &SMng) {
212
213  const Stmt* S = 0;
214  if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
215    const CFGBlock *BSrc = BE->getSrc();
216    S = BSrc->getTerminatorCondition();
217  }
218  else if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
219    S = PS->getStmt();
220  }
221
222  return PathDiagnosticLocation(S, SMng, P.getLocationContext());
223
224  if (!S)
225    return PathDiagnosticLocation();
226}
227
228PathDiagnosticLocation
229  PathDiagnosticLocation::createEndOfPath(const ExplodedNode* N,
230                                          const SourceManager &SM) {
231  assert(N && "Cannot create a location with a null node.");
232
233  const ExplodedNode *NI = N;
234
235  while (NI) {
236    ProgramPoint P = NI->getLocation();
237    const LocationContext *LC = P.getLocationContext();
238    if (const StmtPoint *PS = dyn_cast<StmtPoint>(&P))
239      return PathDiagnosticLocation(PS->getStmt(), SM, LC);
240    else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
241      const Stmt *Term = BE->getSrc()->getTerminator();
242      assert(Term);
243      return PathDiagnosticLocation(Term, SM, LC);
244    }
245    NI = NI->succ_empty() ? 0 : *(NI->succ_begin());
246  }
247
248  return createDeclEnd(N->getLocationContext(), SM);
249}
250
251PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
252                                           const PathDiagnosticLocation &PDL) {
253  FullSourceLoc L = PDL.asLocation();
254  return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
255}
256
257FullSourceLoc
258  PathDiagnosticLocation::genLocation(const ParentMap *PM) const {
259  assert(isValid());
260  // Note that we want a 'switch' here so that the compiler can warn us in
261  // case we add more cases.
262  switch (K) {
263    case SingleLocK:
264    case RangeK:
265      break;
266    case StmtK:
267      return FullSourceLoc(getValidSourceLocation(S, LC->getParentMap()),
268                           const_cast<SourceManager&>(*SM));
269    case DeclK:
270      return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
271  }
272
273  return FullSourceLoc(R.getBegin(), const_cast<SourceManager&>(*SM));
274}
275
276PathDiagnosticRange
277  PathDiagnosticLocation::genRange(const ParentMap *PM) const {
278  assert(isValid());
279  // Note that we want a 'switch' here so that the compiler can warn us in
280  // case we add more cases.
281  switch (K) {
282    case SingleLocK:
283      return PathDiagnosticRange(R, true);
284    case RangeK:
285      break;
286    case StmtK: {
287      const Stmt *S = asStmt();
288      switch (S->getStmtClass()) {
289        default:
290          break;
291        case Stmt::DeclStmtClass: {
292          const DeclStmt *DS = cast<DeclStmt>(S);
293          if (DS->isSingleDecl()) {
294            // Should always be the case, but we'll be defensive.
295            return SourceRange(DS->getLocStart(),
296                               DS->getSingleDecl()->getLocation());
297          }
298          break;
299        }
300          // FIXME: Provide better range information for different
301          //  terminators.
302        case Stmt::IfStmtClass:
303        case Stmt::WhileStmtClass:
304        case Stmt::DoStmtClass:
305        case Stmt::ForStmtClass:
306        case Stmt::ChooseExprClass:
307        case Stmt::IndirectGotoStmtClass:
308        case Stmt::SwitchStmtClass:
309        case Stmt::BinaryConditionalOperatorClass:
310        case Stmt::ConditionalOperatorClass:
311        case Stmt::ObjCForCollectionStmtClass: {
312          SourceLocation L = getValidSourceLocation(S, LC->getParentMap());
313          return SourceRange(L, L);
314        }
315      }
316
317      return S->getSourceRange();
318    }
319    case DeclK:
320      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
321        return MD->getSourceRange();
322      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
323        if (Stmt *Body = FD->getBody())
324          return Body->getSourceRange();
325      }
326      else {
327        SourceLocation L = D->getLocation();
328        return PathDiagnosticRange(SourceRange(L, L), true);
329      }
330  }
331
332  return R;
333}
334
335void PathDiagnosticLocation::flatten() {
336  if (K == StmtK) {
337    R = asRange();
338    K = RangeK;
339    S = 0;
340    D = 0;
341  }
342  else if (K == DeclK) {
343    SourceLocation L = D->getLocation();
344    R = SourceRange(L, L);
345    K = SingleLocK;
346    S = 0;
347    D = 0;
348  }
349}
350
351//===----------------------------------------------------------------------===//
352// FoldingSet profiling methods.
353//===----------------------------------------------------------------------===//
354
355void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
356  ID.AddInteger((unsigned) K);
357  switch (K) {
358    case RangeK:
359      ID.AddInteger(R.getBegin().getRawEncoding());
360      ID.AddInteger(R.getEnd().getRawEncoding());
361      break;
362    case SingleLocK:
363      ID.AddInteger(R.getBegin().getRawEncoding());
364      break;
365    case StmtK:
366      ID.Add(S);
367      break;
368    case DeclK:
369      ID.Add(D);
370      break;
371  }
372  return;
373}
374
375void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
376  ID.AddInteger((unsigned) getKind());
377  ID.AddString(str);
378  // FIXME: Add profiling support for code hints.
379  ID.AddInteger((unsigned) getDisplayHint());
380  for (range_iterator I = ranges_begin(), E = ranges_end(); I != E; ++I) {
381    ID.AddInteger(I->getBegin().getRawEncoding());
382    ID.AddInteger(I->getEnd().getRawEncoding());
383  }
384}
385
386void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
387  PathDiagnosticPiece::Profile(ID);
388  ID.Add(Pos);
389}
390
391void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
392  PathDiagnosticPiece::Profile(ID);
393  for (const_iterator I = begin(), E = end(); I != E; ++I)
394    ID.Add(*I);
395}
396
397void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
398  PathDiagnosticSpotPiece::Profile(ID);
399  for (const_iterator I = begin(), E = end(); I != E; ++I)
400    ID.Add(**I);
401}
402
403void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
404  ID.AddInteger(Size);
405  ID.AddString(BugType);
406  ID.AddString(Desc);
407  ID.AddString(Category);
408  for (const_iterator I = begin(), E = end(); I != E; ++I)
409    ID.Add(*I);
410
411  for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
412    ID.AddString(*I);
413}
414