]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
In preparation for fixing PR 6884, rework CFGElement to have getAs<> return pointers...
[clang] / include / clang / Analysis / CFG.h
1 //===--- CFG.h - Classes for representing and building CFGs------*- 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 CFG and CFGBuilder classes for representing and
11 //  building Control-Flow Graphs (CFGs) from ASTs.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_CFG_H
16 #define LLVM_CLANG_CFG_H
17
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Casting.h"
22 #include "clang/Analysis/Support/BumpVector.h"
23 #include "clang/Basic/SourceLocation.h"
24 #include <cassert>
25 #include <iterator>
26
27 namespace llvm {
28   class raw_ostream;
29 }
30
31 namespace clang {
32   class CXXDestructorDecl;
33   class Decl;
34   class Stmt;
35   class Expr;
36   class FieldDecl;
37   class VarDecl;
38   class CXXCtorInitializer;
39   class CXXBaseSpecifier;
40   class CXXBindTemporaryExpr;
41   class CFG;
42   class PrinterHelper;
43   class LangOptions;
44   class ASTContext;
45
46 /// CFGElement - Represents a top-level expression in a basic block.
47 class CFGElement {
48 public:
49   enum Kind {
50     // main kind
51     Invalid,
52     Statement,
53     Initializer,
54     // dtor kind
55     AutomaticObjectDtor,
56     BaseDtor,
57     MemberDtor,
58     TemporaryDtor,
59     DTOR_BEGIN = AutomaticObjectDtor,
60     DTOR_END = TemporaryDtor
61   };
62
63 protected:
64   // The int bits are used to mark the kind.
65   llvm::PointerIntPair<void *, 2> Data1;
66   llvm::PointerIntPair<void *, 2> Data2;
67
68   CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = 0)
69     : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
70       Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {}  
71
72 public:
73   CFGElement() {}
74
75   Kind getKind() const { 
76     unsigned x = Data2.getInt();
77     x <<= 2;
78     x |= Data1.getInt();
79     return (Kind) x;
80   }
81     
82   bool isValid() const { return getKind() != Invalid; }
83
84   operator bool() const { return isValid(); }
85   
86   template<class ElemTy> const ElemTy *getAs() const {
87     if (llvm::isa<ElemTy>(this))
88       return static_cast<const ElemTy*>(this);
89     return 0;
90   }
91
92   static bool classof(const CFGElement *E) { return true; }
93 };
94
95 class CFGStmt : public CFGElement {
96 public:
97   CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
98
99   Stmt *getStmt() const { return static_cast<Stmt *>(Data1.getPointer()); }
100
101   static bool classof(const CFGElement *E) {
102     return E->getKind() == Statement;
103   }
104 };
105
106 /// CFGInitializer - Represents C++ base or member initializer from
107 /// constructor's initialization list.
108 class CFGInitializer : public CFGElement {
109 public:
110   CFGInitializer(CXXCtorInitializer *initializer)
111       : CFGElement(Initializer, initializer) {}
112
113   CXXCtorInitializer* getInitializer() const {
114     return static_cast<CXXCtorInitializer*>(Data1.getPointer());
115   }
116
117   static bool classof(const CFGElement *E) {
118     return E->getKind() == Initializer;
119   }
120 };
121
122 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
123 /// by compiler on various occasions.
124 class CFGImplicitDtor : public CFGElement {
125 protected:
126   CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = 0) 
127     : CFGElement(kind, data1, data2) {
128     assert(kind >= DTOR_BEGIN && kind <= DTOR_END);    
129   }
130
131 public:
132   const CXXDestructorDecl *getDestructorDecl() const;
133
134   static bool classof(const CFGElement *E) {
135     Kind kind = E->getKind();
136     return kind >= DTOR_BEGIN && kind <= DTOR_END;
137   }
138 };
139
140 /// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
141 /// for automatic object or temporary bound to const reference at the point
142 /// of leaving its local scope.
143 class CFGAutomaticObjDtor: public CFGImplicitDtor {
144 public:
145   CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
146       : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
147
148   const VarDecl *getVarDecl() const {
149     return static_cast<VarDecl*>(Data1.getPointer());
150   }
151
152   // Get statement end of which triggered the destructor call.
153   const Stmt *getTriggerStmt() const {
154     return static_cast<Stmt*>(Data2.getPointer());
155   }
156
157   static bool classof(const CFGElement *elem) {
158     return elem->getKind() == AutomaticObjectDtor;
159   }
160 };
161
162 /// CFGBaseDtor - Represents C++ object destructor implicitly generated for
163 /// base object in destructor.
164 class CFGBaseDtor : public CFGImplicitDtor {
165 public:
166   CFGBaseDtor(const CXXBaseSpecifier *base)
167       : CFGImplicitDtor(BaseDtor, base) {}
168
169   const CXXBaseSpecifier *getBaseSpecifier() const {
170     return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
171   }
172
173   static bool classof(const CFGElement *E) {
174     return E->getKind() == BaseDtor;
175   }
176 };
177
178 /// CFGMemberDtor - Represents C++ object destructor implicitly generated for
179 /// member object in destructor.
180 class CFGMemberDtor : public CFGImplicitDtor {
181 public:
182   CFGMemberDtor(const FieldDecl *field)
183       : CFGImplicitDtor(MemberDtor, field, 0) {}
184
185   const FieldDecl *getFieldDecl() const {
186     return static_cast<const FieldDecl*>(Data1.getPointer());
187   }
188
189   static bool classof(const CFGElement *E) {
190     return E->getKind() == MemberDtor;
191   }
192 };
193
194 /// CFGTemporaryDtor - Represents C++ object destructor implicitly generated
195 /// at the end of full expression for temporary object.
196 class CFGTemporaryDtor : public CFGImplicitDtor {
197 public:
198   CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
199       : CFGImplicitDtor(TemporaryDtor, expr, 0) {}
200
201   const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
202     return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
203   }
204
205   static bool classof(const CFGElement *E) {
206     return E->getKind() == TemporaryDtor;
207   }
208 };
209
210 /// CFGTerminator - Represents CFGBlock terminator statement.
211 ///
212 /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
213 /// in control flow of destructors of temporaries. In this case terminator
214 /// statement is the same statement that branches control flow in evaluation
215 /// of matching full expression.
216 class CFGTerminator {
217   llvm::PointerIntPair<Stmt *, 1> Data;
218 public:
219   CFGTerminator() {}
220   CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
221       : Data(S, TemporaryDtorsBranch) {}
222
223   Stmt *getStmt() { return Data.getPointer(); }
224   const Stmt *getStmt() const { return Data.getPointer(); }
225
226   bool isTemporaryDtorsBranch() const { return Data.getInt(); }
227
228   operator Stmt *() { return getStmt(); }
229   operator const Stmt *() const { return getStmt(); }
230
231   Stmt *operator->() { return getStmt(); }
232   const Stmt *operator->() const { return getStmt(); }
233
234   Stmt &operator*() { return *getStmt(); }
235   const Stmt &operator*() const { return *getStmt(); }
236
237   operator bool() const { return getStmt(); }
238 };
239
240 /// CFGBlock - Represents a single basic block in a source-level CFG.
241 ///  It consists of:
242 ///
243 ///  (1) A set of statements/expressions (which may contain subexpressions).
244 ///  (2) A "terminator" statement (not in the set of statements).
245 ///  (3) A list of successors and predecessors.
246 ///
247 /// Terminator: The terminator represents the type of control-flow that occurs
248 /// at the end of the basic block.  The terminator is a Stmt* referring to an
249 /// AST node that has control-flow: if-statements, breaks, loops, etc.
250 /// If the control-flow is conditional, the condition expression will appear
251 /// within the set of statements in the block (usually the last statement).
252 ///
253 /// Predecessors: the order in the set of predecessors is arbitrary.
254 ///
255 /// Successors: the order in the set of successors is NOT arbitrary.  We
256 ///  currently have the following orderings based on the terminator:
257 ///
258 ///     Terminator       Successor Ordering
259 ///  -----------------------------------------------------
260 ///       if            Then Block;  Else Block
261 ///     ? operator      LHS expression;  RHS expression
262 ///     &&, ||          expression that uses result of && or ||, RHS
263 ///
264 class CFGBlock {
265   class ElementList {
266     typedef BumpVector<CFGElement> ImplTy;
267     ImplTy Impl;
268   public:
269     ElementList(BumpVectorContext &C) : Impl(C, 4) {}
270     
271     typedef std::reverse_iterator<ImplTy::iterator>       iterator;
272     typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
273     typedef ImplTy::iterator                              reverse_iterator;
274     typedef ImplTy::const_iterator                        const_reverse_iterator;
275   
276     void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
277     reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
278         BumpVectorContext& C) {
279       return Impl.insert(I, Cnt, E, C);
280     }
281
282     CFGElement front() const { return Impl.back(); }
283     CFGElement back() const { return Impl.front(); }
284     
285     iterator begin() { return Impl.rbegin(); }
286     iterator end() { return Impl.rend(); }
287     const_iterator begin() const { return Impl.rbegin(); }
288     const_iterator end() const { return Impl.rend(); }
289     reverse_iterator rbegin() { return Impl.begin(); }
290     reverse_iterator rend() { return Impl.end(); }
291     const_reverse_iterator rbegin() const { return Impl.begin(); }
292     const_reverse_iterator rend() const { return Impl.end(); }
293
294    CFGElement operator[](size_t i) const  {
295      assert(i < Impl.size());
296      return Impl[Impl.size() - 1 - i];
297    }
298     
299     size_t size() const { return Impl.size(); }
300     bool empty() const { return Impl.empty(); }
301   };
302
303   /// Stmts - The set of statements in the basic block.
304   ElementList Elements;
305
306   /// Label - An (optional) label that prefixes the executable
307   ///  statements in the block.  When this variable is non-NULL, it is
308   ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
309   Stmt *Label;
310
311   /// Terminator - The terminator for a basic block that
312   ///  indicates the type of control-flow that occurs between a block
313   ///  and its successors.
314   CFGTerminator Terminator;
315
316   /// LoopTarget - Some blocks are used to represent the "loop edge" to
317   ///  the start of a loop from within the loop body.  This Stmt* will be
318   ///  refer to the loop statement for such blocks (and be null otherwise).
319   const Stmt *LoopTarget;
320
321   /// BlockID - A numerical ID assigned to a CFGBlock during construction
322   ///   of the CFG.
323   unsigned BlockID;
324
325   /// Predecessors/Successors - Keep track of the predecessor / successor
326   /// CFG blocks.
327   typedef BumpVector<CFGBlock*> AdjacentBlocks;
328   AdjacentBlocks Preds;
329   AdjacentBlocks Succs;
330
331 public:
332   explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
333     : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
334       BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
335   ~CFGBlock() {}
336
337   // Statement iterators
338   typedef ElementList::iterator                      iterator;
339   typedef ElementList::const_iterator                const_iterator;
340   typedef ElementList::reverse_iterator              reverse_iterator;
341   typedef ElementList::const_reverse_iterator        const_reverse_iterator;
342
343   CFGElement                 front()       const { return Elements.front();   }
344   CFGElement                 back()        const { return Elements.back();    }
345
346   iterator                   begin()             { return Elements.begin();   }
347   iterator                   end()               { return Elements.end();     }
348   const_iterator             begin()       const { return Elements.begin();   }
349   const_iterator             end()         const { return Elements.end();     }
350
351   reverse_iterator           rbegin()            { return Elements.rbegin();  }
352   reverse_iterator           rend()              { return Elements.rend();    }
353   const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
354   const_reverse_iterator     rend()        const { return Elements.rend();    }
355
356   unsigned                   size()        const { return Elements.size();    }
357   bool                       empty()       const { return Elements.empty();   }
358
359   CFGElement operator[](size_t i) const  { return Elements[i]; }
360
361   // CFG iterators
362   typedef AdjacentBlocks::iterator                              pred_iterator;
363   typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
364   typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
365   typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
366
367   typedef AdjacentBlocks::iterator                              succ_iterator;
368   typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
369   typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
370   typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
371
372   pred_iterator                pred_begin()        { return Preds.begin();   }
373   pred_iterator                pred_end()          { return Preds.end();     }
374   const_pred_iterator          pred_begin()  const { return Preds.begin();   }
375   const_pred_iterator          pred_end()    const { return Preds.end();     }
376
377   pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
378   pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
379   const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
380   const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
381
382   succ_iterator                succ_begin()        { return Succs.begin();   }
383   succ_iterator                succ_end()          { return Succs.end();     }
384   const_succ_iterator          succ_begin()  const { return Succs.begin();   }
385   const_succ_iterator          succ_end()    const { return Succs.end();     }
386
387   succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
388   succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
389   const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
390   const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
391
392   unsigned                     succ_size()   const { return Succs.size();    }
393   bool                         succ_empty()  const { return Succs.empty();   }
394
395   unsigned                     pred_size()   const { return Preds.size();    }
396   bool                         pred_empty()  const { return Preds.empty();   }
397
398
399   class FilterOptions {
400   public:
401     FilterOptions() {
402       IgnoreDefaultsWithCoveredEnums = 0;
403     }
404
405     unsigned IgnoreDefaultsWithCoveredEnums : 1;
406   };
407
408   static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
409        const CFGBlock *Dst);
410
411   template <typename IMPL, bool IsPred>
412   class FilteredCFGBlockIterator {
413   private:
414     IMPL I, E;
415     const FilterOptions F;
416     const CFGBlock *From;
417    public:
418     explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
419               const CFGBlock *from,
420               const FilterOptions &f)
421       : I(i), E(e), F(f), From(from) {}
422
423     bool hasMore() const { return I != E; }
424
425     FilteredCFGBlockIterator &operator++() {
426       do { ++I; } while (hasMore() && Filter(*I));
427       return *this;
428     }
429
430     const CFGBlock *operator*() const { return *I; }
431   private:
432     bool Filter(const CFGBlock *To) {
433       return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
434     }
435   };
436
437   typedef FilteredCFGBlockIterator<const_pred_iterator, true>
438           filtered_pred_iterator;
439
440   typedef FilteredCFGBlockIterator<const_succ_iterator, false>
441           filtered_succ_iterator;
442
443   filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
444     return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
445   }
446
447   filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
448     return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
449   }
450
451   // Manipulation of block contents
452
453   void setTerminator(Stmt* Statement) { Terminator = Statement; }
454   void setLabel(Stmt* Statement) { Label = Statement; }
455   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
456
457   CFGTerminator getTerminator() { return Terminator; }
458   const CFGTerminator getTerminator() const { return Terminator; }
459
460   Stmt* getTerminatorCondition();
461
462   const Stmt* getTerminatorCondition() const {
463     return const_cast<CFGBlock*>(this)->getTerminatorCondition();
464   }
465
466   const Stmt *getLoopTarget() const { return LoopTarget; }
467
468   bool hasBinaryBranchTerminator() const;
469
470   Stmt* getLabel() { return Label; }
471   const Stmt* getLabel() const { return Label; }
472
473   unsigned getBlockID() const { return BlockID; }
474
475   void dump(const CFG *cfg, const LangOptions &LO) const;
476   void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
477   void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
478   
479   void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
480     if (Block)
481       Block->Preds.push_back(this, C);
482     Succs.push_back(Block, C);
483   }
484   
485   void appendStmt(Stmt* statement, BumpVectorContext &C) {
486     Elements.push_back(CFGStmt(statement), C);
487   }
488
489   void appendInitializer(CXXCtorInitializer *initializer,
490                         BumpVectorContext& C) {
491     Elements.push_back(CFGInitializer(initializer), C);
492   }
493
494   void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
495     Elements.push_back(CFGBaseDtor(BS), C);
496   }
497
498   void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
499     Elements.push_back(CFGMemberDtor(FD), C);
500   }
501   
502   void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
503     Elements.push_back(CFGTemporaryDtor(E), C);
504   }
505
506   // Destructors must be inserted in reversed order. So insertion is in two
507   // steps. First we prepare space for some number of elements, then we insert
508   // the elements beginning at the last position in prepared space.
509   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
510       BumpVectorContext& C) {
511     return iterator(Elements.insert(I.base(), Cnt, CFGElement(), C));
512   }
513   iterator insertAutomaticObjDtor(iterator I, VarDecl* VD, Stmt* S) {
514     *I = CFGAutomaticObjDtor(VD, S);
515     return ++I;
516   }
517 };
518
519 /// CFG - Represents a source-level, intra-procedural CFG that represents the
520 ///  control-flow of a Stmt.  The Stmt can represent an entire function body,
521 ///  or a single expression.  A CFG will always contain one empty block that
522 ///  represents the Exit point of the CFG.  A CFG will also contain a designated
523 ///  Entry block.  The CFG solely represents control-flow; it consists of
524 ///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
525 ///  was constructed from.
526 class CFG {
527 public:
528   //===--------------------------------------------------------------------===//
529   // CFG Construction & Manipulation.
530   //===--------------------------------------------------------------------===//
531
532   class BuildOptions {
533   public:
534     bool PruneTriviallyFalseEdges:1;
535     bool AddEHEdges:1;
536     bool AddInitializers:1;
537     bool AddImplicitDtors:1;
538
539     BuildOptions()
540         : PruneTriviallyFalseEdges(true)
541         , AddEHEdges(false)
542         , AddInitializers(false)
543         , AddImplicitDtors(false) {}
544   };
545
546   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
547   ///   constructed CFG belongs to the caller.
548   static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
549       BuildOptions BO = BuildOptions());
550
551   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
552   ///  the caller should not directly free it.
553   CFGBlock* createBlock();
554
555   /// setEntry - Set the entry block of the CFG.  This is typically used
556   ///  only during CFG construction.  Most CFG clients expect that the
557   ///  entry block has no predecessors and contains no statements.
558   void setEntry(CFGBlock *B) { Entry = B; }
559
560   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
561   ///  This is typically used only during CFG construction.
562   void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
563
564   //===--------------------------------------------------------------------===//
565   // Block Iterators
566   //===--------------------------------------------------------------------===//
567
568   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;    
569   typedef CFGBlockListTy::iterator                 iterator;
570   typedef CFGBlockListTy::const_iterator           const_iterator;
571   typedef std::reverse_iterator<iterator>          reverse_iterator;
572   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
573
574   CFGBlock&                 front()                { return *Blocks.front(); }
575   CFGBlock&                 back()                 { return *Blocks.back(); }
576
577   iterator                  begin()                { return Blocks.begin(); }
578   iterator                  end()                  { return Blocks.end(); }
579   const_iterator            begin()       const    { return Blocks.begin(); }
580   const_iterator            end()         const    { return Blocks.end(); }
581
582   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
583   reverse_iterator          rend()                 { return Blocks.rend(); }
584   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
585   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
586
587   CFGBlock&                 getEntry()             { return *Entry; }
588   const CFGBlock&           getEntry()    const    { return *Entry; }
589   CFGBlock&                 getExit()              { return *Exit; }
590   const CFGBlock&           getExit()     const    { return *Exit; }
591
592   CFGBlock*        getIndirectGotoBlock() { return IndirectGotoBlock; }
593   const CFGBlock*  getIndirectGotoBlock() const { return IndirectGotoBlock; }
594
595   //===--------------------------------------------------------------------===//
596   // Member templates useful for various batch operations over CFGs.
597   //===--------------------------------------------------------------------===//
598
599   template <typename CALLBACK>
600   void VisitBlockStmts(CALLBACK& O) const {
601     for (const_iterator I=begin(), E=end(); I != E; ++I)
602       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
603            BI != BE; ++BI) {
604         if (const CFGStmt *stmt = BI->getAs<CFGStmt>())
605           O(stmt->getStmt());
606       }
607   }
608
609   //===--------------------------------------------------------------------===//
610   // CFG Introspection.
611   //===--------------------------------------------------------------------===//
612
613   struct   BlkExprNumTy {
614     const signed Idx;
615     explicit BlkExprNumTy(signed idx) : Idx(idx) {}
616     explicit BlkExprNumTy() : Idx(-1) {}
617     operator bool() const { return Idx >= 0; }
618     operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
619   };
620
621   bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
622   bool isBlkExpr(const Stmt *S) const {
623     return const_cast<CFG*>(this)->isBlkExpr(S);
624   }
625   BlkExprNumTy  getBlkExprNum(const Stmt* S);
626   unsigned      getNumBlkExprs();
627
628   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
629   /// start at 0).
630   unsigned getNumBlockIDs() const { return NumBlockIDs; }
631
632   //===--------------------------------------------------------------------===//
633   // CFG Debugging: Pretty-Printing and Visualization.
634   //===--------------------------------------------------------------------===//
635
636   void viewCFG(const LangOptions &LO) const;
637   void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
638   void dump(const LangOptions &LO) const;
639
640   //===--------------------------------------------------------------------===//
641   // Internal: constructors and data.
642   //===--------------------------------------------------------------------===//
643
644   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
645           BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
646
647   ~CFG();
648
649   llvm::BumpPtrAllocator& getAllocator() {
650     return BlkBVC.getAllocator();
651   }
652   
653   BumpVectorContext &getBumpVectorContext() {
654     return BlkBVC;
655   }
656
657 private:
658   CFGBlock* Entry;
659   CFGBlock* Exit;
660   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
661                                 // for indirect gotos
662   unsigned  NumBlockIDs;
663
664   // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
665   //  It represents a map from Expr* to integers to record the set of
666   //  block-level expressions and their "statement number" in the CFG.
667   void*     BlkExprMap;
668   
669   BumpVectorContext BlkBVC;
670   
671   CFGBlockListTy Blocks;
672
673 };
674 } // end namespace clang
675
676 //===----------------------------------------------------------------------===//
677 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
678 //===----------------------------------------------------------------------===//
679
680 namespace llvm {
681
682 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
683 /// CFGTerminator to a specific Stmt class.
684 template <> struct simplify_type<const ::clang::CFGTerminator> {
685   typedef const ::clang::Stmt *SimpleType;
686   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
687     return Val.getStmt();
688   }
689 };
690
691 template <> struct simplify_type< ::clang::CFGTerminator> {
692   typedef ::clang::Stmt *SimpleType;
693   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
694     return const_cast<SimpleType>(Val.getStmt());
695   }
696 };
697
698 // Traits for: CFGBlock
699
700 template <> struct GraphTraits< ::clang::CFGBlock* > {
701   typedef ::clang::CFGBlock NodeType;
702   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
703
704   static NodeType* getEntryNode(::clang::CFGBlock* BB)
705   { return BB; }
706
707   static inline ChildIteratorType child_begin(NodeType* N)
708   { return N->succ_begin(); }
709
710   static inline ChildIteratorType child_end(NodeType* N)
711   { return N->succ_end(); }
712 };
713
714 template <> struct GraphTraits< const ::clang::CFGBlock* > {
715   typedef const ::clang::CFGBlock NodeType;
716   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
717
718   static NodeType* getEntryNode(const clang::CFGBlock* BB)
719   { return BB; }
720
721   static inline ChildIteratorType child_begin(NodeType* N)
722   { return N->succ_begin(); }
723
724   static inline ChildIteratorType child_end(NodeType* N)
725   { return N->succ_end(); }
726 };
727
728 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
729   typedef const ::clang::CFGBlock NodeType;
730   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
731
732   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
733   { return G.Graph; }
734
735   static inline ChildIteratorType child_begin(NodeType* N)
736   { return N->pred_begin(); }
737
738   static inline ChildIteratorType child_end(NodeType* N)
739   { return N->pred_end(); }
740 };
741
742 // Traits for: CFG
743
744 template <> struct GraphTraits< ::clang::CFG* >
745     : public GraphTraits< ::clang::CFGBlock* >  {
746
747   typedef ::clang::CFG::iterator nodes_iterator;
748
749   static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
750   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
751   static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
752 };
753
754 template <> struct GraphTraits<const ::clang::CFG* >
755     : public GraphTraits<const ::clang::CFGBlock* >  {
756
757   typedef ::clang::CFG::const_iterator nodes_iterator;
758
759   static NodeType *getEntryNode( const ::clang::CFG* F) {
760     return &F->getEntry();
761   }
762   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
763     return F->begin();
764   }
765   static nodes_iterator nodes_end( const ::clang::CFG* F) {
766     return F->end();
767   }
768 };
769
770 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
771   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
772
773   typedef ::clang::CFG::const_iterator nodes_iterator;
774
775   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
776   static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
777   static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
778 };
779 } // end llvm namespace
780 #endif