1 //===--- CFG.h - Classes for representing and building CFGs------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_CFG_H
16 #define LLVM_CLANG_CFG_H
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"
39 /// CFGElement - Represents a top-level expression in a basic block.
53 DTOR_BEGIN = AutomaticObjectDtor
57 // The int bits are used to mark the main kind.
58 llvm::PointerIntPair<void *, 2> Data1;
59 // The int bits are used to mark the dtor kind.
60 llvm::PointerIntPair<void *, 2> Data2;
64 CFGElement(void *Ptr, unsigned Int) : Data1(Ptr, Int) {}
66 Kind getKind() const { return static_cast<Kind>(Data1.getInt()); }
68 Kind getDtorKind() const {
69 assert(getKind() == Dtor);
70 return static_cast<Kind>(Data2.getInt() + DTOR_BEGIN);
73 bool isValid() const { return Data1.getPointer(); }
75 operator bool() const { return isValid(); }
77 template<class ElemTy> ElemTy getAs() const {
78 if (llvm::isa<ElemTy>(this))
79 return *static_cast<const ElemTy*>(this);
83 static bool classof(const CFGElement *E) { return true; }
86 class CFGStmt : public CFGElement {
89 CFGStmt(Stmt *S, bool asLValue) : CFGElement(S, asLValue) {}
91 Stmt *getStmt() const { return static_cast<Stmt *>(Data1.getPointer()); }
93 operator Stmt*() const { return getStmt(); }
95 bool asLValue() const {
96 return static_cast<Kind>(Data1.getInt()) == StatementAsLValue;
99 static bool classof(const CFGElement *E) {
100 return E->getKind() == Statement || E->getKind() == StatementAsLValue;
104 class CFGInitializer : public CFGElement {
106 static bool classof(const CFGElement *E) {
107 return E->getKind() == Initializer;
111 class CFGImplicitDtor : public CFGElement {
113 static bool classof(const CFGElement *E) {
114 return E->getKind() == Dtor;
118 class CFGAutomaticObjDtor: public CFGImplicitDtor {
120 static bool classof(const CFGElement *E) {
121 return E->getKind() == Dtor && E->getDtorKind() == AutomaticObjectDtor;
125 class CFGBaseDtor : public CFGImplicitDtor {
127 static bool classof(const CFGElement *E) {
128 return E->getKind() == Dtor && E->getDtorKind() == BaseDtor;
132 class CFGMemberDtor : public CFGImplicitDtor {
134 static bool classof(const CFGElement *E) {
135 return E->getKind() == Dtor && E->getDtorKind() == MemberDtor;
140 class CFGTemporaryDtor : public CFGImplicitDtor {
142 static bool classof(const CFGElement *E) {
143 return E->getKind() == Dtor && E->getDtorKind() == TemporaryDtor;
147 /// CFGBlock - Represents a single basic block in a source-level CFG.
150 /// (1) A set of statements/expressions (which may contain subexpressions).
151 /// (2) A "terminator" statement (not in the set of statements).
152 /// (3) A list of successors and predecessors.
154 /// Terminator: The terminator represents the type of control-flow that occurs
155 /// at the end of the basic block. The terminator is a Stmt* referring to an
156 /// AST node that has control-flow: if-statements, breaks, loops, etc.
157 /// If the control-flow is conditional, the condition expression will appear
158 /// within the set of statements in the block (usually the last statement).
160 /// Predecessors: the order in the set of predecessors is arbitrary.
162 /// Successors: the order in the set of successors is NOT arbitrary. We
163 /// currently have the following orderings based on the terminator:
165 /// Terminator Successor Ordering
166 /// -----------------------------------------------------
167 /// if Then Block; Else Block
168 /// ? operator LHS expression; RHS expression
169 /// &&, || expression that uses result of && or ||, RHS
173 typedef BumpVector<CFGElement> ImplTy;
176 ElementList(BumpVectorContext &C) : Impl(C, 4) {}
178 typedef std::reverse_iterator<ImplTy::iterator> iterator;
179 typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
180 typedef ImplTy::iterator reverse_iterator;
181 typedef ImplTy::const_iterator const_reverse_iterator;
183 void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
184 CFGElement front() const { return Impl.back(); }
185 CFGElement back() const { return Impl.front(); }
187 iterator begin() { return Impl.rbegin(); }
188 iterator end() { return Impl.rend(); }
189 const_iterator begin() const { return Impl.rbegin(); }
190 const_iterator end() const { return Impl.rend(); }
191 reverse_iterator rbegin() { return Impl.begin(); }
192 reverse_iterator rend() { return Impl.end(); }
193 const_reverse_iterator rbegin() const { return Impl.begin(); }
194 const_reverse_iterator rend() const { return Impl.end(); }
196 CFGElement operator[](size_t i) const {
197 assert(i < Impl.size());
198 return Impl[Impl.size() - 1 - i];
201 size_t size() const { return Impl.size(); }
202 bool empty() const { return Impl.empty(); }
205 /// Stmts - The set of statements in the basic block.
206 ElementList Elements;
208 /// Label - An (optional) label that prefixes the executable
209 /// statements in the block. When this variable is non-NULL, it is
210 /// either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
213 /// Terminator - The terminator for a basic block that
214 /// indicates the type of control-flow that occurs between a block
215 /// and its successors.
218 /// LoopTarget - Some blocks are used to represent the "loop edge" to
219 /// the start of a loop from within the loop body. This Stmt* will be
220 /// refer to the loop statement for such blocks (and be null otherwise).
221 const Stmt *LoopTarget;
223 /// BlockID - A numerical ID assigned to a CFGBlock during construction
227 /// Predecessors/Successors - Keep track of the predecessor / successor
229 typedef BumpVector<CFGBlock*> AdjacentBlocks;
230 AdjacentBlocks Preds;
231 AdjacentBlocks Succs;
234 explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
235 : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
236 BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
239 // Statement iterators
240 typedef ElementList::iterator iterator;
241 typedef ElementList::const_iterator const_iterator;
242 typedef ElementList::reverse_iterator reverse_iterator;
243 typedef ElementList::const_reverse_iterator const_reverse_iterator;
245 CFGElement front() const { return Elements.front(); }
246 CFGElement back() const { return Elements.back(); }
248 iterator begin() { return Elements.begin(); }
249 iterator end() { return Elements.end(); }
250 const_iterator begin() const { return Elements.begin(); }
251 const_iterator end() const { return Elements.end(); }
253 reverse_iterator rbegin() { return Elements.rbegin(); }
254 reverse_iterator rend() { return Elements.rend(); }
255 const_reverse_iterator rbegin() const { return Elements.rbegin(); }
256 const_reverse_iterator rend() const { return Elements.rend(); }
258 unsigned size() const { return Elements.size(); }
259 bool empty() const { return Elements.empty(); }
261 CFGElement operator[](size_t i) const { return Elements[i]; }
264 typedef AdjacentBlocks::iterator pred_iterator;
265 typedef AdjacentBlocks::const_iterator const_pred_iterator;
266 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
267 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
269 typedef AdjacentBlocks::iterator succ_iterator;
270 typedef AdjacentBlocks::const_iterator const_succ_iterator;
271 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
272 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
274 pred_iterator pred_begin() { return Preds.begin(); }
275 pred_iterator pred_end() { return Preds.end(); }
276 const_pred_iterator pred_begin() const { return Preds.begin(); }
277 const_pred_iterator pred_end() const { return Preds.end(); }
279 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
280 pred_reverse_iterator pred_rend() { return Preds.rend(); }
281 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
282 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
284 succ_iterator succ_begin() { return Succs.begin(); }
285 succ_iterator succ_end() { return Succs.end(); }
286 const_succ_iterator succ_begin() const { return Succs.begin(); }
287 const_succ_iterator succ_end() const { return Succs.end(); }
289 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
290 succ_reverse_iterator succ_rend() { return Succs.rend(); }
291 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
292 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
294 unsigned succ_size() const { return Succs.size(); }
295 bool succ_empty() const { return Succs.empty(); }
297 unsigned pred_size() const { return Preds.size(); }
298 bool pred_empty() const { return Preds.empty(); }
301 class FilterOptions {
304 IgnoreDefaultsWithCoveredEnums = 0;
307 unsigned IgnoreDefaultsWithCoveredEnums : 1;
310 static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
311 const CFGBlock *Dst);
313 template <typename IMPL, bool IsPred>
314 class FilteredCFGBlockIterator {
317 const FilterOptions F;
318 const CFGBlock *From;
320 explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
321 const CFGBlock *from,
322 const FilterOptions &f)
323 : I(i), E(e), F(f), From(from) {}
325 bool hasMore() const { return I != E; }
327 FilteredCFGBlockIterator &operator++() {
328 do { ++I; } while (hasMore() && Filter(*I));
332 const CFGBlock *operator*() const { return *I; }
334 bool Filter(const CFGBlock *To) {
335 return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
339 typedef FilteredCFGBlockIterator<const_pred_iterator, true>
340 filtered_pred_iterator;
342 typedef FilteredCFGBlockIterator<const_succ_iterator, false>
343 filtered_succ_iterator;
345 filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
346 return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
349 filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
350 return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
353 // Manipulation of block contents
355 void setTerminator(Stmt* Statement) { Terminator = Statement; }
356 void setLabel(Stmt* Statement) { Label = Statement; }
357 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
359 Stmt* getTerminator() { return Terminator; }
360 const Stmt* getTerminator() const { return Terminator; }
362 Stmt* getTerminatorCondition();
364 const Stmt* getTerminatorCondition() const {
365 return const_cast<CFGBlock*>(this)->getTerminatorCondition();
368 const Stmt *getLoopTarget() const { return LoopTarget; }
370 bool hasBinaryBranchTerminator() const;
372 Stmt* getLabel() { return Label; }
373 const Stmt* getLabel() const { return Label; }
375 unsigned getBlockID() const { return BlockID; }
377 void dump(const CFG *cfg, const LangOptions &LO) const;
378 void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
379 void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
381 void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
383 Block->Preds.push_back(this, C);
384 Succs.push_back(Block, C);
387 void appendStmt(Stmt* Statement, BumpVectorContext &C, bool asLValue) {
388 Elements.push_back(CFGStmt(Statement, asLValue), C);
392 /// CFG - Represents a source-level, intra-procedural CFG that represents the
393 /// control-flow of a Stmt. The Stmt can represent an entire function body,
394 /// or a single expression. A CFG will always contain one empty block that
395 /// represents the Exit point of the CFG. A CFG will also contain a designated
396 /// Entry block. The CFG solely represents control-flow; it consists of
397 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
398 /// was constructed from.
401 //===--------------------------------------------------------------------===//
402 // CFG Construction & Manipulation.
403 //===--------------------------------------------------------------------===//
407 bool PruneTriviallyFalseEdges:1;
409 bool AddInitializers:1;
410 bool AddImplicitDtors:1;
413 : PruneTriviallyFalseEdges(true)
415 , AddInitializers(false)
416 , AddImplicitDtors(false) {}
419 /// buildCFG - Builds a CFG from an AST. The responsibility to free the
420 /// constructed CFG belongs to the caller.
421 static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
422 BuildOptions BO = BuildOptions());
424 /// createBlock - Create a new block in the CFG. The CFG owns the block;
425 /// the caller should not directly free it.
426 CFGBlock* createBlock();
428 /// setEntry - Set the entry block of the CFG. This is typically used
429 /// only during CFG construction. Most CFG clients expect that the
430 /// entry block has no predecessors and contains no statements.
431 void setEntry(CFGBlock *B) { Entry = B; }
433 /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
434 /// This is typically used only during CFG construction.
435 void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
437 //===--------------------------------------------------------------------===//
439 //===--------------------------------------------------------------------===//
441 typedef BumpVector<CFGBlock*> CFGBlockListTy;
442 typedef CFGBlockListTy::iterator iterator;
443 typedef CFGBlockListTy::const_iterator const_iterator;
444 typedef std::reverse_iterator<iterator> reverse_iterator;
445 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
447 CFGBlock& front() { return *Blocks.front(); }
448 CFGBlock& back() { return *Blocks.back(); }
450 iterator begin() { return Blocks.begin(); }
451 iterator end() { return Blocks.end(); }
452 const_iterator begin() const { return Blocks.begin(); }
453 const_iterator end() const { return Blocks.end(); }
455 reverse_iterator rbegin() { return Blocks.rbegin(); }
456 reverse_iterator rend() { return Blocks.rend(); }
457 const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
458 const_reverse_iterator rend() const { return Blocks.rend(); }
460 CFGBlock& getEntry() { return *Entry; }
461 const CFGBlock& getEntry() const { return *Entry; }
462 CFGBlock& getExit() { return *Exit; }
463 const CFGBlock& getExit() const { return *Exit; }
465 CFGBlock* getIndirectGotoBlock() { return IndirectGotoBlock; }
466 const CFGBlock* getIndirectGotoBlock() const { return IndirectGotoBlock; }
468 //===--------------------------------------------------------------------===//
469 // Member templates useful for various batch operations over CFGs.
470 //===--------------------------------------------------------------------===//
472 template <typename CALLBACK>
473 void VisitBlockStmts(CALLBACK& O) const {
474 for (const_iterator I=begin(), E=end(); I != E; ++I)
475 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
477 if (CFGStmt S = BI->getAs<CFGStmt>())
482 //===--------------------------------------------------------------------===//
483 // CFG Introspection.
484 //===--------------------------------------------------------------------===//
486 struct BlkExprNumTy {
488 explicit BlkExprNumTy(signed idx) : Idx(idx) {}
489 explicit BlkExprNumTy() : Idx(-1) {}
490 operator bool() const { return Idx >= 0; }
491 operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
494 bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
495 BlkExprNumTy getBlkExprNum(const Stmt* S);
496 unsigned getNumBlkExprs();
498 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
500 unsigned getNumBlockIDs() const { return NumBlockIDs; }
502 //===--------------------------------------------------------------------===//
503 // CFG Debugging: Pretty-Printing and Visualization.
504 //===--------------------------------------------------------------------===//
506 void viewCFG(const LangOptions &LO) const;
507 void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
508 void dump(const LangOptions &LO) const;
510 //===--------------------------------------------------------------------===//
511 // Internal: constructors and data.
512 //===--------------------------------------------------------------------===//
514 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
515 BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
519 llvm::BumpPtrAllocator& getAllocator() {
520 return BlkBVC.getAllocator();
523 BumpVectorContext &getBumpVectorContext() {
530 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
531 // for indirect gotos
532 unsigned NumBlockIDs;
534 // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
535 // It represents a map from Expr* to integers to record the set of
536 // block-level expressions and their "statement number" in the CFG.
539 BumpVectorContext BlkBVC;
541 CFGBlockListTy Blocks;
544 } // end namespace clang
546 //===----------------------------------------------------------------------===//
547 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
548 //===----------------------------------------------------------------------===//
552 // Traits for: CFGBlock
554 template <> struct GraphTraits< ::clang::CFGBlock* > {
555 typedef ::clang::CFGBlock NodeType;
556 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
558 static NodeType* getEntryNode(::clang::CFGBlock* BB)
561 static inline ChildIteratorType child_begin(NodeType* N)
562 { return N->succ_begin(); }
564 static inline ChildIteratorType child_end(NodeType* N)
565 { return N->succ_end(); }
568 template <> struct GraphTraits< const ::clang::CFGBlock* > {
569 typedef const ::clang::CFGBlock NodeType;
570 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
572 static NodeType* getEntryNode(const clang::CFGBlock* BB)
575 static inline ChildIteratorType child_begin(NodeType* N)
576 { return N->succ_begin(); }
578 static inline ChildIteratorType child_end(NodeType* N)
579 { return N->succ_end(); }
582 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
583 typedef const ::clang::CFGBlock NodeType;
584 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
586 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
589 static inline ChildIteratorType child_begin(NodeType* N)
590 { return N->pred_begin(); }
592 static inline ChildIteratorType child_end(NodeType* N)
593 { return N->pred_end(); }
598 template <> struct GraphTraits< ::clang::CFG* >
599 : public GraphTraits< ::clang::CFGBlock* > {
601 typedef ::clang::CFG::iterator nodes_iterator;
603 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
604 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
605 static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
608 template <> struct GraphTraits<const ::clang::CFG* >
609 : public GraphTraits<const ::clang::CFGBlock* > {
611 typedef ::clang::CFG::const_iterator nodes_iterator;
613 static NodeType *getEntryNode( const ::clang::CFG* F) {
614 return &F->getEntry();
616 static nodes_iterator nodes_begin( const ::clang::CFG* F) {
619 static nodes_iterator nodes_end( const ::clang::CFG* F) {
624 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
625 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
627 typedef ::clang::CFG::const_iterator nodes_iterator;
629 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
630 static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
631 static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
633 } // end llvm namespace