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"
35 class CXXBaseOrMemberInitializer;
41 /// CFGElement - Represents a top-level expression in a basic block.
55 DTOR_BEGIN = AutomaticObjectDtor
59 // The int bits are used to mark the main kind.
60 llvm::PointerIntPair<void *, 2> Data1;
61 // The int bits are used to mark the dtor kind.
62 llvm::PointerIntPair<void *, 2> Data2;
64 CFGElement(void *Ptr, unsigned Int) : Data1(Ptr, Int) {}
65 CFGElement(void *Ptr1, unsigned Int1, void *Ptr2, unsigned Int2)
66 : Data1(Ptr1, Int1), Data2(Ptr2, Int2) {}
71 Kind getKind() const { return static_cast<Kind>(Data1.getInt()); }
73 Kind getDtorKind() const {
74 assert(getKind() == Dtor);
75 return static_cast<Kind>(Data2.getInt() + DTOR_BEGIN);
78 bool isValid() const { return Data1.getPointer(); }
80 operator bool() const { return isValid(); }
82 template<class ElemTy> ElemTy getAs() const {
83 if (llvm::isa<ElemTy>(this))
84 return *static_cast<const ElemTy*>(this);
88 static bool classof(const CFGElement *E) { return true; }
91 class CFGStmt : public CFGElement {
94 CFGStmt(Stmt *S, bool asLValue) : CFGElement(S, asLValue) {}
96 Stmt *getStmt() const { return static_cast<Stmt *>(Data1.getPointer()); }
98 operator Stmt*() const { return getStmt(); }
100 bool asLValue() const {
101 return static_cast<Kind>(Data1.getInt()) == StatementAsLValue;
104 static bool classof(const CFGElement *E) {
105 return E->getKind() == Statement || E->getKind() == StatementAsLValue;
109 /// CFGInitializer - Represents C++ base or member initializer from
110 /// constructor's initialization list.
111 class CFGInitializer : public CFGElement {
114 CFGInitializer(CXXBaseOrMemberInitializer* I)
115 : CFGElement(I, Initializer) {}
117 CXXBaseOrMemberInitializer* getInitializer() const {
118 return static_cast<CXXBaseOrMemberInitializer*>(Data1.getPointer());
120 operator CXXBaseOrMemberInitializer*() const { return getInitializer(); }
122 static bool classof(const CFGElement *E) {
123 return E->getKind() == Initializer;
127 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated
128 /// by compiler on various occasions.
129 class CFGImplicitDtor : public CFGElement {
131 CFGImplicitDtor(unsigned K, void* P, void* S)
132 : CFGElement(P, Dtor, S, K - DTOR_BEGIN) {}
137 static bool classof(const CFGElement *E) {
138 return E->getKind() == Dtor;
142 /// CFGAutomaticObjDtor - Represents C++ object destructor implicit generated
143 /// for automatic object or temporary bound to const reference at the point
144 /// of leaving its local scope.
145 class CFGAutomaticObjDtor: public CFGImplicitDtor {
147 CFGAutomaticObjDtor() {}
148 CFGAutomaticObjDtor(VarDecl* VD, Stmt* S)
149 : CFGImplicitDtor(AutomaticObjectDtor, VD, S) {}
151 VarDecl* getVarDecl() const {
152 return static_cast<VarDecl*>(Data1.getPointer());
155 // Get statement end of which triggered the destructor call.
156 Stmt* getTriggerStmt() const {
157 return static_cast<Stmt*>(Data2.getPointer());
160 static bool classof(const CFGElement *E) {
161 return E->getKind() == Dtor && E->getDtorKind() == AutomaticObjectDtor;
165 class CFGBaseDtor : public CFGImplicitDtor {
167 static bool classof(const CFGElement *E) {
168 return E->getKind() == Dtor && E->getDtorKind() == BaseDtor;
172 class CFGMemberDtor : public CFGImplicitDtor {
174 static bool classof(const CFGElement *E) {
175 return E->getKind() == Dtor && E->getDtorKind() == MemberDtor;
180 class CFGTemporaryDtor : public CFGImplicitDtor {
182 static bool classof(const CFGElement *E) {
183 return E->getKind() == Dtor && E->getDtorKind() == TemporaryDtor;
187 /// CFGBlock - Represents a single basic block in a source-level CFG.
190 /// (1) A set of statements/expressions (which may contain subexpressions).
191 /// (2) A "terminator" statement (not in the set of statements).
192 /// (3) A list of successors and predecessors.
194 /// Terminator: The terminator represents the type of control-flow that occurs
195 /// at the end of the basic block. The terminator is a Stmt* referring to an
196 /// AST node that has control-flow: if-statements, breaks, loops, etc.
197 /// If the control-flow is conditional, the condition expression will appear
198 /// within the set of statements in the block (usually the last statement).
200 /// Predecessors: the order in the set of predecessors is arbitrary.
202 /// Successors: the order in the set of successors is NOT arbitrary. We
203 /// currently have the following orderings based on the terminator:
205 /// Terminator Successor Ordering
206 /// -----------------------------------------------------
207 /// if Then Block; Else Block
208 /// ? operator LHS expression; RHS expression
209 /// &&, || expression that uses result of && or ||, RHS
213 typedef BumpVector<CFGElement> ImplTy;
216 ElementList(BumpVectorContext &C) : Impl(C, 4) {}
218 typedef std::reverse_iterator<ImplTy::iterator> iterator;
219 typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
220 typedef ImplTy::iterator reverse_iterator;
221 typedef ImplTy::const_iterator const_reverse_iterator;
223 void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
224 reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
225 BumpVectorContext& C) {
226 return Impl.insert(I, Cnt, E, C);
229 CFGElement front() const { return Impl.back(); }
230 CFGElement back() const { return Impl.front(); }
232 iterator begin() { return Impl.rbegin(); }
233 iterator end() { return Impl.rend(); }
234 const_iterator begin() const { return Impl.rbegin(); }
235 const_iterator end() const { return Impl.rend(); }
236 reverse_iterator rbegin() { return Impl.begin(); }
237 reverse_iterator rend() { return Impl.end(); }
238 const_reverse_iterator rbegin() const { return Impl.begin(); }
239 const_reverse_iterator rend() const { return Impl.end(); }
241 CFGElement operator[](size_t i) const {
242 assert(i < Impl.size());
243 return Impl[Impl.size() - 1 - i];
246 size_t size() const { return Impl.size(); }
247 bool empty() const { return Impl.empty(); }
250 /// Stmts - The set of statements in the basic block.
251 ElementList Elements;
253 /// Label - An (optional) label that prefixes the executable
254 /// statements in the block. When this variable is non-NULL, it is
255 /// either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
258 /// Terminator - The terminator for a basic block that
259 /// indicates the type of control-flow that occurs between a block
260 /// and its successors.
263 /// LoopTarget - Some blocks are used to represent the "loop edge" to
264 /// the start of a loop from within the loop body. This Stmt* will be
265 /// refer to the loop statement for such blocks (and be null otherwise).
266 const Stmt *LoopTarget;
268 /// BlockID - A numerical ID assigned to a CFGBlock during construction
272 /// Predecessors/Successors - Keep track of the predecessor / successor
274 typedef BumpVector<CFGBlock*> AdjacentBlocks;
275 AdjacentBlocks Preds;
276 AdjacentBlocks Succs;
279 explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
280 : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
281 BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
284 // Statement iterators
285 typedef ElementList::iterator iterator;
286 typedef ElementList::const_iterator const_iterator;
287 typedef ElementList::reverse_iterator reverse_iterator;
288 typedef ElementList::const_reverse_iterator const_reverse_iterator;
290 CFGElement front() const { return Elements.front(); }
291 CFGElement back() const { return Elements.back(); }
293 iterator begin() { return Elements.begin(); }
294 iterator end() { return Elements.end(); }
295 const_iterator begin() const { return Elements.begin(); }
296 const_iterator end() const { return Elements.end(); }
298 reverse_iterator rbegin() { return Elements.rbegin(); }
299 reverse_iterator rend() { return Elements.rend(); }
300 const_reverse_iterator rbegin() const { return Elements.rbegin(); }
301 const_reverse_iterator rend() const { return Elements.rend(); }
303 unsigned size() const { return Elements.size(); }
304 bool empty() const { return Elements.empty(); }
306 CFGElement operator[](size_t i) const { return Elements[i]; }
309 typedef AdjacentBlocks::iterator pred_iterator;
310 typedef AdjacentBlocks::const_iterator const_pred_iterator;
311 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
312 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
314 typedef AdjacentBlocks::iterator succ_iterator;
315 typedef AdjacentBlocks::const_iterator const_succ_iterator;
316 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
317 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
319 pred_iterator pred_begin() { return Preds.begin(); }
320 pred_iterator pred_end() { return Preds.end(); }
321 const_pred_iterator pred_begin() const { return Preds.begin(); }
322 const_pred_iterator pred_end() const { return Preds.end(); }
324 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
325 pred_reverse_iterator pred_rend() { return Preds.rend(); }
326 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
327 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
329 succ_iterator succ_begin() { return Succs.begin(); }
330 succ_iterator succ_end() { return Succs.end(); }
331 const_succ_iterator succ_begin() const { return Succs.begin(); }
332 const_succ_iterator succ_end() const { return Succs.end(); }
334 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
335 succ_reverse_iterator succ_rend() { return Succs.rend(); }
336 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
337 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
339 unsigned succ_size() const { return Succs.size(); }
340 bool succ_empty() const { return Succs.empty(); }
342 unsigned pred_size() const { return Preds.size(); }
343 bool pred_empty() const { return Preds.empty(); }
346 class FilterOptions {
349 IgnoreDefaultsWithCoveredEnums = 0;
352 unsigned IgnoreDefaultsWithCoveredEnums : 1;
355 static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
356 const CFGBlock *Dst);
358 template <typename IMPL, bool IsPred>
359 class FilteredCFGBlockIterator {
362 const FilterOptions F;
363 const CFGBlock *From;
365 explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
366 const CFGBlock *from,
367 const FilterOptions &f)
368 : I(i), E(e), F(f), From(from) {}
370 bool hasMore() const { return I != E; }
372 FilteredCFGBlockIterator &operator++() {
373 do { ++I; } while (hasMore() && Filter(*I));
377 const CFGBlock *operator*() const { return *I; }
379 bool Filter(const CFGBlock *To) {
380 return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
384 typedef FilteredCFGBlockIterator<const_pred_iterator, true>
385 filtered_pred_iterator;
387 typedef FilteredCFGBlockIterator<const_succ_iterator, false>
388 filtered_succ_iterator;
390 filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
391 return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
394 filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
395 return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
398 // Manipulation of block contents
400 void setTerminator(Stmt* Statement) { Terminator = Statement; }
401 void setLabel(Stmt* Statement) { Label = Statement; }
402 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
404 Stmt* getTerminator() { return Terminator; }
405 const Stmt* getTerminator() const { return Terminator; }
407 Stmt* getTerminatorCondition();
409 const Stmt* getTerminatorCondition() const {
410 return const_cast<CFGBlock*>(this)->getTerminatorCondition();
413 const Stmt *getLoopTarget() const { return LoopTarget; }
415 bool hasBinaryBranchTerminator() const;
417 Stmt* getLabel() { return Label; }
418 const Stmt* getLabel() const { return Label; }
420 unsigned getBlockID() const { return BlockID; }
422 void dump(const CFG *cfg, const LangOptions &LO) const;
423 void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
424 void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
426 void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
428 Block->Preds.push_back(this, C);
429 Succs.push_back(Block, C);
432 void appendStmt(Stmt* Statement, BumpVectorContext &C, bool asLValue) {
433 Elements.push_back(CFGStmt(Statement, asLValue), C);
436 // Destructors must be inserted in reversed order. So insertion is in two
437 // steps. First we prepare space for some number of elements, then we insert
438 // the elements beginning at the last position in prepared space.
439 iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
440 BumpVectorContext& C) {
441 return iterator(Elements.insert(I.base(), Cnt, CFGElement(), C));
443 iterator insertAutomaticObjDtor(iterator I, VarDecl* VD, Stmt* S) {
444 *I = CFGAutomaticObjDtor(VD, S);
449 /// CFG - Represents a source-level, intra-procedural CFG that represents the
450 /// control-flow of a Stmt. The Stmt can represent an entire function body,
451 /// or a single expression. A CFG will always contain one empty block that
452 /// represents the Exit point of the CFG. A CFG will also contain a designated
453 /// Entry block. The CFG solely represents control-flow; it consists of
454 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
455 /// was constructed from.
458 //===--------------------------------------------------------------------===//
459 // CFG Construction & Manipulation.
460 //===--------------------------------------------------------------------===//
464 bool PruneTriviallyFalseEdges:1;
466 bool AddInitializers:1;
467 bool AddImplicitDtors:1;
470 : PruneTriviallyFalseEdges(true)
472 , AddInitializers(false)
473 , AddImplicitDtors(false) {}
476 /// buildCFG - Builds a CFG from an AST. The responsibility to free the
477 /// constructed CFG belongs to the caller.
478 static CFG* buildCFG(const Decl *D, Stmt* AST, ASTContext *C,
479 BuildOptions BO = BuildOptions());
481 /// createBlock - Create a new block in the CFG. The CFG owns the block;
482 /// the caller should not directly free it.
483 CFGBlock* createBlock();
485 /// setEntry - Set the entry block of the CFG. This is typically used
486 /// only during CFG construction. Most CFG clients expect that the
487 /// entry block has no predecessors and contains no statements.
488 void setEntry(CFGBlock *B) { Entry = B; }
490 /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
491 /// This is typically used only during CFG construction.
492 void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
494 //===--------------------------------------------------------------------===//
496 //===--------------------------------------------------------------------===//
498 typedef BumpVector<CFGBlock*> CFGBlockListTy;
499 typedef CFGBlockListTy::iterator iterator;
500 typedef CFGBlockListTy::const_iterator const_iterator;
501 typedef std::reverse_iterator<iterator> reverse_iterator;
502 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
504 CFGBlock& front() { return *Blocks.front(); }
505 CFGBlock& back() { return *Blocks.back(); }
507 iterator begin() { return Blocks.begin(); }
508 iterator end() { return Blocks.end(); }
509 const_iterator begin() const { return Blocks.begin(); }
510 const_iterator end() const { return Blocks.end(); }
512 reverse_iterator rbegin() { return Blocks.rbegin(); }
513 reverse_iterator rend() { return Blocks.rend(); }
514 const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
515 const_reverse_iterator rend() const { return Blocks.rend(); }
517 CFGBlock& getEntry() { return *Entry; }
518 const CFGBlock& getEntry() const { return *Entry; }
519 CFGBlock& getExit() { return *Exit; }
520 const CFGBlock& getExit() const { return *Exit; }
522 CFGBlock* getIndirectGotoBlock() { return IndirectGotoBlock; }
523 const CFGBlock* getIndirectGotoBlock() const { return IndirectGotoBlock; }
525 //===--------------------------------------------------------------------===//
526 // Member templates useful for various batch operations over CFGs.
527 //===--------------------------------------------------------------------===//
529 template <typename CALLBACK>
530 void VisitBlockStmts(CALLBACK& O) const {
531 for (const_iterator I=begin(), E=end(); I != E; ++I)
532 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
534 if (CFGStmt S = BI->getAs<CFGStmt>())
539 //===--------------------------------------------------------------------===//
540 // CFG Introspection.
541 //===--------------------------------------------------------------------===//
543 struct BlkExprNumTy {
545 explicit BlkExprNumTy(signed idx) : Idx(idx) {}
546 explicit BlkExprNumTy() : Idx(-1) {}
547 operator bool() const { return Idx >= 0; }
548 operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
551 bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
552 BlkExprNumTy getBlkExprNum(const Stmt* S);
553 unsigned getNumBlkExprs();
555 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
557 unsigned getNumBlockIDs() const { return NumBlockIDs; }
559 //===--------------------------------------------------------------------===//
560 // CFG Debugging: Pretty-Printing and Visualization.
561 //===--------------------------------------------------------------------===//
563 void viewCFG(const LangOptions &LO) const;
564 void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
565 void dump(const LangOptions &LO) const;
567 //===--------------------------------------------------------------------===//
568 // Internal: constructors and data.
569 //===--------------------------------------------------------------------===//
571 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
572 BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
576 llvm::BumpPtrAllocator& getAllocator() {
577 return BlkBVC.getAllocator();
580 BumpVectorContext &getBumpVectorContext() {
587 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
588 // for indirect gotos
589 unsigned NumBlockIDs;
591 // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
592 // It represents a map from Expr* to integers to record the set of
593 // block-level expressions and their "statement number" in the CFG.
596 BumpVectorContext BlkBVC;
598 CFGBlockListTy Blocks;
601 } // end namespace clang
603 //===----------------------------------------------------------------------===//
604 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
605 //===----------------------------------------------------------------------===//
609 // Traits for: CFGBlock
611 template <> struct GraphTraits< ::clang::CFGBlock* > {
612 typedef ::clang::CFGBlock NodeType;
613 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
615 static NodeType* getEntryNode(::clang::CFGBlock* BB)
618 static inline ChildIteratorType child_begin(NodeType* N)
619 { return N->succ_begin(); }
621 static inline ChildIteratorType child_end(NodeType* N)
622 { return N->succ_end(); }
625 template <> struct GraphTraits< const ::clang::CFGBlock* > {
626 typedef const ::clang::CFGBlock NodeType;
627 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
629 static NodeType* getEntryNode(const clang::CFGBlock* BB)
632 static inline ChildIteratorType child_begin(NodeType* N)
633 { return N->succ_begin(); }
635 static inline ChildIteratorType child_end(NodeType* N)
636 { return N->succ_end(); }
639 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
640 typedef const ::clang::CFGBlock NodeType;
641 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
643 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
646 static inline ChildIteratorType child_begin(NodeType* N)
647 { return N->pred_begin(); }
649 static inline ChildIteratorType child_end(NodeType* N)
650 { return N->pred_end(); }
655 template <> struct GraphTraits< ::clang::CFG* >
656 : public GraphTraits< ::clang::CFGBlock* > {
658 typedef ::clang::CFG::iterator nodes_iterator;
660 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
661 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
662 static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
665 template <> struct GraphTraits<const ::clang::CFG* >
666 : public GraphTraits<const ::clang::CFGBlock* > {
668 typedef ::clang::CFG::const_iterator nodes_iterator;
670 static NodeType *getEntryNode( const ::clang::CFG* F) {
671 return &F->getEntry();
673 static nodes_iterator nodes_begin( const ::clang::CFG* F) {
676 static nodes_iterator nodes_end( const ::clang::CFG* F) {
681 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
682 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
684 typedef ::clang::CFG::const_iterator nodes_iterator;
686 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
687 static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
688 static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
690 } // end llvm namespace