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