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