]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
[analyzer] Add a CFG node for the allocator call in a C++ 'new' expression.
[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 "llvm/Support/raw_ostream.h"
29 #include <bitset>
30 #include <cassert>
31 #include <iterator>
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   /// Predecessors/Successors - Keep track of the predecessor / successor
416   /// CFG blocks.
417   typedef BumpVector<CFGBlock*> AdjacentBlocks;
418   AdjacentBlocks Preds;
419   AdjacentBlocks Succs;
420
421   /// NoReturn - This bit is set when the basic block contains a function call
422   /// or implicit destructor that is attributed as 'noreturn'. In that case,
423   /// control cannot technically ever proceed past this block. All such blocks
424   /// will have a single immediate successor: the exit block. This allows them
425   /// to be easily reached from the exit block and using this bit quickly
426   /// recognized without scanning the contents of the block.
427   ///
428   /// Optimization Note: This bit could be profitably folded with Terminator's
429   /// storage if the memory usage of CFGBlock becomes an issue.
430   unsigned HasNoReturnElement : 1;
431
432   /// Parent - The parent CFG that owns this CFGBlock.
433   CFG *Parent;
434
435 public:
436   explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
437     : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL), 
438       BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
439       Parent(parent) {}
440   ~CFGBlock() {}
441
442   // Statement iterators
443   typedef ElementList::iterator                      iterator;
444   typedef ElementList::const_iterator                const_iterator;
445   typedef ElementList::reverse_iterator              reverse_iterator;
446   typedef ElementList::const_reverse_iterator        const_reverse_iterator;
447
448   CFGElement                 front()       const { return Elements.front();   }
449   CFGElement                 back()        const { return Elements.back();    }
450
451   iterator                   begin()             { return Elements.begin();   }
452   iterator                   end()               { return Elements.end();     }
453   const_iterator             begin()       const { return Elements.begin();   }
454   const_iterator             end()         const { return Elements.end();     }
455
456   reverse_iterator           rbegin()            { return Elements.rbegin();  }
457   reverse_iterator           rend()              { return Elements.rend();    }
458   const_reverse_iterator     rbegin()      const { return Elements.rbegin();  }
459   const_reverse_iterator     rend()        const { return Elements.rend();    }
460
461   unsigned                   size()        const { return Elements.size();    }
462   bool                       empty()       const { return Elements.empty();   }
463
464   CFGElement operator[](size_t i) const  { return Elements[i]; }
465
466   // CFG iterators
467   typedef AdjacentBlocks::iterator                              pred_iterator;
468   typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
469   typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
470   typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
471
472   typedef AdjacentBlocks::iterator                              succ_iterator;
473   typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
474   typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
475   typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
476
477   pred_iterator                pred_begin()        { return Preds.begin();   }
478   pred_iterator                pred_end()          { return Preds.end();     }
479   const_pred_iterator          pred_begin()  const { return Preds.begin();   }
480   const_pred_iterator          pred_end()    const { return Preds.end();     }
481
482   pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
483   pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
484   const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
485   const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
486
487   succ_iterator                succ_begin()        { return Succs.begin();   }
488   succ_iterator                succ_end()          { return Succs.end();     }
489   const_succ_iterator          succ_begin()  const { return Succs.begin();   }
490   const_succ_iterator          succ_end()    const { return Succs.end();     }
491
492   succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
493   succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
494   const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
495   const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
496
497   unsigned                     succ_size()   const { return Succs.size();    }
498   bool                         succ_empty()  const { return Succs.empty();   }
499
500   unsigned                     pred_size()   const { return Preds.size();    }
501   bool                         pred_empty()  const { return Preds.empty();   }
502
503
504   class FilterOptions {
505   public:
506     FilterOptions() {
507       IgnoreDefaultsWithCoveredEnums = 0;
508     }
509
510     unsigned IgnoreDefaultsWithCoveredEnums : 1;
511   };
512
513   static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
514        const CFGBlock *Dst);
515
516   template <typename IMPL, bool IsPred>
517   class FilteredCFGBlockIterator {
518   private:
519     IMPL I, E;
520     const FilterOptions F;
521     const CFGBlock *From;
522    public:
523     explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
524               const CFGBlock *from,
525               const FilterOptions &f)
526       : I(i), E(e), F(f), From(from) {}
527
528     bool hasMore() const { return I != E; }
529
530     FilteredCFGBlockIterator &operator++() {
531       do { ++I; } while (hasMore() && Filter(*I));
532       return *this;
533     }
534
535     const CFGBlock *operator*() const { return *I; }
536   private:
537     bool Filter(const CFGBlock *To) {
538       return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
539     }
540   };
541
542   typedef FilteredCFGBlockIterator<const_pred_iterator, true>
543           filtered_pred_iterator;
544
545   typedef FilteredCFGBlockIterator<const_succ_iterator, false>
546           filtered_succ_iterator;
547
548   filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
549     return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
550   }
551
552   filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
553     return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
554   }
555
556   // Manipulation of block contents
557
558   void setTerminator(Stmt *Statement) { Terminator = Statement; }
559   void setLabel(Stmt *Statement) { Label = Statement; }
560   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
561   void setHasNoReturnElement() { HasNoReturnElement = true; }
562
563   CFGTerminator getTerminator() { return Terminator; }
564   const CFGTerminator getTerminator() const { return Terminator; }
565
566   Stmt *getTerminatorCondition();
567
568   const Stmt *getTerminatorCondition() const {
569     return const_cast<CFGBlock*>(this)->getTerminatorCondition();
570   }
571
572   const Stmt *getLoopTarget() const { return LoopTarget; }
573
574   Stmt *getLabel() { return Label; }
575   const Stmt *getLabel() const { return Label; }
576
577   bool hasNoReturnElement() const { return HasNoReturnElement; }
578
579   unsigned getBlockID() const { return BlockID; }
580
581   CFG *getParent() const { return Parent; }
582
583   void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
584   void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
585              bool ShowColors) const;
586   void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
587   void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
588     OS << "BB#" << getBlockID();
589   }
590
591   void addSuccessor(CFGBlock *Block, BumpVectorContext &C) {
592     if (Block)
593       Block->Preds.push_back(this, C);
594     Succs.push_back(Block, C);
595   }
596
597   void appendStmt(Stmt *statement, BumpVectorContext &C) {
598     Elements.push_back(CFGStmt(statement), C);
599   }
600
601   void appendInitializer(CXXCtorInitializer *initializer,
602                         BumpVectorContext &C) {
603     Elements.push_back(CFGInitializer(initializer), C);
604   }
605
606   void appendNewAllocator(CXXNewExpr *NE,
607                           BumpVectorContext &C) {
608     Elements.push_back(CFGNewAllocator(NE), C);
609   }
610
611   void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
612     Elements.push_back(CFGBaseDtor(BS), C);
613   }
614
615   void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
616     Elements.push_back(CFGMemberDtor(FD), C);
617   }
618
619   void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
620     Elements.push_back(CFGTemporaryDtor(E), C);
621   }
622
623   void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
624     Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
625   }
626
627   void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
628     Elements.push_back(CFGDeleteDtor(RD, DE), C);
629   }
630
631   // Destructors must be inserted in reversed order. So insertion is in two
632   // steps. First we prepare space for some number of elements, then we insert
633   // the elements beginning at the last position in prepared space.
634   iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
635       BumpVectorContext &C) {
636     return iterator(Elements.insert(I.base(), Cnt, CFGAutomaticObjDtor(0, 0), C));
637   }
638   iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
639     *I = CFGAutomaticObjDtor(VD, S);
640     return ++I;
641   }
642 };
643
644 /// CFG - Represents a source-level, intra-procedural CFG that represents the
645 ///  control-flow of a Stmt.  The Stmt can represent an entire function body,
646 ///  or a single expression.  A CFG will always contain one empty block that
647 ///  represents the Exit point of the CFG.  A CFG will also contain a designated
648 ///  Entry block.  The CFG solely represents control-flow; it consists of
649 ///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
650 ///  was constructed from.
651 class CFG {
652 public:
653   //===--------------------------------------------------------------------===//
654   // CFG Construction & Manipulation.
655   //===--------------------------------------------------------------------===//
656
657   class BuildOptions {
658     std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
659   public:
660     typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
661     ForcedBlkExprs **forcedBlkExprs;
662
663     bool PruneTriviallyFalseEdges;
664     bool AddEHEdges;
665     bool AddInitializers;
666     bool AddImplicitDtors;
667     bool AddTemporaryDtors;
668     bool AddStaticInitBranches;
669     bool AddCXXNewAllocator;
670
671     bool alwaysAdd(const Stmt *stmt) const {
672       return alwaysAddMask[stmt->getStmtClass()];
673     }
674
675     BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
676       alwaysAddMask[stmtClass] = val;
677       return *this;
678     }
679
680     BuildOptions &setAllAlwaysAdd() {
681       alwaysAddMask.set();
682       return *this;
683     }
684
685     BuildOptions()
686     : forcedBlkExprs(0), PruneTriviallyFalseEdges(true)
687       ,AddEHEdges(false)
688       ,AddInitializers(false)
689       ,AddImplicitDtors(false)
690       ,AddTemporaryDtors(false)
691       ,AddStaticInitBranches(false)
692       ,AddCXXNewAllocator(false) {}
693   };
694
695   /// \brief Provides a custom implementation of the iterator class to have the
696   /// same interface as Function::iterator - iterator returns CFGBlock
697   /// (not a pointer to CFGBlock).
698   class graph_iterator {
699   public:
700     typedef const CFGBlock                  value_type;
701     typedef value_type&                     reference;
702     typedef value_type*                     pointer;
703     typedef BumpVector<CFGBlock*>::iterator ImplTy;
704
705     graph_iterator(const ImplTy &i) : I(i) {}
706
707     bool operator==(const graph_iterator &X) const { return I == X.I; }
708     bool operator!=(const graph_iterator &X) const { return I != X.I; }
709
710     reference operator*()    const { return **I; }
711     pointer operator->()     const { return  *I; }
712     operator CFGBlock* ()          { return  *I; }
713
714     graph_iterator &operator++() { ++I; return *this; }
715     graph_iterator &operator--() { --I; return *this; }
716
717   private:
718     ImplTy I;
719   };
720
721   class const_graph_iterator {
722   public:
723     typedef const CFGBlock                  value_type;
724     typedef value_type&                     reference;
725     typedef value_type*                     pointer;
726     typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
727
728     const_graph_iterator(const ImplTy &i) : I(i) {}
729
730     bool operator==(const const_graph_iterator &X) const { return I == X.I; }
731     bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
732
733     reference operator*() const { return **I; }
734     pointer operator->()  const { return  *I; }
735     operator CFGBlock* () const { return  *I; }
736
737     const_graph_iterator &operator++() { ++I; return *this; }
738     const_graph_iterator &operator--() { --I; return *this; }
739
740   private:
741     ImplTy I;
742   };
743
744   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
745   ///   constructed CFG belongs to the caller.
746   static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
747                        const BuildOptions &BO);
748
749   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
750   ///  the caller should not directly free it.
751   CFGBlock *createBlock();
752
753   /// setEntry - Set the entry block of the CFG.  This is typically used
754   ///  only during CFG construction.  Most CFG clients expect that the
755   ///  entry block has no predecessors and contains no statements.
756   void setEntry(CFGBlock *B) { Entry = B; }
757
758   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
759   ///  This is typically used only during CFG construction.
760   void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
761
762   //===--------------------------------------------------------------------===//
763   // Block Iterators
764   //===--------------------------------------------------------------------===//
765
766   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;
767   typedef CFGBlockListTy::iterator                 iterator;
768   typedef CFGBlockListTy::const_iterator           const_iterator;
769   typedef std::reverse_iterator<iterator>          reverse_iterator;
770   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
771
772   CFGBlock &                front()                { return *Blocks.front(); }
773   CFGBlock &                back()                 { return *Blocks.back(); }
774
775   iterator                  begin()                { return Blocks.begin(); }
776   iterator                  end()                  { return Blocks.end(); }
777   const_iterator            begin()       const    { return Blocks.begin(); }
778   const_iterator            end()         const    { return Blocks.end(); }
779
780   graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
781   graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
782   const_graph_iterator nodes_begin() const {
783     return const_graph_iterator(Blocks.begin());
784   }
785   const_graph_iterator nodes_end() const {
786     return const_graph_iterator(Blocks.end());
787   }
788
789   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
790   reverse_iterator          rend()                 { return Blocks.rend(); }
791   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
792   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
793
794   CFGBlock &                getEntry()             { return *Entry; }
795   const CFGBlock &          getEntry()    const    { return *Entry; }
796   CFGBlock &                getExit()              { return *Exit; }
797   const CFGBlock &          getExit()     const    { return *Exit; }
798
799   CFGBlock *       getIndirectGotoBlock() { return IndirectGotoBlock; }
800   const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
801
802   typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
803   try_block_iterator try_blocks_begin() const {
804     return TryDispatchBlocks.begin();
805   }
806   try_block_iterator try_blocks_end() const {
807     return TryDispatchBlocks.end();
808   }
809
810   void addTryDispatchBlock(const CFGBlock *block) {
811     TryDispatchBlocks.push_back(block);
812   }
813
814   /// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
815   ///
816   /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
817   /// multiple decls.
818   void addSyntheticDeclStmt(const DeclStmt *Synthetic,
819                             const DeclStmt *Source) {
820     assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
821     assert(Synthetic != Source && "Don't include original DeclStmts in map");
822     assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
823     SyntheticDeclStmts[Synthetic] = Source;
824   }
825
826   typedef llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator
827     synthetic_stmt_iterator;
828
829   /// Iterates over synthetic DeclStmts in the CFG.
830   ///
831   /// Each element is a (synthetic statement, source statement) pair.
832   ///
833   /// \sa addSyntheticDeclStmt
834   synthetic_stmt_iterator synthetic_stmt_begin() const {
835     return SyntheticDeclStmts.begin();
836   }
837
838   /// \sa synthetic_stmt_begin
839   synthetic_stmt_iterator synthetic_stmt_end() const {
840     return SyntheticDeclStmts.end();
841   }
842
843   //===--------------------------------------------------------------------===//
844   // Member templates useful for various batch operations over CFGs.
845   //===--------------------------------------------------------------------===//
846
847   template <typename CALLBACK>
848   void VisitBlockStmts(CALLBACK& O) const {
849     for (const_iterator I=begin(), E=end(); I != E; ++I)
850       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
851            BI != BE; ++BI) {
852         if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
853           O(const_cast<Stmt*>(stmt->getStmt()));
854       }
855   }
856
857   //===--------------------------------------------------------------------===//
858   // CFG Introspection.
859   //===--------------------------------------------------------------------===//
860
861   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
862   /// start at 0).
863   unsigned getNumBlockIDs() const { return NumBlockIDs; }
864
865   /// size - Return the total number of CFGBlocks within the CFG
866   /// This is simply a renaming of the getNumBlockIDs(). This is necessary 
867   /// because the dominator implementation needs such an interface.
868   unsigned size() const { return NumBlockIDs; }
869
870   //===--------------------------------------------------------------------===//
871   // CFG Debugging: Pretty-Printing and Visualization.
872   //===--------------------------------------------------------------------===//
873
874   void viewCFG(const LangOptions &LO) const;
875   void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
876   void dump(const LangOptions &LO, bool ShowColors) const;
877
878   //===--------------------------------------------------------------------===//
879   // Internal: constructors and data.
880   //===--------------------------------------------------------------------===//
881
882   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
883           Blocks(BlkBVC, 10) {}
884
885   llvm::BumpPtrAllocator& getAllocator() {
886     return BlkBVC.getAllocator();
887   }
888
889   BumpVectorContext &getBumpVectorContext() {
890     return BlkBVC;
891   }
892
893 private:
894   CFGBlock *Entry;
895   CFGBlock *Exit;
896   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
897                                 // for indirect gotos
898   unsigned  NumBlockIDs;
899
900   BumpVectorContext BlkBVC;
901
902   CFGBlockListTy Blocks;
903
904   /// C++ 'try' statements are modeled with an indirect dispatch block.
905   /// This is the collection of such blocks present in the CFG.
906   std::vector<const CFGBlock *> TryDispatchBlocks;
907
908   /// Collects DeclStmts synthesized for this CFG and maps each one back to its
909   /// source DeclStmt.
910   llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
911 };
912 } // end namespace clang
913
914 //===----------------------------------------------------------------------===//
915 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
916 //===----------------------------------------------------------------------===//
917
918 namespace llvm {
919
920 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
921 /// CFGTerminator to a specific Stmt class.
922 template <> struct simplify_type< ::clang::CFGTerminator> {
923   typedef ::clang::Stmt *SimpleType;
924   static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
925     return Val.getStmt();
926   }
927 };
928
929 // Traits for: CFGBlock
930
931 template <> struct GraphTraits< ::clang::CFGBlock *> {
932   typedef ::clang::CFGBlock NodeType;
933   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
934
935   static NodeType* getEntryNode(::clang::CFGBlock *BB)
936   { return BB; }
937
938   static inline ChildIteratorType child_begin(NodeType* N)
939   { return N->succ_begin(); }
940
941   static inline ChildIteratorType child_end(NodeType* N)
942   { return N->succ_end(); }
943 };
944
945 template <> struct GraphTraits< const ::clang::CFGBlock *> {
946   typedef const ::clang::CFGBlock NodeType;
947   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
948
949   static NodeType* getEntryNode(const clang::CFGBlock *BB)
950   { return BB; }
951
952   static inline ChildIteratorType child_begin(NodeType* N)
953   { return N->succ_begin(); }
954
955   static inline ChildIteratorType child_end(NodeType* N)
956   { return N->succ_end(); }
957 };
958
959 template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
960   typedef ::clang::CFGBlock NodeType;
961   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
962
963   static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
964   { return G.Graph; }
965
966   static inline ChildIteratorType child_begin(NodeType* N)
967   { return N->pred_begin(); }
968
969   static inline ChildIteratorType child_end(NodeType* N)
970   { return N->pred_end(); }
971 };
972
973 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
974   typedef const ::clang::CFGBlock NodeType;
975   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
976
977   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
978   { return G.Graph; }
979
980   static inline ChildIteratorType child_begin(NodeType* N)
981   { return N->pred_begin(); }
982
983   static inline ChildIteratorType child_end(NodeType* N)
984   { return N->pred_end(); }
985 };
986
987 // Traits for: CFG
988
989 template <> struct GraphTraits< ::clang::CFG* >
990     : public GraphTraits< ::clang::CFGBlock *>  {
991
992   typedef ::clang::CFG::graph_iterator nodes_iterator;
993
994   static NodeType     *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
995   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
996   static nodes_iterator   nodes_end(::clang::CFG* F) { return F->nodes_end(); }
997   static unsigned              size(::clang::CFG* F) { return F->size(); }
998 };
999
1000 template <> struct GraphTraits<const ::clang::CFG* >
1001     : public GraphTraits<const ::clang::CFGBlock *>  {
1002
1003   typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1004
1005   static NodeType *getEntryNode( const ::clang::CFG* F) {
1006     return &F->getEntry();
1007   }
1008   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
1009     return F->nodes_begin();
1010   }
1011   static nodes_iterator nodes_end( const ::clang::CFG* F) {
1012     return F->nodes_end();
1013   }
1014   static unsigned size(const ::clang::CFG* F) {
1015     return F->size();
1016   }
1017 };
1018
1019 template <> struct GraphTraits<Inverse< ::clang::CFG*> >
1020   : public GraphTraits<Inverse< ::clang::CFGBlock*> > {
1021
1022   typedef ::clang::CFG::graph_iterator nodes_iterator;
1023
1024   static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
1025   static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
1026   static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
1027 };
1028
1029 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
1030   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
1031
1032   typedef ::clang::CFG::const_graph_iterator nodes_iterator;
1033
1034   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
1035   static nodes_iterator nodes_begin(const ::clang::CFG* F) {
1036     return F->nodes_begin();
1037   }
1038   static nodes_iterator nodes_end(const ::clang::CFG* F) {
1039     return F->nodes_end();
1040   }
1041 };
1042 } // end llvm namespace
1043 #endif