]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
Remove the CFGElement "Invalid" state.
[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 "clang/AST/Stmt.h"
19 #include "clang/Analysis/Support/BumpVector.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/GraphTraits.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/PointerIntPair.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Casting.h"
28 #include <bitset>
29 #include <cassert>
30 #include <iterator>
31
32 namespace clang {
33   class CXXDestructorDecl;
34   class Decl;
35   class Stmt;
36   class Expr;
37   class FieldDecl;
38   class VarDecl;
39   class CXXCtorInitializer;
40   class CXXBaseSpecifier;
41   class CXXBindTemporaryExpr;
42   class CFG;
43   class PrinterHelper;
44   class LangOptions;
45   class ASTContext;
46
47 /// CFGElement - Represents a top-level expression in a basic block.
48 class CFGElement {
49 public:
50   enum Kind {
51     // main kind
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   CFGElement() {}
73 public:
74
75   /// \brief Convert to the specified CFGElement type, asserting that this
76   /// CFGElement is of the desired type.
77   template<typename T>
78   T castAs() const {
79     assert(T::isKind(*this));
80     T t;
81     CFGElement& e = t;
82     e = *this;
83     return t;
84   }
85
86   /// \brief Convert to the specified CFGElement type, returning None if this
87   /// CFGElement is not of the desired type.
88   template<typename T>
89   Optional<T> getAs() const {
90     if (!T::isKind(*this))
91       return None;
92     T t;
93     CFGElement& e = t;
94     e = *this;
95     return t;
96   }
97
98   Kind getKind() const {
99     unsigned x = Data2.getInt();
100     x <<= 2;
101     x |= Data1.getInt();
102     return (Kind) x;
103   }
104 };
105
106 class CFGStmt : public CFGElement {
107 public:
108   CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
109
110   const Stmt *getStmt() const {
111     return static_cast<const Stmt *>(Data1.getPointer());
112   }
113
114 private:
115   friend class CFGElement;
116   CFGStmt() {}
117   static bool isKind(const CFGElement &E) {
118     return E.getKind() == Statement;
119   }
120 };
121
122 /// CFGInitializer - Represents C++ base or member initializer from
123 /// constructor's initialization list.
124 class CFGInitializer : public CFGElement {
125 public:
126   CFGInitializer(CXXCtorInitializer *initializer)
127       : CFGElement(Initializer, initializer) {}
128
129   CXXCtorInitializer* getInitializer() const {
130     return static_cast<CXXCtorInitializer*>(Data1.getPointer());
131   }
132
133 private:
134   friend class CFGElement;
135   CFGInitializer() {}
136   static bool isKind(const CFGElement &E) {
137     return E.getKind() == Initializer;
138   }
139 };
140
141 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
142 /// by compiler on various occasions.
143 class CFGImplicitDtor : public CFGElement {
144 protected:
145   CFGImplicitDtor() {}
146   CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = 0)
147     : CFGElement(kind, data1, data2) {
148     assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
149   }
150
151 public:
152   const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
153   bool isNoReturn(ASTContext &astContext) const;
154
155 private:
156   friend class CFGElement;
157   static bool isKind(const CFGElement &E) {
158     Kind kind = E.getKind();
159     return kind >= DTOR_BEGIN && kind <= DTOR_END;
160   }
161 };
162
163 /// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
164 /// for automatic object or temporary bound to const reference at the point
165 /// of leaving its local scope.
166 class CFGAutomaticObjDtor: public CFGImplicitDtor {
167 public:
168   CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
169       : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
170
171   const VarDecl *getVarDecl() const {
172     return static_cast<VarDecl*>(Data1.getPointer());
173   }
174
175   // Get statement end of which triggered the destructor call.
176   const Stmt *getTriggerStmt() const {
177     return static_cast<Stmt*>(Data2.getPointer());
178   }
179
180 private:
181   friend class CFGElement;
182   CFGAutomaticObjDtor() {}
183   static bool isKind(const CFGElement &elem) {
184     return elem.getKind() == AutomaticObjectDtor;
185   }
186 };
187
188 /// CFGBaseDtor - Represents C++ object destructor implicitly generated for
189 /// base object in destructor.
190 class CFGBaseDtor : public CFGImplicitDtor {
191 public:
192   CFGBaseDtor(const CXXBaseSpecifier *base)
193       : CFGImplicitDtor(BaseDtor, base) {}
194
195   const CXXBaseSpecifier *getBaseSpecifier() const {
196     return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
197   }
198
199 private:
200   friend class CFGElement;
201   CFGBaseDtor() {}
202   static bool isKind(const CFGElement &E) {
203     return E.getKind() == BaseDtor;
204   }
205 };
206
207 /// CFGMemberDtor - Represents C++ object destructor implicitly generated for
208 /// member object in destructor.
209 class CFGMemberDtor : public CFGImplicitDtor {
210 public:
211   CFGMemberDtor(const FieldDecl *field)
212       : CFGImplicitDtor(MemberDtor, field, 0) {}
213
214   const FieldDecl *getFieldDecl() const {
215     return static_cast<const FieldDecl*>(Data1.getPointer());
216   }
217
218 private:
219   friend class CFGElement;
220   CFGMemberDtor() {}
221   static bool isKind(const CFGElement &E) {
222     return E.getKind() == MemberDtor;
223   }
224 };
225
226 /// CFGTemporaryDtor - Represents C++ object destructor implicitly generated
227 /// at the end of full expression for temporary object.
228 class CFGTemporaryDtor : public CFGImplicitDtor {
229 public:
230   CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
231       : CFGImplicitDtor(TemporaryDtor, expr, 0) {}
232
233   const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
234     return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
235   }
236
237 private:
238   friend class CFGElement;
239   CFGTemporaryDtor() {}
240   static bool isKind(const CFGElement &E) {
241     return E.getKind() == TemporaryDtor;
242   }
243 };
244
245 /// CFGTerminator - Represents CFGBlock terminator statement.
246 ///
247 /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
248 /// in control flow of destructors of temporaries. In this case terminator
249 /// statement is the same statement that branches control flow in evaluation
250 /// of matching full expression.
251 class CFGTerminator {
252   llvm::PointerIntPair<Stmt *, 1> Data;
253 public:
254   CFGTerminator() {}
255   CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
256       : Data(S, TemporaryDtorsBranch) {}
257
258   Stmt *getStmt() { return Data.getPointer(); }
259   const Stmt *getStmt() const { return Data.getPointer(); }
260
261   bool isTemporaryDtorsBranch() const { return Data.getInt(); }
262
263   operator Stmt *() { return getStmt(); }
264   operator const Stmt *() const { return getStmt(); }
265
266   Stmt *operator->() { return getStmt(); }
267   const Stmt *operator->() const { return getStmt(); }
268
269   Stmt &operator*() { return *getStmt(); }
270   const Stmt &operator*() const { return *getStmt(); }
271
272   operator bool() const { return getStmt(); }
273 };
274
275 /// CFGBlock - Represents a single basic block in a source-level CFG.
276 ///  It consists of:
277 ///
278 ///  (1) A set of statements/expressions (which may contain subexpressions).
279 ///  (2) A "terminator" statement (not in the set of statements).
280 ///  (3) A list of successors and predecessors.
281 ///
282 /// Terminator: The terminator represents the type of control-flow that occurs
283 /// at the end of the basic block.  The terminator is a Stmt* referring to an
284 /// AST node that has control-flow: if-statements, breaks, loops, etc.
285 /// If the control-flow is conditional, the condition expression will appear
286 /// within the set of statements in the block (usually the last statement).
287 ///
288 /// Predecessors: the order in the set of predecessors is arbitrary.
289 ///
290 /// Successors: the order in the set of successors is NOT arbitrary.  We
291 ///  currently have the following orderings based on the terminator:
292 ///
293 ///     Terminator       Successor Ordering
294 ///  -----------------------------------------------------
295 ///       if            Then Block;  Else Block
296 ///     ? operator      LHS expression;  RHS expression
297 ///     &&, ||          expression that uses result of && or ||, RHS
298 ///
299 /// But note that any of that may be NULL in case of optimized-out edges.
300 ///
301 class CFGBlock {
302   class ElementList {
303     typedef BumpVector<CFGElement> ImplTy;
304     ImplTy Impl;
305   public:
306     ElementList(BumpVectorContext &C) : Impl(C, 4) {}
307
308     typedef std::reverse_iterator<ImplTy::iterator>       iterator;
309     typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
310     typedef ImplTy::iterator                              reverse_iterator;
311     typedef ImplTy::const_iterator                       const_reverse_iterator;
312     typedef ImplTy::const_reference                       const_reference;
313
314     void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
315     reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
316         BumpVectorContext &C) {
317       return Impl.insert(I, Cnt, E, C);
318     }
319
320     const_reference front() const { return Impl.back(); }
321     const_reference back() const { return Impl.front(); }
322
323     iterator begin() { return Impl.rbegin(); }
324     iterator end() { return Impl.rend(); }
325     const_iterator begin() const { return Impl.rbegin(); }
326     const_iterator end() const { return Impl.rend(); }
327     reverse_iterator rbegin() { return Impl.begin(); }
328     reverse_iterator rend() { return Impl.end(); }
329     const_reverse_iterator rbegin() const { return Impl.begin(); }
330     const_reverse_iterator rend() const { return Impl.end(); }
331
332    CFGElement operator[](size_t i) const  {
333      assert(i < Impl.size());
334      return Impl[Impl.size() - 1 - i];
335    }
336
337     size_t size() const { return Impl.size(); }
338     bool empty() const { return Impl.empty(); }
339   };
340
341   /// Stmts - The set of statements in the basic block.
342   ElementList Elements;
343
344   /// Label - An (optional) label that prefixes the executable
345   ///  statements in the block.  When this variable is non-NULL, it is
346   ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
347   Stmt *Label;
348
349   /// Terminator - The terminator for a basic block that
350   ///  indicates the type of control-flow that occurs between a block
351   ///  and its successors.
352   CFGTerminator Terminator;
353
354   /// LoopTarget - Some blocks are used to represent the "loop edge" to
355   ///  the start of a loop from within the loop body.  This Stmt* will be
356   ///  refer to the loop statement for such blocks (and be null otherwise).
357   const Stmt *LoopTarget;
358
359   /// BlockID - A numerical ID assigned to a CFGBlock during construction
360   ///   of the CFG.
361   unsigned BlockID;
362
363   /// Predecessors/Successors - Keep track of the predecessor / successor
364   /// CFG blocks.
365   typedef BumpVector<CFGBlock*> AdjacentBlocks;
366   AdjacentBlocks Preds;
367   AdjacentBlocks Succs;
368
369   /// NoReturn - This bit is set when the basic block contains a function call
370   /// or implicit destructor that is attributed as 'noreturn'. In that case,
371   /// control cannot technically ever proceed past this block. All such blocks
372   /// will have a single immediate successor: the exit block. This allows them
373   /// to be easily reached from the exit block and using this bit quickly
374   /// recognized without scanning the contents of the block.
375   ///
376   /// Optimization Note: This bit could be profitably folded with Terminator's
377   /// storage if the memory usage of CFGBlock becomes an issue.
378   unsigned HasNoReturnElement : 1;
379
380   /// Parent - The parent CFG that owns this CFGBlock.
381   CFG *Parent;
382
383 public:
384   explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
385     : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL), 
386       BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
387       Parent(parent) {}
388   ~CFGBlock() {}
389
390   // Statement iterators
391   typedef ElementList::iterator                      iterator;
392   typedef ElementList::const_iterator                const_iterator;
393   typedef ElementList::reverse_iterator              reverse_iterator;
394   typedef ElementList::const_reverse_iterator        const_reverse_iterator;
395
396   CFGElement                 front()       const { return Elements.front();   }
397   CFGElement                 back()        const { return Elements.back();    }
398
399   iterator                   begin()             { return Elements.begin();   }
400   iterator                   end()               { return Elements.end();     }
401   const_iterator             begin()       const { return Elements.begin();   }
402   const_iterator             end()         const { return Elements.end();     }
403
404   reverse_iterator           rbegin()            { return Elements.rbegin();  }
405   reverse_iterator           rend()              { return Elements.rend();    }
406   const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
407   const_reverse_iterator     rend()        const { return Elements.rend();    }
408
409   unsigned                   size()        const { return Elements.size();    }
410   bool                       empty()       const { return Elements.empty();   }
411
412   CFGElement operator[](size_t i) const  { return Elements[i]; }
413
414   // CFG iterators
415   typedef AdjacentBlocks::iterator                              pred_iterator;
416   typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
417   typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
418   typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
419
420   typedef AdjacentBlocks::iterator                              succ_iterator;
421   typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
422   typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
423   typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
424
425   pred_iterator                pred_begin()        { return Preds.begin();   }
426   pred_iterator                pred_end()          { return Preds.end();     }
427   const_pred_iterator          pred_begin()  const { return Preds.begin();   }
428   const_pred_iterator          pred_end()    const { return Preds.end();     }
429
430   pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
431   pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
432   const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
433   const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
434
435   succ_iterator                succ_begin()        { return Succs.begin();   }
436   succ_iterator                succ_end()          { return Succs.end();     }
437   const_succ_iterator          succ_begin()  const { return Succs.begin();   }
438   const_succ_iterator          succ_end()    const { return Succs.end();     }
439
440   succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
441   succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
442   const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
443   const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
444
445   unsigned                     succ_size()   const { return Succs.size();    }
446   bool                         succ_empty()  const { return Succs.empty();   }
447
448   unsigned                     pred_size()   const { return Preds.size();    }
449   bool                         pred_empty()  const { return Preds.empty();   }
450
451
452   class FilterOptions {
453   public:
454     FilterOptions() {
455       IgnoreDefaultsWithCoveredEnums = 0;
456     }
457
458     unsigned IgnoreDefaultsWithCoveredEnums : 1;
459   };
460
461   static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
462        const CFGBlock *Dst);
463
464   template <typename IMPL, bool IsPred>
465   class FilteredCFGBlockIterator {
466   private:
467     IMPL I, E;
468     const FilterOptions F;
469     const CFGBlock *From;
470    public:
471     explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
472               const CFGBlock *from,
473               const FilterOptions &f)
474       : I(i), E(e), F(f), From(from) {}
475
476     bool hasMore() const { return I != E; }
477
478     FilteredCFGBlockIterator &operator++() {
479       do { ++I; } while (hasMore() && Filter(*I));
480       return *this;
481     }
482
483     const CFGBlock *operator*() const { return *I; }
484   private:
485     bool Filter(const CFGBlock *To) {
486       return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
487     }
488   };
489
490   typedef FilteredCFGBlockIterator<const_pred_iterator, true>
491           filtered_pred_iterator;
492
493   typedef FilteredCFGBlockIterator<const_succ_iterator, false>
494           filtered_succ_iterator;
495
496   filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
497     return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
498   }
499
500   filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
501     return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
502   }
503
504   // Manipulation of block contents
505
506   void setTerminator(Stmt *Statement) { Terminator = Statement; }
507   void setLabel(Stmt *Statement) { Label = Statement; }
508   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
509   void setHasNoReturnElement() { HasNoReturnElement = true; }
510
511   CFGTerminator getTerminator() { return Terminator; }
512   const CFGTerminator getTerminator() const { return Terminator; }
513
514   Stmt *getTerminatorCondition();
515
516   const Stmt *getTerminatorCondition() const {
517     return const_cast<CFGBlock*>(this)->getTerminatorCondition();
518   }
519
520   const Stmt *getLoopTarget() const { return LoopTarget; }
521
522   Stmt *getLabel() { return Label; }
523   const Stmt *getLabel() const { return Label; }
524
525   bool hasNoReturnElement() const { return HasNoReturnElement; }
526
527   unsigned getBlockID() const { return BlockID; }
528
529   CFG *getParent() const { return Parent; }
530
531   void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
532   void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
533              bool ShowColors) const;
534   void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
535
536   void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
537     if (Block)
538       Block->Preds.push_back(this, C);
539     Succs.push_back(Block, C);
540   }
541
542   void appendStmt(Stmt *statement, BumpVectorContext &C) {
543     Elements.push_back(CFGStmt(statement), C);
544   }
545
546   void appendInitializer(CXXCtorInitializer *initializer,
547                         BumpVectorContext &C) {
548     Elements.push_back(CFGInitializer(initializer), C);
549   }
550
551   void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
552     Elements.push_back(CFGBaseDtor(BS), C);
553   }
554
555   void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
556     Elements.push_back(CFGMemberDtor(FD), C);
557   }
558
559   void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
560     Elements.push_back(CFGTemporaryDtor(E), C);
561   }
562
563   void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
564     Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
565   }
566
567   // Destructors must be inserted in reversed order. So insertion is in two
568   // steps. First we prepare space for some number of elements, then we insert
569   // the elements beginning at the last position in prepared space.
570   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
571       BumpVectorContext &C) {
572     return iterator(Elements.insert(I.base(), Cnt, CFGAutomaticObjDtor(0, 0), C));
573   }
574   iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
575     *I = CFGAutomaticObjDtor(VD, S);
576     return ++I;
577   }
578 };
579
580 /// CFG - Represents a source-level, intra-procedural CFG that represents the
581 ///  control-flow of a Stmt.  The Stmt can represent an entire function body,
582 ///  or a single expression.  A CFG will always contain one empty block that
583 ///  represents the Exit point of the CFG.  A CFG will also contain a designated
584 ///  Entry block.  The CFG solely represents control-flow; it consists of
585 ///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
586 ///  was constructed from.
587 class CFG {
588 public:
589   //===--------------------------------------------------------------------===//
590   // CFG Construction & Manipulation.
591   //===--------------------------------------------------------------------===//
592
593   class BuildOptions {
594     std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
595   public:
596     typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
597     ForcedBlkExprs **forcedBlkExprs;
598
599     bool PruneTriviallyFalseEdges;
600     bool AddEHEdges;
601     bool AddInitializers;
602     bool AddImplicitDtors;
603     bool AddTemporaryDtors;
604
605     bool alwaysAdd(const Stmt *stmt) const {
606       return alwaysAddMask[stmt->getStmtClass()];
607     }
608
609     BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
610       alwaysAddMask[stmtClass] = val;
611       return *this;
612     }
613
614     BuildOptions &setAllAlwaysAdd() {
615       alwaysAddMask.set();
616       return *this;
617     }
618
619     BuildOptions()
620     : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
621       ,AddEHEdges(false)
622       ,AddInitializers(false)
623       ,AddImplicitDtors(false)
624       ,AddTemporaryDtors(false) {}
625   };
626
627   /// \brief Provides a custom implementation of the iterator class to have the
628   /// same interface as Function::iterator - iterator returns CFGBlock
629   /// (not a pointer to CFGBlock).
630   class graph_iterator {
631   public:
632     typedef const CFGBlock                  value_type;
633     typedef value_type&                     reference;
634     typedef value_type*                     pointer;
635     typedef BumpVector<CFGBlock*>::iterator ImplTy;
636
637     graph_iterator(const ImplTy &i) : I(i) {}
638
639     bool operator==(const graph_iterator &X) const { return I == X.I; }
640     bool operator!=(const graph_iterator &X) const { return I != X.I; }
641
642     reference operator*()    const { return **I; }
643     pointer operator->()     const { return  *I; }
644     operator CFGBlock* ()          { return  *I; }
645
646     graph_iterator &operator++() { ++I; return *this; }
647     graph_iterator &operator--() { --I; return *this; }
648
649   private:
650     ImplTy I;
651   };
652
653   class const_graph_iterator {
654   public:
655     typedef const CFGBlock                  value_type;
656     typedef value_type&                     reference;
657     typedef value_type*                     pointer;
658     typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
659
660     const_graph_iterator(const ImplTy &i) : I(i) {}
661
662     bool operator==(const const_graph_iterator &X) const { return I == X.I; }
663     bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
664
665     reference operator*() const { return **I; }
666     pointer operator->()  const { return  *I; }
667     operator CFGBlock* () const { return  *I; }
668
669     const_graph_iterator &operator++() { ++I; return *this; }
670     const_graph_iterator &operator--() { --I; return *this; }
671
672   private:
673     ImplTy I;
674   };
675
676   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
677   ///   constructed CFG belongs to the caller.
678   static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
679                        const BuildOptions &BO);
680
681   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
682   ///  the caller should not directly free it.
683   CFGBlock *createBlock();
684
685   /// setEntry - Set the entry block of the CFG.  This is typically used
686   ///  only during CFG construction.  Most CFG clients expect that the
687   ///  entry block has no predecessors and contains no statements.
688   void setEntry(CFGBlock *B) { Entry = B; }
689
690   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
691   ///  This is typically used only during CFG construction.
692   void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
693
694   //===--------------------------------------------------------------------===//
695   // Block Iterators
696   //===--------------------------------------------------------------------===//
697
698   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;
699   typedef CFGBlockListTy::iterator                 iterator;
700   typedef CFGBlockListTy::const_iterator           const_iterator;
701   typedef std::reverse_iterator<iterator>          reverse_iterator;
702   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
703
704   CFGBlock &                front()                { return *Blocks.front(); }
705   CFGBlock &                back()                 { return *Blocks.back(); }
706
707   iterator                  begin()                { return Blocks.begin(); }
708   iterator                  end()                  { return Blocks.end(); }
709   const_iterator            begin()       const    { return Blocks.begin(); }
710   const_iterator            end()         const    { return Blocks.end(); }
711
712   graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
713   graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
714   const_graph_iterator nodes_begin() const {
715     return const_graph_iterator(Blocks.begin());
716   }
717   const_graph_iterator nodes_end() const {
718     return const_graph_iterator(Blocks.end());
719   }
720
721   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
722   reverse_iterator          rend()                 { return Blocks.rend(); }
723   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
724   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
725
726   CFGBlock &                getEntry()             { return *Entry; }
727   const CFGBlock &          getEntry()    const    { return *Entry; }
728   CFGBlock &                getExit()              { return *Exit; }
729   const CFGBlock &          getExit()     const    { return *Exit; }
730
731   CFGBlock *       getIndirectGotoBlock() { return IndirectGotoBlock; }
732   const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
733
734   typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
735   try_block_iterator try_blocks_begin() const {
736     return TryDispatchBlocks.begin();
737   }
738   try_block_iterator try_blocks_end() const {
739     return TryDispatchBlocks.end();
740   }
741
742   void addTryDispatchBlock(const CFGBlock *block) {
743     TryDispatchBlocks.push_back(block);
744   }
745
746   //===--------------------------------------------------------------------===//
747   // Member templates useful for various batch operations over CFGs.
748   //===--------------------------------------------------------------------===//
749
750   template <typename CALLBACK>
751   void VisitBlockStmts(CALLBACK& O) const {
752     for (const_iterator I=begin(), E=end(); I != E; ++I)
753       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
754            BI != BE; ++BI) {
755         if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
756           O(const_cast<Stmt*>(stmt->getStmt()));
757       }
758   }
759
760   //===--------------------------------------------------------------------===//
761   // CFG Introspection.
762   //===--------------------------------------------------------------------===//
763
764   struct   BlkExprNumTy {
765     const signed Idx;
766     explicit BlkExprNumTy(signed idx) : Idx(idx) {}
767     explicit BlkExprNumTy() : Idx(-1) {}
768     operator bool() const { return Idx >= 0; }
769     operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
770   };
771
772   bool isBlkExpr(const Stmt *S) { return getBlkExprNum(S); }
773   bool isBlkExpr(const Stmt *S) const {
774     return const_cast<CFG*>(this)->isBlkExpr(S);
775   }
776   BlkExprNumTy  getBlkExprNum(const Stmt *S);
777   unsigned      getNumBlkExprs();
778
779   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
780   /// start at 0).
781   unsigned getNumBlockIDs() const { return NumBlockIDs; }
782
783   /// size - Return the total number of CFGBlocks within the CFG
784   /// This is simply a renaming of the getNumBlockIDs(). This is necessary 
785   /// because the dominator implementation needs such an interface.
786   unsigned size() const { return NumBlockIDs; }
787
788   //===--------------------------------------------------------------------===//
789   // CFG Debugging: Pretty-Printing and Visualization.
790   //===--------------------------------------------------------------------===//
791
792   void viewCFG(const LangOptions &LO) const;
793   void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
794   void dump(const LangOptions &LO, bool ShowColors) const;
795
796   //===--------------------------------------------------------------------===//
797   // Internal: constructors and data.
798   //===--------------------------------------------------------------------===//
799
800   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
801           BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
802
803   ~CFG();
804
805   llvm::BumpPtrAllocator& getAllocator() {
806     return BlkBVC.getAllocator();
807   }
808
809   BumpVectorContext &getBumpVectorContext() {
810     return BlkBVC;
811   }
812
813 private:
814   CFGBlock *Entry;
815   CFGBlock *Exit;
816   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
817                                 // for indirect gotos
818   unsigned  NumBlockIDs;
819
820   // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
821   //  It represents a map from Expr* to integers to record the set of
822   //  block-level expressions and their "statement number" in the CFG.
823   void *    BlkExprMap;
824
825   BumpVectorContext BlkBVC;
826
827   CFGBlockListTy Blocks;
828
829   /// C++ 'try' statements are modeled with an indirect dispatch block.
830   /// This is the collection of such blocks present in the CFG.
831   std::vector<const CFGBlock *> TryDispatchBlocks;
832
833 };
834 } // end namespace clang
835
836 //===----------------------------------------------------------------------===//
837 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
838 //===----------------------------------------------------------------------===//
839
840 namespace llvm {
841
842 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
843 /// CFGTerminator to a specific Stmt class.
844 template <> struct simplify_type<const ::clang::CFGTerminator> {
845   typedef const ::clang::Stmt *SimpleType;
846   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
847     return Val.getStmt();
848   }
849 };
850
851 template <> struct simplify_type< ::clang::CFGTerminator> {
852   typedef ::clang::Stmt *SimpleType;
853   static SimpleType getSimplifiedValue(const ::clang::CFGTerminator &Val) {
854     return const_cast<SimpleType>(Val.getStmt());
855   }
856 };
857
858 // Traits for: CFGBlock
859
860 template <> struct GraphTraits< ::clang::CFGBlock *> {
861   typedef ::clang::CFGBlock NodeType;
862   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
863
864   static NodeType* getEntryNode(::clang::CFGBlock *BB)
865   { return BB; }
866
867   static inline ChildIteratorType child_begin(NodeType* N)
868   { return N->succ_begin(); }
869
870   static inline ChildIteratorType child_end(NodeType* N)
871   { return N->succ_end(); }
872 };
873
874 template <> struct GraphTraits< const ::clang::CFGBlock *> {
875   typedef const ::clang::CFGBlock NodeType;
876   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
877
878   static NodeType* getEntryNode(const clang::CFGBlock *BB)
879   { return BB; }
880
881   static inline ChildIteratorType child_begin(NodeType* N)
882   { return N->succ_begin(); }
883
884   static inline ChildIteratorType child_end(NodeType* N)
885   { return N->succ_end(); }
886 };
887
888 template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
889   typedef ::clang::CFGBlock NodeType;
890   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
891
892   static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
893   { return G.Graph; }
894
895   static inline ChildIteratorType child_begin(NodeType* N)
896   { return N->pred_begin(); }
897
898   static inline ChildIteratorType child_end(NodeType* N)
899   { return N->pred_end(); }
900 };
901
902 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
903   typedef const ::clang::CFGBlock NodeType;
904   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
905
906   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
907   { return G.Graph; }
908
909   static inline ChildIteratorType child_begin(NodeType* N)
910   { return N->pred_begin(); }
911
912   static inline ChildIteratorType child_end(NodeType* N)
913   { return N->pred_end(); }
914 };
915
916 // Traits for: CFG
917
918 template <> struct GraphTraits< ::clang::CFG* >
919     : public GraphTraits< ::clang::CFGBlock *>  {
920
921   typedef ::clang::CFG::graph_iterator nodes_iterator;
922
923   static NodeType     *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
924   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
925   static nodes_iterator   nodes_end(::clang::CFG* F) { return F->nodes_end(); }
926   static unsigned              size(::clang::CFG* F) { return F->size(); }
927 };
928
929 template <> struct GraphTraits<const ::clang::CFG* >
930     : public GraphTraits<const ::clang::CFGBlock *>  {
931
932   typedef ::clang::CFG::const_graph_iterator nodes_iterator;
933
934   static NodeType *getEntryNode( const ::clang::CFG* F) {
935     return &F->getEntry();
936   }
937   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
938     return F->nodes_begin();
939   }
940   static nodes_iterator nodes_end( const ::clang::CFG* F) {
941     return F->nodes_end();
942   }
943   static unsigned size(const ::clang::CFG* F) {
944     return F->size();
945   }
946 };
947
948 template <> struct GraphTraits<Inverse< ::clang::CFG*> >
949   : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
950
951   typedef ::clang::CFG::graph_iterator nodes_iterator;
952
953   static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
954   static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
955   static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
956 };
957
958 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
959   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
960
961   typedef ::clang::CFG::const_graph_iterator nodes_iterator;
962
963   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
964   static nodes_iterator nodes_begin(const ::clang::CFG* F) {
965     return F->nodes_begin();
966   }
967   static nodes_iterator nodes_end(const ::clang::CFG* F) {
968     return F->nodes_end();
969   }
970 };
971 } // end llvm namespace
972 #endif