]> granicus.if.org Git - clang/blob - include/clang/Analysis/CFG.h
Remove from the CFG the half-implemented support for scoping information. We decided...
[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   /// buildCFG - Builds a CFG from an AST.  The responsibility to free the
315   ///   constructed CFG belongs to the caller.
316   static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
317                        bool pruneTriviallyFalseEdges = true,
318                        bool AddEHEdges = false);
319
320   /// createBlock - Create a new block in the CFG.  The CFG owns the block;
321   ///  the caller should not directly free it.
322   CFGBlock* createBlock();
323
324   /// setEntry - Set the entry block of the CFG.  This is typically used
325   ///  only during CFG construction.  Most CFG clients expect that the
326   ///  entry block has no predecessors and contains no statements.
327   void setEntry(CFGBlock *B) { Entry = B; }
328
329   /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
330   ///  This is typically used only during CFG construction.
331   void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
332
333   //===--------------------------------------------------------------------===//
334   // Block Iterators
335   //===--------------------------------------------------------------------===//
336
337   typedef BumpVector<CFGBlock*>                    CFGBlockListTy;    
338   typedef CFGBlockListTy::iterator                 iterator;
339   typedef CFGBlockListTy::const_iterator           const_iterator;
340   typedef std::reverse_iterator<iterator>          reverse_iterator;
341   typedef std::reverse_iterator<const_iterator>    const_reverse_iterator;
342
343   CFGBlock&                 front()                { return *Blocks.front(); }
344   CFGBlock&                 back()                 { return *Blocks.back(); }
345
346   iterator                  begin()                { return Blocks.begin(); }
347   iterator                  end()                  { return Blocks.end(); }
348   const_iterator            begin()       const    { return Blocks.begin(); }
349   const_iterator            end()         const    { return Blocks.end(); }
350
351   reverse_iterator          rbegin()               { return Blocks.rbegin(); }
352   reverse_iterator          rend()                 { return Blocks.rend(); }
353   const_reverse_iterator    rbegin()      const    { return Blocks.rbegin(); }
354   const_reverse_iterator    rend()        const    { return Blocks.rend(); }
355
356   CFGBlock&                 getEntry()             { return *Entry; }
357   const CFGBlock&           getEntry()    const    { return *Entry; }
358   CFGBlock&                 getExit()              { return *Exit; }
359   const CFGBlock&           getExit()     const    { return *Exit; }
360
361   CFGBlock*        getIndirectGotoBlock() { return IndirectGotoBlock; }
362   const CFGBlock*  getIndirectGotoBlock() const { return IndirectGotoBlock; }
363
364   //===--------------------------------------------------------------------===//
365   // Member templates useful for various batch operations over CFGs.
366   //===--------------------------------------------------------------------===//
367
368   template <typename CALLBACK>
369   void VisitBlockStmts(CALLBACK& O) const {
370     for (const_iterator I=begin(), E=end(); I != E; ++I)
371       for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
372            BI != BE; ++BI)
373         O(*BI);
374   }
375
376   //===--------------------------------------------------------------------===//
377   // CFG Introspection.
378   //===--------------------------------------------------------------------===//
379
380   struct   BlkExprNumTy {
381     const signed Idx;
382     explicit BlkExprNumTy(signed idx) : Idx(idx) {}
383     explicit BlkExprNumTy() : Idx(-1) {}
384     operator bool() const { return Idx >= 0; }
385     operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
386   };
387
388   bool          isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
389   BlkExprNumTy  getBlkExprNum(const Stmt* S);
390   unsigned      getNumBlkExprs();
391
392   /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
393   /// start at 0).
394   unsigned getNumBlockIDs() const { return NumBlockIDs; }
395
396   //===--------------------------------------------------------------------===//
397   // CFG Debugging: Pretty-Printing and Visualization.
398   //===--------------------------------------------------------------------===//
399
400   void viewCFG(const LangOptions &LO) const;
401   void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
402   void dump(const LangOptions &LO) const;
403
404   //===--------------------------------------------------------------------===//
405   // Internal: constructors and data.
406   //===--------------------------------------------------------------------===//
407
408   CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
409           BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
410
411   ~CFG();
412
413   llvm::BumpPtrAllocator& getAllocator() {
414     return BlkBVC.getAllocator();
415   }
416   
417   BumpVectorContext &getBumpVectorContext() {
418     return BlkBVC;
419   }
420
421 private:
422   CFGBlock* Entry;
423   CFGBlock* Exit;
424   CFGBlock* IndirectGotoBlock;  // Special block to contain collective dispatch
425                                 // for indirect gotos
426   unsigned  NumBlockIDs;
427
428   // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
429   //  It represents a map from Expr* to integers to record the set of
430   //  block-level expressions and their "statement number" in the CFG.
431   void*     BlkExprMap;
432   
433   BumpVectorContext BlkBVC;
434   
435   CFGBlockListTy Blocks;
436
437 };
438 } // end namespace clang
439
440 //===----------------------------------------------------------------------===//
441 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
442 //===----------------------------------------------------------------------===//
443
444 namespace llvm {
445
446 /// Implement simplify_type for CFGElement, so that we can dyn_cast from
447 /// CFGElement to a specific Stmt class.
448 template <> struct simplify_type<const ::clang::CFGElement> {
449   typedef ::clang::Stmt* SimpleType;
450   static SimpleType getSimplifiedValue(const ::clang::CFGElement &Val) {
451     return Val.getStmt();
452   }
453 };
454   
455 template <> struct simplify_type< ::clang::CFGElement> 
456   : public simplify_type<const ::clang::CFGElement> {};
457   
458 // Traits for: CFGBlock
459
460 template <> struct GraphTraits< ::clang::CFGBlock* > {
461   typedef ::clang::CFGBlock NodeType;
462   typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
463
464   static NodeType* getEntryNode(::clang::CFGBlock* BB)
465   { return BB; }
466
467   static inline ChildIteratorType child_begin(NodeType* N)
468   { return N->succ_begin(); }
469
470   static inline ChildIteratorType child_end(NodeType* N)
471   { return N->succ_end(); }
472 };
473
474 template <> struct GraphTraits< const ::clang::CFGBlock* > {
475   typedef const ::clang::CFGBlock NodeType;
476   typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
477
478   static NodeType* getEntryNode(const clang::CFGBlock* BB)
479   { return BB; }
480
481   static inline ChildIteratorType child_begin(NodeType* N)
482   { return N->succ_begin(); }
483
484   static inline ChildIteratorType child_end(NodeType* N)
485   { return N->succ_end(); }
486 };
487
488 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
489   typedef const ::clang::CFGBlock NodeType;
490   typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
491
492   static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
493   { return G.Graph; }
494
495   static inline ChildIteratorType child_begin(NodeType* N)
496   { return N->pred_begin(); }
497
498   static inline ChildIteratorType child_end(NodeType* N)
499   { return N->pred_end(); }
500 };
501
502 // Traits for: CFG
503
504 template <> struct GraphTraits< ::clang::CFG* >
505     : public GraphTraits< ::clang::CFGBlock* >  {
506
507   typedef ::clang::CFG::iterator nodes_iterator;
508
509   static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
510   static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
511   static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
512 };
513
514 template <> struct GraphTraits<const ::clang::CFG* >
515     : public GraphTraits<const ::clang::CFGBlock* >  {
516
517   typedef ::clang::CFG::const_iterator nodes_iterator;
518
519   static NodeType *getEntryNode( const ::clang::CFG* F) {
520     return &F->getEntry();
521   }
522   static nodes_iterator nodes_begin( const ::clang::CFG* F) {
523     return F->begin();
524   }
525   static nodes_iterator nodes_end( const ::clang::CFG* F) {
526     return F->end();
527   }
528 };
529
530 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
531   : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
532
533   typedef ::clang::CFG::const_iterator nodes_iterator;
534
535   static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
536   static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
537   static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
538 };
539 } // end llvm namespace
540 #endif