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