]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
Add CFG::BuildOptions class to pass in CFG builder options under on parameter. Patch...
[clang] / include / clang / Analysis / CFG.h
1 //===--- CFG.h - Classes for representing and building CFGs------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the CFG and CFGBuilder classes for representing and
11 //  building Control-Flow Graphs (CFGs) from ASTs.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_CFG_H
16 #define LLVM_CLANG_CFG_H
17
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Casting.h"
22 #include "clang/Analysis/Support/BumpVector.h"
23 #include "clang/Basic/SourceLocation.h"
24 #include <cassert>
25
26 namespace llvm {
27   class raw_ostream;
28 }
29 namespace clang {
30   class Decl;
31   class Stmt;
32   class Expr;
33   class CFG;
34   class PrinterHelper;
35   class LangOptions;
36   class ASTContext;
37
38 /// CFGElement - Represents a top-level expression in a basic block.
39 class CFGElement {
40   llvm::PointerIntPair<Stmt *, 2> Data;
41 public:
42   enum Type { StartScope, EndScope };
43   explicit CFGElement() {}
44   CFGElement(Stmt *S, bool lvalue) : Data(S, lvalue ? 1 : 0) {}
45   CFGElement(Stmt *S, Type t) : Data(S, t == StartScope ? 2 : 3) {}
46   Stmt *getStmt() const { return Data.getPointer(); }
47   bool asLValue() const { return Data.getInt() == 1; }
48   bool asStartScope() const { return Data.getInt() == 2; }
49   bool asEndScope() const { return Data.getInt() == 3; }
50   bool asDtor() const { return Data.getInt() == 4; }
51   operator Stmt*() const { return getStmt(); }
52   operator bool() const { return getStmt() != 0; }
53 };
54
55 /// CFGBlock - Represents a single basic block in a source-level CFG.
56 ///  It consists of:
57 ///
58 ///  (1) A set of statements/expressions (which may contain subexpressions).
59 ///  (2) A "terminator" statement (not in the set of statements).
60 ///  (3) A list of successors and predecessors.
61 ///
62 /// Terminator: The terminator represents the type of control-flow that occurs
63 /// at the end of the basic block.  The terminator is a Stmt* referring to an
64 /// AST node that has control-flow: if-statements, breaks, loops, etc.
65 /// If the control-flow is conditional, the condition expression will appear
66 /// within the set of statements in the block (usually the last statement).
67 ///
68 /// Predecessors: the order in the set of predecessors is arbitrary.
69 ///
70 /// Successors: the order in the set of successors is NOT arbitrary.  We
71 ///  currently have the following orderings based on the terminator:
72 ///
73 ///     Terminator       Successor Ordering
74 ///  -----------------------------------------------------
75 ///       if            Then Block;  Else Block
76 ///     ? operator      LHS expression;  RHS expression
77 ///     &&, ||          expression that uses result of && or ||, RHS
78 ///
79 class CFGBlock {
80   class StatementList {
81     typedef BumpVector<CFGElement> ImplTy;
82     ImplTy Impl;
83   public:
84     StatementList(BumpVectorContext &C) : Impl(C, 4) {}
85     
86     typedef std::reverse_iterator<ImplTy::iterator>       iterator;
87     typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
88     typedef ImplTy::iterator                              reverse_iterator;
89     typedef ImplTy::const_iterator                        const_reverse_iterator;
90   
91     void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
92     CFGElement front() const { return Impl.back(); }
93     CFGElement back() const { return Impl.front(); }
94     
95     iterator begin() { return Impl.rbegin(); }
96     iterator end() { return Impl.rend(); }
97     const_iterator begin() const { return Impl.rbegin(); }
98     const_iterator end() const { return Impl.rend(); }
99     reverse_iterator rbegin() { return Impl.begin(); }
100     reverse_iterator rend() { return Impl.end(); }
101     const_reverse_iterator rbegin() const { return Impl.begin(); }
102     const_reverse_iterator rend() const { return Impl.end(); }
103
104    CFGElement operator[](size_t i) const  {
105      assert(i < Impl.size());
106      return Impl[Impl.size() - 1 - i];
107    }
108     
109     size_t size() const { return Impl.size(); }
110     bool empty() const { return Impl.empty(); }
111   };
112
113   /// Stmts - The set of statements in the basic block.
114   StatementList Stmts;
115
116   /// Label - An (optional) label that prefixes the executable
117   ///  statements in the block.  When this variable is non-NULL, it is
118   ///  either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
119   Stmt *Label;
120
121   /// Terminator - The terminator for a basic block that
122   ///  indicates the type of control-flow that occurs between a block
123   ///  and its successors.
124   Stmt *Terminator;
125
126   /// LoopTarget - Some blocks are used to represent the "loop edge" to
127   ///  the start of a loop from within the loop body.  This Stmt* will be
128   ///  refer to the loop statement for such blocks (and be null otherwise).
129   const Stmt *LoopTarget;
130
131   /// BlockID - A numerical ID assigned to a CFGBlock during construction
132   ///   of the CFG.
133   unsigned BlockID;
134
135   /// Predecessors/Successors - Keep track of the predecessor / successor
136   /// CFG blocks.
137   typedef BumpVector<CFGBlock*> AdjacentBlocks;
138   AdjacentBlocks Preds;
139   AdjacentBlocks Succs;
140
141 public:
142   explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
143     : Stmts(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
144       BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
145   ~CFGBlock() {}
146
147   // Statement iterators
148   typedef StatementList::iterator                      iterator;
149   typedef StatementList::const_iterator                const_iterator;
150   typedef StatementList::reverse_iterator              reverse_iterator;
151   typedef StatementList::const_reverse_iterator        const_reverse_iterator;
152
153   CFGElement                   front()       const { return Stmts.front();   }
154   CFGElement                   back()        const { return Stmts.back();    }
155
156   iterator                     begin()             { return Stmts.begin();   }
157   iterator                     end()               { return Stmts.end();     }
158   const_iterator               begin()       const { return Stmts.begin();   }
159   const_iterator               end()         const { return Stmts.end();     }
160
161   reverse_iterator             rbegin()            { return Stmts.rbegin();  }
162   reverse_iterator             rend()              { return Stmts.rend();    }
163   const_reverse_iterator       rbegin()      const { return Stmts.rbegin();  }
164   const_reverse_iterator       rend()        const { return Stmts.rend();    }
165
166   unsigned                     size()        const { return Stmts.size();    }
167   bool                         empty()       const { return Stmts.empty();   }
168
169   CFGElement operator[](size_t i) const  { return Stmts[i]; }
170
171   // CFG iterators
172   typedef AdjacentBlocks::iterator                              pred_iterator;
173   typedef AdjacentBlocks::const_iterator                  const_pred_iterator;
174   typedef AdjacentBlocks::reverse_iterator              pred_reverse_iterator;
175   typedef AdjacentBlocks::const_reverse_iterator  const_pred_reverse_iterator;
176
177   typedef AdjacentBlocks::iterator                              succ_iterator;
178   typedef AdjacentBlocks::const_iterator                  const_succ_iterator;
179   typedef AdjacentBlocks::reverse_iterator              succ_reverse_iterator;
180   typedef AdjacentBlocks::const_reverse_iterator  const_succ_reverse_iterator;
181
182   pred_iterator                pred_begin()        { return Preds.begin();   }
183   pred_iterator                pred_end()          { return Preds.end();     }
184   const_pred_iterator          pred_begin()  const { return Preds.begin();   }
185   const_pred_iterator          pred_end()    const { return Preds.end();     }
186
187   pred_reverse_iterator        pred_rbegin()       { return Preds.rbegin();  }
188   pred_reverse_iterator        pred_rend()         { return Preds.rend();    }
189   const_pred_reverse_iterator  pred_rbegin() const { return Preds.rbegin();  }
190   const_pred_reverse_iterator  pred_rend()   const { return Preds.rend();    }
191
192   succ_iterator                succ_begin()        { return Succs.begin();   }
193   succ_iterator                succ_end()          { return Succs.end();     }
194   const_succ_iterator          succ_begin()  const { return Succs.begin();   }
195   const_succ_iterator          succ_end()    const { return Succs.end();     }
196
197   succ_reverse_iterator        succ_rbegin()       { return Succs.rbegin();  }
198   succ_reverse_iterator        succ_rend()         { return Succs.rend();    }
199   const_succ_reverse_iterator  succ_rbegin() const { return Succs.rbegin();  }
200   const_succ_reverse_iterator  succ_rend()   const { return Succs.rend();    }
201
202   unsigned                     succ_size()   const { return Succs.size();    }
203   bool                         succ_empty()  const { return Succs.empty();   }
204
205   unsigned                     pred_size()   const { return Preds.size();    }
206   bool                         pred_empty()  const { return Preds.empty();   }
207
208
209   class FilterOptions {
210   public:
211     FilterOptions() {
212       IgnoreDefaultsWithCoveredEnums = 0;
213     }
214
215     unsigned IgnoreDefaultsWithCoveredEnums : 1;
216   };
217
218   static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
219        const CFGBlock *Dst);
220
221   template <typename IMPL, bool IsPred>
222   class FilteredCFGBlockIterator {
223   private:
224     IMPL I, E;
225     const FilterOptions F;
226     const CFGBlock *From;
227    public:
228     explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
229               const CFGBlock *from,
230               const FilterOptions &f)
231       : I(i), E(e), F(f), From(from) {}
232
233     bool hasMore() const { return I != E; }
234
235     FilteredCFGBlockIterator &operator++() {
236       do { ++I; } while (hasMore() && Filter(*I));
237       return *this;
238     }
239
240     const CFGBlock *operator*() const { return *I; }
241   private:
242     bool Filter(const CFGBlock *To) {
243       return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
244     }
245   };
246
247   typedef FilteredCFGBlockIterator<const_pred_iterator, true>
248           filtered_pred_iterator;
249
250   typedef FilteredCFGBlockIterator<const_succ_iterator, false>
251           filtered_succ_iterator;
252
253   filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
254     return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
255   }
256
257   filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
258     return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
259   }
260
261   // Manipulation of block contents
262
263   void setTerminator(Stmt* Statement) { Terminator = Statement; }
264   void setLabel(Stmt* Statement) { Label = Statement; }
265   void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
266
267   Stmt* getTerminator() { return Terminator; }
268   const Stmt* getTerminator() const { return Terminator; }
269
270   Stmt* getTerminatorCondition();
271
272   const Stmt* getTerminatorCondition() const {
273     return const_cast<CFGBlock*>(this)->getTerminatorCondition();
274   }
275
276   const Stmt *getLoopTarget() const { return LoopTarget; }
277
278   bool hasBinaryBranchTerminator() const;
279
280   Stmt* getLabel() { return Label; }
281   const Stmt* getLabel() const { return Label; }
282
283   unsigned getBlockID() const { return BlockID; }
284
285   void dump(const CFG *cfg, const LangOptions &LO) const;
286   void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
287   void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
288   
289   void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
290     if (Block)
291       Block->Preds.push_back(this, C);
292     Succs.push_back(Block, C);
293   }
294   
295   void appendStmt(Stmt* Statement, BumpVectorContext &C, bool asLValue) {
296       Stmts.push_back(CFGElement(Statement, asLValue), C);
297   }
298 };
299
300
301 /// CFG - Represents a source-level, intra-procedural CFG that represents the
302 ///  control-flow of a Stmt.  The Stmt can represent an entire function body,
303 ///  or a single expression.  A CFG will always contain one empty block that
304 ///  represents the Exit point of the CFG.  A CFG will also contain a designated
305 ///  Entry block.  The CFG solely represents control-flow; it consists of
306 ///  CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
307 ///  was constructed from.
308 class CFG {
309 public:
310   //===--------------------------------------------------------------------===//
311   // CFG Construction & Manipulation.
312   //===--------------------------------------------------------------------===//
313
314   class BuildOptions {
315   public:
316     bool PruneTriviallyFalseEdges:1;
317     bool AddEHEdges:1;
318     bool AddInitializers:1;
319     bool AddImplicitDtors:1;
320
321     BuildOptions()
322         : PruneTriviallyFalseEdges(true)
323         , AddEHEdges(false)
324         , AddInitializers(false)
325         , AddImplicitDtors(false) {}
326   };
327
328   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
329   ///   constructed CFG belongs to the caller.
330   static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
331       BuildOptions BO = BuildOptions());
332
333   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
334   ///  the caller should not directly free it.
335   CFGBlock* createBlock();
336
337   /// setEntry - Set the entry block of the CFG.  This is typically used
338   ///  only during CFG construction.  Most CFG clients expect that the
339   ///  entry block has no predecessors and contains no statements.
340   void setEntry(CFGBlock *B) { Entry = B; }
341
342   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
343   ///  This is typically used only during CFG construction.
344   void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
345
346   //===--------------------------------------------------------------------===//
347   // Block Iterators
348   //===--------------------------------------------------------------------===//
349
350   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;    
351   typedef CFGBlockListTy::iterator                 iterator;
352   typedef CFGBlockListTy::const_iterator           const_iterator;
353   typedef std::reverse_iterator<iterator>          reverse_iterator;
354   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
355
356   CFGBlock&                 front()                { return *Blocks.front(); }
357   CFGBlock&                 back()                 { return *Blocks.back(); }
358
359   iterator                  begin()                { return Blocks.begin(); }
360   iterator                  end()                  { return Blocks.end(); }
361   const_iterator            begin()       const    { return Blocks.begin(); }
362   const_iterator            end()         const    { return Blocks.end(); }
363
364   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
365   reverse_iterator          rend()                 { return Blocks.rend(); }
366   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
367   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
368
369   CFGBlock&                 getEntry()             { return *Entry; }
370   const CFGBlock&           getEntry()    const    { return *Entry; }
371   CFGBlock&                 getExit()              { return *Exit; }
372   const CFGBlock&           getExit()     const    { return *Exit; }
373
374   CFGBlock*        getIndirectGotoBlock() { return IndirectGotoBlock; }
375   const CFGBlock*  getIndirectGotoBlock() const { return IndirectGotoBlock; }
376
377   //===--------------------------------------------------------------------===//
378   // Member templates useful for various batch operations over CFGs.
379   //===--------------------------------------------------------------------===//
380
381   template <typename CALLBACK>
382   void VisitBlockStmts(CALLBACK& O) const {
383     for (const_iterator I=begin(), E=end(); I != E; ++I)
384       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
385            BI != BE; ++BI)
386         O(*BI);
387   }
388
389   //===--------------------------------------------------------------------===//
390   // CFG Introspection.
391   //===--------------------------------------------------------------------===//
392
393   struct   BlkExprNumTy {
394     const signed Idx;
395     explicit BlkExprNumTy(signed idx) : Idx(idx) {}
396     explicit BlkExprNumTy() : Idx(-1) {}
397     operator bool() const { return Idx >= 0; }
398     operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
399   };
400
401   bool          isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
402   BlkExprNumTy  getBlkExprNum(const Stmt* S);
403   unsigned      getNumBlkExprs();
404
405   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
406   /// start at 0).
407   unsigned getNumBlockIDs() const { return NumBlockIDs; }
408
409   //===--------------------------------------------------------------------===//
410   // CFG Debugging: Pretty-Printing and Visualization.
411   //===--------------------------------------------------------------------===//
412
413   void viewCFG(const LangOptions &LO) const;
414   void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
415   void dump(const LangOptions &LO) const;
416
417   //===--------------------------------------------------------------------===//
418   // Internal: constructors and data.
419   //===--------------------------------------------------------------------===//
420
421   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
422           BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
423
424   ~CFG();
425
426   llvm::BumpPtrAllocator& getAllocator() {
427     return BlkBVC.getAllocator();
428   }
429   
430   BumpVectorContext &getBumpVectorContext() {
431     return BlkBVC;
432   }
433
434 private:
435   CFGBlock* Entry;
436   CFGBlock* Exit;
437   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
438                                 // for indirect gotos
439   unsigned  NumBlockIDs;
440
441   // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
442   //  It represents a map from Expr* to integers to record the set of
443   //  block-level expressions and their "statement number" in the CFG.
444   void*     BlkExprMap;
445   
446   BumpVectorContext BlkBVC;
447   
448   CFGBlockListTy Blocks;
449
450 };
451 } // end namespace clang
452
453 //===----------------------------------------------------------------------===//
454 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
455 //===----------------------------------------------------------------------===//
456
457 namespace llvm {
458
459 /// Implement simplify_type for CFGElement, so that we can dyn_cast from
460 /// CFGElement to a specific Stmt class.
461 template <> struct simplify_type<const ::clang::CFGElement> {
462   typedef ::clang::Stmt* SimpleType;
463   static SimpleType getSimplifiedValue(const ::clang::CFGElement &Val) {
464     return Val.getStmt();
465   }
466 };
467   
468 template <> struct simplify_type< ::clang::CFGElement> 
469   : public simplify_type<const ::clang::CFGElement> {};
470   
471 // Traits for: CFGBlock
472
473 template <> struct GraphTraits< ::clang::CFGBlock* > {
474   typedef ::clang::CFGBlock NodeType;
475   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
476
477   static NodeType* getEntryNode(::clang::CFGBlock* BB)
478   { return BB; }
479
480   static inline ChildIteratorType child_begin(NodeType* N)
481   { return N->succ_begin(); }
482
483   static inline ChildIteratorType child_end(NodeType* N)
484   { return N->succ_end(); }
485 };
486
487 template <> struct GraphTraits< const ::clang::CFGBlock* > {
488   typedef const ::clang::CFGBlock NodeType;
489   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
490
491   static NodeType* getEntryNode(const clang::CFGBlock* BB)
492   { return BB; }
493
494   static inline ChildIteratorType child_begin(NodeType* N)
495   { return N->succ_begin(); }
496
497   static inline ChildIteratorType child_end(NodeType* N)
498   { return N->succ_end(); }
499 };
500
501 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
502   typedef const ::clang::CFGBlock NodeType;
503   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
504
505   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
506   { return G.Graph; }
507
508   static inline ChildIteratorType child_begin(NodeType* N)
509   { return N->pred_begin(); }
510
511   static inline ChildIteratorType child_end(NodeType* N)
512   { return N->pred_end(); }
513 };
514
515 // Traits for: CFG
516
517 template <> struct GraphTraits< ::clang::CFG* >
518     : public GraphTraits< ::clang::CFGBlock* >  {
519
520   typedef ::clang::CFG::iterator nodes_iterator;
521
522   static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
523   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
524   static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
525 };
526
527 template <> struct GraphTraits<const ::clang::CFG* >
528     : public GraphTraits<const ::clang::CFGBlock* >  {
529
530   typedef ::clang::CFG::const_iterator nodes_iterator;
531
532   static NodeType *getEntryNode( const ::clang::CFG* F) {
533     return &F->getEntry();
534   }
535   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
536     return F->begin();
537   }
538   static nodes_iterator nodes_end( const ::clang::CFG* F) {
539     return F->end();
540   }
541 };
542
543 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
544   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
545
546   typedef ::clang::CFG::const_iterator nodes_iterator;
547
548   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
549   static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
550   static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
551 };
552 } // end llvm namespace
553 #endif