• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- PathDiagnostic.h - 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 #ifndef LLVM_CLANG_PATH_DIAGNOSTIC_H
15 #define LLVM_CLANG_PATH_DIAGNOSTIC_H
16 
17 #include "clang/Analysis/ProgramPoint.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/PointerUnion.h"
23 #include <deque>
24 #include <iterator>
25 #include <string>
26 #include <vector>
27 
28 namespace clang {
29 
30 class AnalysisDeclContext;
31 class BinaryOperator;
32 class CompoundStmt;
33 class Decl;
34 class LocationContext;
35 class MemberExpr;
36 class ParentMap;
37 class ProgramPoint;
38 class SourceManager;
39 class Stmt;
40 
41 namespace ento {
42 
43 class ExplodedNode;
44 class SymExpr;
45 typedef const SymExpr* SymbolRef;
46 
47 //===----------------------------------------------------------------------===//
48 // High-level interface for handlers of path-sensitive diagnostics.
49 //===----------------------------------------------------------------------===//
50 
51 class PathDiagnostic;
52 
53 class PathDiagnosticConsumer {
54 public:
55   class PDFileEntry : public llvm::FoldingSetNode {
56   public:
PDFileEntry(llvm::FoldingSetNodeID & NodeID)57     PDFileEntry(llvm::FoldingSetNodeID &NodeID) : NodeID(NodeID) {}
58 
59     typedef std::vector<std::pair<StringRef, StringRef> > ConsumerFiles;
60 
61     /// \brief A vector of <consumer,file> pairs.
62     ConsumerFiles files;
63 
64     /// \brief A precomputed hash tag used for uniquing PDFileEntry objects.
65     const llvm::FoldingSetNodeID NodeID;
66 
67     /// \brief Used for profiling in the FoldingSet.
Profile(llvm::FoldingSetNodeID & ID)68     void Profile(llvm::FoldingSetNodeID &ID) { ID = NodeID; }
69   };
70 
71   struct FilesMade : public llvm::FoldingSet<PDFileEntry> {
72     llvm::BumpPtrAllocator Alloc;
73 
74     void addDiagnostic(const PathDiagnostic &PD,
75                        StringRef ConsumerName,
76                        StringRef fileName);
77 
78     PDFileEntry::ConsumerFiles *getFiles(const PathDiagnostic &PD);
79   };
80 
81 private:
82   virtual void anchor();
83 public:
PathDiagnosticConsumer()84   PathDiagnosticConsumer() : flushed(false) {}
85   virtual ~PathDiagnosticConsumer();
86 
87   void FlushDiagnostics(FilesMade *FilesMade);
88 
89   virtual void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
90                                     FilesMade *filesMade) = 0;
91 
92   virtual StringRef getName() const = 0;
93 
94   void HandlePathDiagnostic(PathDiagnostic *D);
95 
96   enum PathGenerationScheme { None, Minimal, Extensive };
getGenerationScheme()97   virtual PathGenerationScheme getGenerationScheme() const { return Minimal; }
supportsLogicalOpControlFlow()98   virtual bool supportsLogicalOpControlFlow() const { return false; }
supportsAllBlockEdges()99   virtual bool supportsAllBlockEdges() const { return false; }
100 
101   /// Return true if the PathDiagnosticConsumer supports individual
102   /// PathDiagnostics that span multiple files.
supportsCrossFileDiagnostics()103   virtual bool supportsCrossFileDiagnostics() const { return false; }
104 
105 protected:
106   bool flushed;
107   llvm::FoldingSet<PathDiagnostic> Diags;
108 };
109 
110 //===----------------------------------------------------------------------===//
111 // Path-sensitive diagnostics.
112 //===----------------------------------------------------------------------===//
113 
114 class PathDiagnosticRange : public SourceRange {
115 public:
116   bool isPoint;
117 
118   PathDiagnosticRange(const SourceRange &R, bool isP = false)
SourceRange(R)119     : SourceRange(R), isPoint(isP) {}
120 
PathDiagnosticRange()121   PathDiagnosticRange() : isPoint(false) {}
122 };
123 
124 typedef llvm::PointerUnion<const LocationContext*, AnalysisDeclContext*>
125                                                    LocationOrAnalysisDeclContext;
126 
127 class PathDiagnosticLocation {
128 private:
129   enum Kind { RangeK, SingleLocK, StmtK, DeclK } K;
130   const Stmt *S;
131   const Decl *D;
132   const SourceManager *SM;
133   FullSourceLoc Loc;
134   PathDiagnosticRange Range;
135 
PathDiagnosticLocation(SourceLocation L,const SourceManager & sm,Kind kind)136   PathDiagnosticLocation(SourceLocation L, const SourceManager &sm,
137                          Kind kind)
138     : K(kind), S(0), D(0), SM(&sm),
139       Loc(genLocation(L)), Range(genRange()) {
140   }
141 
142   FullSourceLoc
143     genLocation(SourceLocation L = SourceLocation(),
144                 LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext*)0) const;
145 
146   PathDiagnosticRange
147     genRange(LocationOrAnalysisDeclContext LAC = (AnalysisDeclContext*)0) const;
148 
149 public:
150   /// Create an invalid location.
PathDiagnosticLocation()151   PathDiagnosticLocation()
152     : K(SingleLocK), S(0), D(0), SM(0) {}
153 
154   /// Create a location corresponding to the given statement.
PathDiagnosticLocation(const Stmt * s,const SourceManager & sm,LocationOrAnalysisDeclContext lac)155   PathDiagnosticLocation(const Stmt *s,
156                          const SourceManager &sm,
157                          LocationOrAnalysisDeclContext lac)
158     : K(s->getLocStart().isValid() ? StmtK : SingleLocK),
159       S(K == StmtK ? s : 0),
160       D(0), SM(&sm),
161       Loc(genLocation(SourceLocation(), lac)),
162       Range(genRange(lac)) {
163     assert(K == SingleLocK || S);
164     assert(K == SingleLocK || Loc.isValid());
165     assert(K == SingleLocK || Range.isValid());
166   }
167 
168   /// Create a location corresponding to the given declaration.
PathDiagnosticLocation(const Decl * d,const SourceManager & sm)169   PathDiagnosticLocation(const Decl *d, const SourceManager &sm)
170     : K(DeclK), S(0), D(d), SM(&sm),
171       Loc(genLocation()), Range(genRange()) {
172     assert(D);
173     assert(Loc.isValid());
174     assert(Range.isValid());
175   }
176 
177   /// Create a location at an explicit offset in the source.
178   ///
179   /// This should only be used if there are no more appropriate constructors.
PathDiagnosticLocation(SourceLocation loc,const SourceManager & sm)180   PathDiagnosticLocation(SourceLocation loc, const SourceManager &sm)
181     : K(SingleLocK), S(0), D(0), SM(&sm), Loc(loc, sm), Range(genRange()) {
182     assert(Loc.isValid());
183     assert(Range.isValid());
184   }
185 
186   /// Create a location corresponding to the given declaration.
create(const Decl * D,const SourceManager & SM)187   static PathDiagnosticLocation create(const Decl *D,
188                                        const SourceManager &SM) {
189     return PathDiagnosticLocation(D, SM);
190   }
191 
192   /// Create a location for the beginning of the declaration.
193   static PathDiagnosticLocation createBegin(const Decl *D,
194                                             const SourceManager &SM);
195 
196   /// Create a location for the beginning of the statement.
197   static PathDiagnosticLocation createBegin(const Stmt *S,
198                                             const SourceManager &SM,
199                                             const LocationOrAnalysisDeclContext LAC);
200 
201   /// Create a location for the end of the statement.
202   ///
203   /// If the statement is a CompoundStatement, the location will point to the
204   /// closing brace instead of following it.
205   static PathDiagnosticLocation createEnd(const Stmt *S,
206                                           const SourceManager &SM,
207                                        const LocationOrAnalysisDeclContext LAC);
208 
209   /// Create the location for the operator of the binary expression.
210   /// Assumes the statement has a valid location.
211   static PathDiagnosticLocation createOperatorLoc(const BinaryOperator *BO,
212                                                   const SourceManager &SM);
213 
214   /// For member expressions, return the location of the '.' or '->'.
215   /// Assumes the statement has a valid location.
216   static PathDiagnosticLocation createMemberLoc(const MemberExpr *ME,
217                                                 const SourceManager &SM);
218 
219   /// Create a location for the beginning of the compound statement.
220   /// Assumes the statement has a valid location.
221   static PathDiagnosticLocation createBeginBrace(const CompoundStmt *CS,
222                                                  const SourceManager &SM);
223 
224   /// Create a location for the end of the compound statement.
225   /// Assumes the statement has a valid location.
226   static PathDiagnosticLocation createEndBrace(const CompoundStmt *CS,
227                                                const SourceManager &SM);
228 
229   /// Create a location for the beginning of the enclosing declaration body.
230   /// Defaults to the beginning of the first statement in the declaration body.
231   static PathDiagnosticLocation createDeclBegin(const LocationContext *LC,
232                                                 const SourceManager &SM);
233 
234   /// Constructs a location for the end of the enclosing declaration body.
235   /// Defaults to the end of brace.
236   static PathDiagnosticLocation createDeclEnd(const LocationContext *LC,
237                                                    const SourceManager &SM);
238 
239   /// Create a location corresponding to the given valid ExplodedNode.
240   static PathDiagnosticLocation create(const ProgramPoint& P,
241                                        const SourceManager &SMng);
242 
243   /// Create a location corresponding to the next valid ExplodedNode as end
244   /// of path location.
245   static PathDiagnosticLocation createEndOfPath(const ExplodedNode* N,
246                                                 const SourceManager &SM);
247 
248   /// Convert the given location into a single kind location.
249   static PathDiagnosticLocation createSingleLocation(
250                                              const PathDiagnosticLocation &PDL);
251 
252   bool operator==(const PathDiagnosticLocation &X) const {
253     return K == X.K && Loc == X.Loc && Range == X.Range;
254   }
255 
256   bool operator!=(const PathDiagnosticLocation &X) const {
257     return !(*this == X);
258   }
259 
isValid()260   bool isValid() const {
261     return SM != 0;
262   }
263 
asLocation()264   FullSourceLoc asLocation() const {
265     return Loc;
266   }
267 
asRange()268   PathDiagnosticRange asRange() const {
269     return Range;
270   }
271 
asStmt()272   const Stmt *asStmt() const { assert(isValid()); return S; }
asDecl()273   const Decl *asDecl() const { assert(isValid()); return D; }
274 
hasRange()275   bool hasRange() const { return K == StmtK || K == RangeK || K == DeclK; }
276 
invalidate()277   void invalidate() {
278     *this = PathDiagnosticLocation();
279   }
280 
281   void flatten();
282 
getManager()283   const SourceManager& getManager() const { assert(isValid()); return *SM; }
284 
285   void Profile(llvm::FoldingSetNodeID &ID) const;
286 };
287 
288 class PathDiagnosticLocationPair {
289 private:
290   PathDiagnosticLocation Start, End;
291 public:
PathDiagnosticLocationPair(const PathDiagnosticLocation & start,const PathDiagnosticLocation & end)292   PathDiagnosticLocationPair(const PathDiagnosticLocation &start,
293                              const PathDiagnosticLocation &end)
294     : Start(start), End(end) {}
295 
getStart()296   const PathDiagnosticLocation &getStart() const { return Start; }
getEnd()297   const PathDiagnosticLocation &getEnd() const { return End; }
298 
flatten()299   void flatten() {
300     Start.flatten();
301     End.flatten();
302   }
303 
Profile(llvm::FoldingSetNodeID & ID)304   void Profile(llvm::FoldingSetNodeID &ID) const {
305     Start.Profile(ID);
306     End.Profile(ID);
307   }
308 };
309 
310 //===----------------------------------------------------------------------===//
311 // Path "pieces" for path-sensitive diagnostics.
312 //===----------------------------------------------------------------------===//
313 
314 class PathDiagnosticPiece : public RefCountedBaseVPTR {
315 public:
316   enum Kind { ControlFlow, Event, Macro, Call };
317   enum DisplayHint { Above, Below };
318 
319 private:
320   const std::string str;
321   const Kind kind;
322   const DisplayHint Hint;
323 
324   /// A constant string that can be used to tag the PathDiagnosticPiece,
325   /// typically with the identification of the creator.  The actual pointer
326   /// value is meant to be an identifier; the string itself is useful for
327   /// debugging.
328   StringRef Tag;
329 
330   std::vector<SourceRange> ranges;
331 
332   PathDiagnosticPiece() LLVM_DELETED_FUNCTION;
333   PathDiagnosticPiece(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
334   void operator=(const PathDiagnosticPiece &P) LLVM_DELETED_FUNCTION;
335 
336 protected:
337   PathDiagnosticPiece(StringRef s, Kind k, DisplayHint hint = Below);
338 
339   PathDiagnosticPiece(Kind k, DisplayHint hint = Below);
340 
341 public:
342   virtual ~PathDiagnosticPiece();
343 
getString()344   StringRef getString() const { return str; }
345 
346   /// Tag this PathDiagnosticPiece with the given C-string.
setTag(const char * tag)347   void setTag(const char *tag) { Tag = tag; }
348 
349   /// Return the opaque tag (if any) on the PathDiagnosticPiece.
getTag()350   const void *getTag() const { return Tag.data(); }
351 
352   /// Return the string representation of the tag.  This is useful
353   /// for debugging.
getTagStr()354   StringRef getTagStr() const { return Tag; }
355 
356   /// getDisplayHint - Return a hint indicating where the diagnostic should
357   ///  be displayed by the PathDiagnosticConsumer.
getDisplayHint()358   DisplayHint getDisplayHint() const { return Hint; }
359 
360   virtual PathDiagnosticLocation getLocation() const = 0;
361   virtual void flattenLocations() = 0;
362 
getKind()363   Kind getKind() const { return kind; }
364 
addRange(SourceRange R)365   void addRange(SourceRange R) {
366     if (!R.isValid())
367       return;
368     ranges.push_back(R);
369   }
370 
addRange(SourceLocation B,SourceLocation E)371   void addRange(SourceLocation B, SourceLocation E) {
372     if (!B.isValid() || !E.isValid())
373       return;
374     ranges.push_back(SourceRange(B,E));
375   }
376 
377   /// Return the SourceRanges associated with this PathDiagnosticPiece.
getRanges()378   ArrayRef<SourceRange> getRanges() const { return ranges; }
379 
380   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
381 };
382 
383 
384 class PathPieces : public std::deque<IntrusiveRefCntPtr<PathDiagnosticPiece> > {
385   void flattenTo(PathPieces &Primary, PathPieces &Current,
386                  bool ShouldFlattenMacros) const;
387 public:
388   ~PathPieces();
389 
flatten(bool ShouldFlattenMacros)390   PathPieces flatten(bool ShouldFlattenMacros) const {
391     PathPieces Result;
392     flattenTo(Result, Result, ShouldFlattenMacros);
393     return Result;
394   }
395 };
396 
397 class PathDiagnosticSpotPiece : public PathDiagnosticPiece {
398 private:
399   PathDiagnosticLocation Pos;
400 public:
401   PathDiagnosticSpotPiece(const PathDiagnosticLocation &pos,
402                           StringRef s,
403                           PathDiagnosticPiece::Kind k,
404                           bool addPosRange = true)
PathDiagnosticPiece(s,k)405   : PathDiagnosticPiece(s, k), Pos(pos) {
406     assert(Pos.isValid() && Pos.asLocation().isValid() &&
407            "PathDiagnosticSpotPiece's must have a valid location.");
408     if (addPosRange && Pos.hasRange()) addRange(Pos.asRange());
409   }
410 
getLocation()411   PathDiagnosticLocation getLocation() const { return Pos; }
flattenLocations()412   virtual void flattenLocations() { Pos.flatten(); }
413 
414   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
415 
classof(const PathDiagnosticPiece * P)416   static bool classof(const PathDiagnosticPiece *P) {
417     return P->getKind() == Event || P->getKind() == Macro;
418   }
419 };
420 
421 /// \brief Interface for classes constructing Stack hints.
422 ///
423 /// If a PathDiagnosticEvent occurs in a different frame than the final
424 /// diagnostic the hints can be used to summarize the effect of the call.
425 class StackHintGenerator {
426 public:
427   virtual ~StackHintGenerator() = 0;
428 
429   /// \brief Construct the Diagnostic message for the given ExplodedNode.
430   virtual std::string getMessage(const ExplodedNode *N) = 0;
431 };
432 
433 /// \brief Constructs a Stack hint for the given symbol.
434 ///
435 /// The class knows how to construct the stack hint message based on
436 /// traversing the CallExpr associated with the call and checking if the given
437 /// symbol is returned or is one of the arguments.
438 /// The hint can be customized by redefining 'getMessageForX()' methods.
439 class StackHintGeneratorForSymbol : public StackHintGenerator {
440 private:
441   SymbolRef Sym;
442   std::string Msg;
443 
444 public:
StackHintGeneratorForSymbol(SymbolRef S,StringRef M)445   StackHintGeneratorForSymbol(SymbolRef S, StringRef M) : Sym(S), Msg(M) {}
~StackHintGeneratorForSymbol()446   virtual ~StackHintGeneratorForSymbol() {}
447 
448   /// \brief Search the call expression for the symbol Sym and dispatch the
449   /// 'getMessageForX()' methods to construct a specific message.
450   virtual std::string getMessage(const ExplodedNode *N);
451 
452   /// Produces the message of the following form:
453   ///   'Msg via Nth parameter'
454   virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex);
getMessageForReturn(const CallExpr * CallExpr)455   virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
456     return Msg;
457   }
getMessageForSymbolNotFound()458   virtual std::string getMessageForSymbolNotFound() {
459     return Msg;
460   }
461 };
462 
463 class PathDiagnosticEventPiece : public PathDiagnosticSpotPiece {
464   Optional<bool> IsPrunable;
465 
466   /// If the event occurs in a different frame than the final diagnostic,
467   /// supply a message that will be used to construct an extra hint on the
468   /// returns from all the calls on the stack from this event to the final
469   /// diagnostic.
470   OwningPtr<StackHintGenerator> CallStackHint;
471 
472 public:
473   PathDiagnosticEventPiece(const PathDiagnosticLocation &pos,
474                            StringRef s, bool addPosRange = true,
475                            StackHintGenerator *stackHint = 0)
PathDiagnosticSpotPiece(pos,s,Event,addPosRange)476     : PathDiagnosticSpotPiece(pos, s, Event, addPosRange),
477       CallStackHint(stackHint) {}
478 
479   ~PathDiagnosticEventPiece();
480 
481   /// Mark the diagnostic piece as being potentially prunable.  This
482   /// flag may have been previously set, at which point it will not
483   /// be reset unless one specifies to do so.
484   void setPrunable(bool isPrunable, bool override = false) {
485     if (IsPrunable.hasValue() && !override)
486      return;
487     IsPrunable = isPrunable;
488   }
489 
490   /// Return true if the diagnostic piece is prunable.
isPrunable()491   bool isPrunable() const {
492     return IsPrunable.hasValue() ? IsPrunable.getValue() : false;
493   }
494 
hasCallStackHint()495   bool hasCallStackHint() {
496     return (CallStackHint != 0);
497   }
498 
499   /// Produce the hint for the given node. The node contains
500   /// information about the call for which the diagnostic can be generated.
getCallStackMessage(const ExplodedNode * N)501   std::string getCallStackMessage(const ExplodedNode *N) {
502     if (CallStackHint)
503       return CallStackHint->getMessage(N);
504     return "";
505   }
506 
classof(const PathDiagnosticPiece * P)507   static inline bool classof(const PathDiagnosticPiece *P) {
508     return P->getKind() == Event;
509   }
510 };
511 
512 class PathDiagnosticCallPiece : public PathDiagnosticPiece {
PathDiagnosticCallPiece(const Decl * callerD,const PathDiagnosticLocation & callReturnPos)513   PathDiagnosticCallPiece(const Decl *callerD,
514                           const PathDiagnosticLocation &callReturnPos)
515     : PathDiagnosticPiece(Call), Caller(callerD), Callee(0),
516       NoExit(false), callReturn(callReturnPos) {}
517 
PathDiagnosticCallPiece(PathPieces & oldPath,const Decl * caller)518   PathDiagnosticCallPiece(PathPieces &oldPath, const Decl *caller)
519     : PathDiagnosticPiece(Call), Caller(caller), Callee(0),
520       NoExit(true), path(oldPath) {}
521 
522   const Decl *Caller;
523   const Decl *Callee;
524 
525   // Flag signifying that this diagnostic has only call enter and no matching
526   // call exit.
527   bool NoExit;
528 
529   // The custom string, which should appear after the call Return Diagnostic.
530   // TODO: Should we allow multiple diagnostics?
531   std::string CallStackMessage;
532 
533 public:
534   PathDiagnosticLocation callEnter;
535   PathDiagnosticLocation callEnterWithin;
536   PathDiagnosticLocation callReturn;
537   PathPieces path;
538 
539   virtual ~PathDiagnosticCallPiece();
540 
getCaller()541   const Decl *getCaller() const { return Caller; }
542 
getCallee()543   const Decl *getCallee() const { return Callee; }
544   void setCallee(const CallEnter &CE, const SourceManager &SM);
545 
hasCallStackMessage()546   bool hasCallStackMessage() { return !CallStackMessage.empty(); }
setCallStackMessage(StringRef st)547   void setCallStackMessage(StringRef st) {
548     CallStackMessage = st;
549   }
550 
getLocation()551   virtual PathDiagnosticLocation getLocation() const {
552     return callEnter;
553   }
554 
555   IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallEnterEvent() const;
556   IntrusiveRefCntPtr<PathDiagnosticEventPiece>
557     getCallEnterWithinCallerEvent() const;
558   IntrusiveRefCntPtr<PathDiagnosticEventPiece> getCallExitEvent() const;
559 
flattenLocations()560   virtual void flattenLocations() {
561     callEnter.flatten();
562     callReturn.flatten();
563     for (PathPieces::iterator I = path.begin(),
564          E = path.end(); I != E; ++I) (*I)->flattenLocations();
565   }
566 
567   static PathDiagnosticCallPiece *construct(const ExplodedNode *N,
568                                             const CallExitEnd &CE,
569                                             const SourceManager &SM);
570 
571   static PathDiagnosticCallPiece *construct(PathPieces &pieces,
572                                             const Decl *caller);
573 
574   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
575 
classof(const PathDiagnosticPiece * P)576   static inline bool classof(const PathDiagnosticPiece *P) {
577     return P->getKind() == Call;
578   }
579 };
580 
581 class PathDiagnosticControlFlowPiece : public PathDiagnosticPiece {
582   std::vector<PathDiagnosticLocationPair> LPairs;
583 public:
PathDiagnosticControlFlowPiece(const PathDiagnosticLocation & startPos,const PathDiagnosticLocation & endPos,StringRef s)584   PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos,
585                                  const PathDiagnosticLocation &endPos,
586                                  StringRef s)
587     : PathDiagnosticPiece(s, ControlFlow) {
588       LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos));
589     }
590 
PathDiagnosticControlFlowPiece(const PathDiagnosticLocation & startPos,const PathDiagnosticLocation & endPos)591   PathDiagnosticControlFlowPiece(const PathDiagnosticLocation &startPos,
592                                  const PathDiagnosticLocation &endPos)
593     : PathDiagnosticPiece(ControlFlow) {
594       LPairs.push_back(PathDiagnosticLocationPair(startPos, endPos));
595     }
596 
597   ~PathDiagnosticControlFlowPiece();
598 
getStartLocation()599   PathDiagnosticLocation getStartLocation() const {
600     assert(!LPairs.empty() &&
601            "PathDiagnosticControlFlowPiece needs at least one location.");
602     return LPairs[0].getStart();
603   }
604 
getEndLocation()605   PathDiagnosticLocation getEndLocation() const {
606     assert(!LPairs.empty() &&
607            "PathDiagnosticControlFlowPiece needs at least one location.");
608     return LPairs[0].getEnd();
609   }
610 
push_back(const PathDiagnosticLocationPair & X)611   void push_back(const PathDiagnosticLocationPair &X) { LPairs.push_back(X); }
612 
getLocation()613   virtual PathDiagnosticLocation getLocation() const {
614     return getStartLocation();
615   }
616 
617   typedef std::vector<PathDiagnosticLocationPair>::iterator iterator;
begin()618   iterator begin() { return LPairs.begin(); }
end()619   iterator end()   { return LPairs.end(); }
620 
flattenLocations()621   virtual void flattenLocations() {
622     for (iterator I=begin(), E=end(); I!=E; ++I) I->flatten();
623   }
624 
625   typedef std::vector<PathDiagnosticLocationPair>::const_iterator
626           const_iterator;
begin()627   const_iterator begin() const { return LPairs.begin(); }
end()628   const_iterator end() const   { return LPairs.end(); }
629 
classof(const PathDiagnosticPiece * P)630   static inline bool classof(const PathDiagnosticPiece *P) {
631     return P->getKind() == ControlFlow;
632   }
633 
634   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
635 };
636 
637 class PathDiagnosticMacroPiece : public PathDiagnosticSpotPiece {
638 public:
PathDiagnosticMacroPiece(const PathDiagnosticLocation & pos)639   PathDiagnosticMacroPiece(const PathDiagnosticLocation &pos)
640     : PathDiagnosticSpotPiece(pos, "", Macro) {}
641 
642   ~PathDiagnosticMacroPiece();
643 
644   PathPieces subPieces;
645 
646   bool containsEvent() const;
647 
flattenLocations()648   virtual void flattenLocations() {
649     PathDiagnosticSpotPiece::flattenLocations();
650     for (PathPieces::iterator I = subPieces.begin(),
651          E = subPieces.end(); I != E; ++I) (*I)->flattenLocations();
652   }
653 
classof(const PathDiagnosticPiece * P)654   static inline bool classof(const PathDiagnosticPiece *P) {
655     return P->getKind() == Macro;
656   }
657 
658   virtual void Profile(llvm::FoldingSetNodeID &ID) const;
659 };
660 
661 /// PathDiagnostic - PathDiagnostic objects represent a single path-sensitive
662 ///  diagnostic.  It represents an ordered-collection of PathDiagnosticPieces,
663 ///  each which represent the pieces of the path.
664 class PathDiagnostic : public llvm::FoldingSetNode {
665   const Decl *DeclWithIssue;
666   std::string BugType;
667   std::string VerboseDesc;
668   std::string ShortDesc;
669   std::string Category;
670   std::deque<std::string> OtherDesc;
671   PathDiagnosticLocation Loc;
672   PathPieces pathImpl;
673   SmallVector<PathPieces *, 3> pathStack;
674 
675   /// \brief Important bug uniqueing location.
676   /// The location info is useful to differentiate between bugs.
677   PathDiagnosticLocation UniqueingLoc;
678   const Decl *UniqueingDecl;
679 
680   PathDiagnostic() LLVM_DELETED_FUNCTION;
681 public:
682   PathDiagnostic(const Decl *DeclWithIssue, StringRef bugtype,
683                  StringRef verboseDesc, StringRef shortDesc,
684                  StringRef category, PathDiagnosticLocation LocationToUnique,
685                  const Decl *DeclToUnique);
686 
687   ~PathDiagnostic();
688 
689   const PathPieces &path;
690 
691   /// Return the path currently used by builders for constructing the
692   /// PathDiagnostic.
getActivePath()693   PathPieces &getActivePath() {
694     if (pathStack.empty())
695       return pathImpl;
696     return *pathStack.back();
697   }
698 
699   /// Return a mutable version of 'path'.
getMutablePieces()700   PathPieces &getMutablePieces() {
701     return pathImpl;
702   }
703 
704   /// Return the unrolled size of the path.
705   unsigned full_size();
706 
pushActivePath(PathPieces * p)707   void pushActivePath(PathPieces *p) { pathStack.push_back(p); }
popActivePath()708   void popActivePath() { if (!pathStack.empty()) pathStack.pop_back(); }
709 
isWithinCall()710   bool isWithinCall() const { return !pathStack.empty(); }
711 
setEndOfPath(PathDiagnosticPiece * EndPiece)712   void setEndOfPath(PathDiagnosticPiece *EndPiece) {
713     assert(!Loc.isValid() && "End location already set!");
714     Loc = EndPiece->getLocation();
715     assert(Loc.isValid() && "Invalid location for end-of-path piece");
716     getActivePath().push_back(EndPiece);
717   }
718 
resetPath()719   void resetPath() {
720     pathStack.clear();
721     pathImpl.clear();
722     Loc = PathDiagnosticLocation();
723   }
724 
getVerboseDescription()725   StringRef getVerboseDescription() const { return VerboseDesc; }
getShortDescription()726   StringRef getShortDescription() const {
727     return ShortDesc.empty() ? VerboseDesc : ShortDesc;
728   }
getBugType()729   StringRef getBugType() const { return BugType; }
getCategory()730   StringRef getCategory() const { return Category; }
731 
732   /// Return the semantic context where an issue occurred.  If the
733   /// issue occurs along a path, this represents the "central" area
734   /// where the bug manifests.
getDeclWithIssue()735   const Decl *getDeclWithIssue() const { return DeclWithIssue; }
736 
737   typedef std::deque<std::string>::const_iterator meta_iterator;
meta_begin()738   meta_iterator meta_begin() const { return OtherDesc.begin(); }
meta_end()739   meta_iterator meta_end() const { return OtherDesc.end(); }
addMeta(StringRef s)740   void addMeta(StringRef s) { OtherDesc.push_back(s); }
741 
getLocation()742   PathDiagnosticLocation getLocation() const {
743     assert(Loc.isValid() && "No end-of-path location set yet!");
744     return Loc;
745   }
746 
747   /// \brief Get the location on which the report should be uniqued.
getUniqueingLoc()748   PathDiagnosticLocation getUniqueingLoc() const {
749     return UniqueingLoc;
750   }
751 
752   /// \brief Get the declaration containing the uniqueing location.
getUniqueingDecl()753   const Decl *getUniqueingDecl() const {
754     return UniqueingDecl;
755   }
756 
flattenLocations()757   void flattenLocations() {
758     Loc.flatten();
759     for (PathPieces::iterator I = pathImpl.begin(), E = pathImpl.end();
760          I != E; ++I) (*I)->flattenLocations();
761   }
762 
763   /// Profiles the diagnostic, independent of the path it references.
764   ///
765   /// This can be used to merge diagnostics that refer to the same issue
766   /// along different paths.
767   void Profile(llvm::FoldingSetNodeID &ID) const;
768 
769   /// Profiles the diagnostic, including its path.
770   ///
771   /// Two diagnostics with the same issue along different paths will generate
772   /// different profiles.
773   void FullProfile(llvm::FoldingSetNodeID &ID) const;
774 };
775 
776 } // end GR namespace
777 
778 } //end clang namespace
779 
780 #endif
781