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 "clang/AST/Stmt.h" 19 #include "clang/Analysis/Support/BumpVector.h" 20 #include "clang/Basic/SourceLocation.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/GraphTraits.h" 23 #include "llvm/ADT/Optional.h" 24 #include "llvm/ADT/OwningPtr.h" 25 #include "llvm/ADT/PointerIntPair.h" 26 #include "llvm/Support/Allocator.h" 27 #include "llvm/Support/Casting.h" 28 #include <bitset> 29 #include <cassert> 30 #include <iterator> 31 32 namespace clang { 33 class CXXDestructorDecl; 34 class Decl; 35 class Stmt; 36 class Expr; 37 class FieldDecl; 38 class VarDecl; 39 class CXXCtorInitializer; 40 class CXXBaseSpecifier; 41 class CXXBindTemporaryExpr; 42 class CFG; 43 class PrinterHelper; 44 class LangOptions; 45 class ASTContext; 46 47 /// CFGElement - Represents a top-level expression in a basic block. 48 class CFGElement { 49 public: 50 enum Kind { 51 // main kind 52 Statement, 53 Initializer, 54 // dtor kind 55 AutomaticObjectDtor, 56 BaseDtor, 57 MemberDtor, 58 TemporaryDtor, 59 DTOR_BEGIN = AutomaticObjectDtor, 60 DTOR_END = TemporaryDtor 61 }; 62 63 protected: 64 // The int bits are used to mark the kind. 65 llvm::PointerIntPair<void *, 2> Data1; 66 llvm::PointerIntPair<void *, 2> Data2; 67 68 CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = 0) 69 : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3), 70 Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {} 71 72 CFGElement() {} 73 public: 74 75 /// \brief Convert to the specified CFGElement type, asserting that this 76 /// CFGElement is of the desired type. 77 template<typename T> 78 T castAs() const { 79 assert(T::isKind(*this)); 80 T t; 81 CFGElement& e = t; 82 e = *this; 83 return t; 84 } 85 86 /// \brief Convert to the specified CFGElement type, returning None if this 87 /// CFGElement is not of the desired type. 88 template<typename T> 89 Optional<T> getAs() const { 90 if (!T::isKind(*this)) 91 return None; 92 T t; 93 CFGElement& e = t; 94 e = *this; 95 return t; 96 } 97 98 Kind getKind() const { 99 unsigned x = Data2.getInt(); 100 x <<= 2; 101 x |= Data1.getInt(); 102 return (Kind) x; 103 } 104 }; 105 106 class CFGStmt : public CFGElement { 107 public: 108 CFGStmt(Stmt *S) : CFGElement(Statement, S) {} 109 110 const Stmt *getStmt() const { 111 return static_cast<const Stmt *>(Data1.getPointer()); 112 } 113 114 private: 115 friend class CFGElement; 116 CFGStmt() {} 117 static bool isKind(const CFGElement &E) { 118 return E.getKind() == Statement; 119 } 120 }; 121 122 /// CFGInitializer - Represents C++ base or member initializer from 123 /// constructor's initialization list. 124 class CFGInitializer : public CFGElement { 125 public: 126 CFGInitializer(CXXCtorInitializer *initializer) 127 : CFGElement(Initializer, initializer) {} 128 129 CXXCtorInitializer* getInitializer() const { 130 return static_cast<CXXCtorInitializer*>(Data1.getPointer()); 131 } 132 133 private: 134 friend class CFGElement; 135 CFGInitializer() {} 136 static bool isKind(const CFGElement &E) { 137 return E.getKind() == Initializer; 138 } 139 }; 140 141 /// CFGImplicitDtor - Represents C++ object destructor implicitly generated 142 /// by compiler on various occasions. 143 class CFGImplicitDtor : public CFGElement { 144 protected: 145 CFGImplicitDtor() {} 146 CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = 0) 147 : CFGElement(kind, data1, data2) { 148 assert(kind >= DTOR_BEGIN && kind <= DTOR_END); 149 } 150 151 public: 152 const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const; 153 bool isNoReturn(ASTContext &astContext) const; 154 155 private: 156 friend class CFGElement; 157 static bool isKind(const CFGElement &E) { 158 Kind kind = E.getKind(); 159 return kind >= DTOR_BEGIN && kind <= DTOR_END; 160 } 161 }; 162 163 /// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated 164 /// for automatic object or temporary bound to const reference at the point 165 /// of leaving its local scope. 166 class CFGAutomaticObjDtor: public CFGImplicitDtor { 167 public: 168 CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt) 169 : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {} 170 171 const VarDecl *getVarDecl() const { 172 return static_cast<VarDecl*>(Data1.getPointer()); 173 } 174 175 // Get statement end of which triggered the destructor call. 176 const Stmt *getTriggerStmt() const { 177 return static_cast<Stmt*>(Data2.getPointer()); 178 } 179 180 private: 181 friend class CFGElement; 182 CFGAutomaticObjDtor() {} 183 static bool isKind(const CFGElement &elem) { 184 return elem.getKind() == AutomaticObjectDtor; 185 } 186 }; 187 188 /// CFGBaseDtor - Represents C++ object destructor implicitly generated for 189 /// base object in destructor. 190 class CFGBaseDtor : public CFGImplicitDtor { 191 public: 192 CFGBaseDtor(const CXXBaseSpecifier *base) 193 : CFGImplicitDtor(BaseDtor, base) {} 194 195 const CXXBaseSpecifier *getBaseSpecifier() const { 196 return static_cast<const CXXBaseSpecifier*>(Data1.getPointer()); 197 } 198 199 private: 200 friend class CFGElement; 201 CFGBaseDtor() {} 202 static bool isKind(const CFGElement &E) { 203 return E.getKind() == BaseDtor; 204 } 205 }; 206 207 /// CFGMemberDtor - Represents C++ object destructor implicitly generated for 208 /// member object in destructor. 209 class CFGMemberDtor : public CFGImplicitDtor { 210 public: 211 CFGMemberDtor(const FieldDecl *field) 212 : CFGImplicitDtor(MemberDtor, field, 0) {} 213 214 const FieldDecl *getFieldDecl() const { 215 return static_cast<const FieldDecl*>(Data1.getPointer()); 216 } 217 218 private: 219 friend class CFGElement; 220 CFGMemberDtor() {} 221 static bool isKind(const CFGElement &E) { 222 return E.getKind() == MemberDtor; 223 } 224 }; 225 226 /// CFGTemporaryDtor - Represents C++ object destructor implicitly generated 227 /// at the end of full expression for temporary object. 228 class CFGTemporaryDtor : public CFGImplicitDtor { 229 public: 230 CFGTemporaryDtor(CXXBindTemporaryExpr *expr) 231 : CFGImplicitDtor(TemporaryDtor, expr, 0) {} 232 233 const CXXBindTemporaryExpr *getBindTemporaryExpr() const { 234 return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer()); 235 } 236 237 private: 238 friend class CFGElement; 239 CFGTemporaryDtor() {} 240 static bool isKind(const CFGElement &E) { 241 return E.getKind() == TemporaryDtor; 242 } 243 }; 244 245 /// CFGTerminator - Represents CFGBlock terminator statement. 246 /// 247 /// TemporaryDtorsBranch bit is set to true if the terminator marks a branch 248 /// in control flow of destructors of temporaries. In this case terminator 249 /// statement is the same statement that branches control flow in evaluation 250 /// of matching full expression. 251 class CFGTerminator { 252 llvm::PointerIntPair<Stmt *, 1> Data; 253 public: 254 CFGTerminator() {} 255 CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false) 256 : Data(S, TemporaryDtorsBranch) {} 257 258 Stmt *getStmt() { return Data.getPointer(); } 259 const Stmt *getStmt() const { return Data.getPointer(); } 260 261 bool isTemporaryDtorsBranch() const { return Data.getInt(); } 262 263 operator Stmt *() { return getStmt(); } 264 operator const Stmt *() const { return getStmt(); } 265 266 Stmt *operator->() { return getStmt(); } 267 const Stmt *operator->() const { return getStmt(); } 268 269 Stmt &operator*() { return *getStmt(); } 270 const Stmt &operator*() const { return *getStmt(); } 271 272 LLVM_EXPLICIT operator bool() const { return getStmt(); } 273 }; 274 275 /// CFGBlock - Represents a single basic block in a source-level CFG. 276 /// It consists of: 277 /// 278 /// (1) A set of statements/expressions (which may contain subexpressions). 279 /// (2) A "terminator" statement (not in the set of statements). 280 /// (3) A list of successors and predecessors. 281 /// 282 /// Terminator: The terminator represents the type of control-flow that occurs 283 /// at the end of the basic block. The terminator is a Stmt* referring to an 284 /// AST node that has control-flow: if-statements, breaks, loops, etc. 285 /// If the control-flow is conditional, the condition expression will appear 286 /// within the set of statements in the block (usually the last statement). 287 /// 288 /// Predecessors: the order in the set of predecessors is arbitrary. 289 /// 290 /// Successors: the order in the set of successors is NOT arbitrary. We 291 /// currently have the following orderings based on the terminator: 292 /// 293 /// Terminator Successor Ordering 294 /// ----------------------------------------------------- 295 /// if Then Block; Else Block 296 /// ? operator LHS expression; RHS expression 297 /// &&, || expression that uses result of && or ||, RHS 298 /// 299 /// But note that any of that may be NULL in case of optimized-out edges. 300 /// 301 class CFGBlock { 302 class ElementList { 303 typedef BumpVector<CFGElement> ImplTy; 304 ImplTy Impl; 305 public: 306 ElementList(BumpVectorContext &C) : Impl(C, 4) {} 307 308 typedef std::reverse_iterator<ImplTy::iterator> iterator; 309 typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator; 310 typedef ImplTy::iterator reverse_iterator; 311 typedef ImplTy::const_iterator const_reverse_iterator; 312 typedef ImplTy::const_reference const_reference; 313 314 void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); } 315 reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E, 316 BumpVectorContext &C) { 317 return Impl.insert(I, Cnt, E, C); 318 } 319 320 const_reference front() const { return Impl.back(); } 321 const_reference back() const { return Impl.front(); } 322 323 iterator begin() { return Impl.rbegin(); } 324 iterator end() { return Impl.rend(); } 325 const_iterator begin() const { return Impl.rbegin(); } 326 const_iterator end() const { return Impl.rend(); } 327 reverse_iterator rbegin() { return Impl.begin(); } 328 reverse_iterator rend() { return Impl.end(); } 329 const_reverse_iterator rbegin() const { return Impl.begin(); } 330 const_reverse_iterator rend() const { return Impl.end(); } 331 332 CFGElement operator[](size_t i) const { 333 assert(i < Impl.size()); 334 return Impl[Impl.size() - 1 - i]; 335 } 336 337 size_t size() const { return Impl.size(); } 338 bool empty() const { return Impl.empty(); } 339 }; 340 341 /// Stmts - The set of statements in the basic block. 342 ElementList Elements; 343 344 /// Label - An (optional) label that prefixes the executable 345 /// statements in the block. When this variable is non-NULL, it is 346 /// either an instance of LabelStmt, SwitchCase or CXXCatchStmt. 347 Stmt *Label; 348 349 /// Terminator - The terminator for a basic block that 350 /// indicates the type of control-flow that occurs between a block 351 /// and its successors. 352 CFGTerminator Terminator; 353 354 /// LoopTarget - Some blocks are used to represent the "loop edge" to 355 /// the start of a loop from within the loop body. This Stmt* will be 356 /// refer to the loop statement for such blocks (and be null otherwise). 357 const Stmt *LoopTarget; 358 359 /// BlockID - A numerical ID assigned to a CFGBlock during construction 360 /// of the CFG. 361 unsigned BlockID; 362 363 /// Predecessors/Successors - Keep track of the predecessor / successor 364 /// CFG blocks. 365 typedef BumpVector<CFGBlock*> AdjacentBlocks; 366 AdjacentBlocks Preds; 367 AdjacentBlocks Succs; 368 369 /// NoReturn - This bit is set when the basic block contains a function call 370 /// or implicit destructor that is attributed as 'noreturn'. In that case, 371 /// control cannot technically ever proceed past this block. All such blocks 372 /// will have a single immediate successor: the exit block. This allows them 373 /// to be easily reached from the exit block and using this bit quickly 374 /// recognized without scanning the contents of the block. 375 /// 376 /// Optimization Note: This bit could be profitably folded with Terminator's 377 /// storage if the memory usage of CFGBlock becomes an issue. 378 unsigned HasNoReturnElement : 1; 379 380 /// Parent - The parent CFG that owns this CFGBlock. 381 CFG *Parent; 382 383 public: 384 explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent) 385 : Elements(C), Label(NULL), Terminator(NULL), LoopTarget(NULL), 386 BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false), 387 Parent(parent) {} 388 ~CFGBlock() {} 389 390 // Statement iterators 391 typedef ElementList::iterator iterator; 392 typedef ElementList::const_iterator const_iterator; 393 typedef ElementList::reverse_iterator reverse_iterator; 394 typedef ElementList::const_reverse_iterator const_reverse_iterator; 395 396 CFGElement front() const { return Elements.front(); } 397 CFGElement back() const { return Elements.back(); } 398 399 iterator begin() { return Elements.begin(); } 400 iterator end() { return Elements.end(); } 401 const_iterator begin() const { return Elements.begin(); } 402 const_iterator end() const { return Elements.end(); } 403 404 reverse_iterator rbegin() { return Elements.rbegin(); } 405 reverse_iterator rend() { return Elements.rend(); } 406 const_reverse_iterator rbegin() const { return Elements.rbegin(); } 407 const_reverse_iterator rend() const { return Elements.rend(); } 408 409 unsigned size() const { return Elements.size(); } 410 bool empty() const { return Elements.empty(); } 411 412 CFGElement operator[](size_t i) const { return Elements[i]; } 413 414 // CFG iterators 415 typedef AdjacentBlocks::iterator pred_iterator; 416 typedef AdjacentBlocks::const_iterator const_pred_iterator; 417 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator; 418 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator; 419 420 typedef AdjacentBlocks::iterator succ_iterator; 421 typedef AdjacentBlocks::const_iterator const_succ_iterator; 422 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator; 423 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator; 424 425 pred_iterator pred_begin() { return Preds.begin(); } 426 pred_iterator pred_end() { return Preds.end(); } 427 const_pred_iterator pred_begin() const { return Preds.begin(); } 428 const_pred_iterator pred_end() const { return Preds.end(); } 429 430 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); } 431 pred_reverse_iterator pred_rend() { return Preds.rend(); } 432 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); } 433 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); } 434 435 succ_iterator succ_begin() { return Succs.begin(); } 436 succ_iterator succ_end() { return Succs.end(); } 437 const_succ_iterator succ_begin() const { return Succs.begin(); } 438 const_succ_iterator succ_end() const { return Succs.end(); } 439 440 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); } 441 succ_reverse_iterator succ_rend() { return Succs.rend(); } 442 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); } 443 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); } 444 445 unsigned succ_size() const { return Succs.size(); } 446 bool succ_empty() const { return Succs.empty(); } 447 448 unsigned pred_size() const { return Preds.size(); } 449 bool pred_empty() const { return Preds.empty(); } 450 451 452 class FilterOptions { 453 public: 454 FilterOptions() { 455 IgnoreDefaultsWithCoveredEnums = 0; 456 } 457 458 unsigned IgnoreDefaultsWithCoveredEnums : 1; 459 }; 460 461 static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src, 462 const CFGBlock *Dst); 463 464 template <typename IMPL, bool IsPred> 465 class FilteredCFGBlockIterator { 466 private: 467 IMPL I, E; 468 const FilterOptions F; 469 const CFGBlock *From; 470 public: 471 explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e, 472 const CFGBlock *from, 473 const FilterOptions &f) 474 : I(i), E(e), F(f), From(from) {} 475 476 bool hasMore() const { return I != E; } 477 478 FilteredCFGBlockIterator &operator++() { 479 do { ++I; } while (hasMore() && Filter(*I)); 480 return *this; 481 } 482 483 const CFGBlock *operator*() const { return *I; } 484 private: 485 bool Filter(const CFGBlock *To) { 486 return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To); 487 } 488 }; 489 490 typedef FilteredCFGBlockIterator<const_pred_iterator, true> 491 filtered_pred_iterator; 492 493 typedef FilteredCFGBlockIterator<const_succ_iterator, false> 494 filtered_succ_iterator; 495 496 filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const { 497 return filtered_pred_iterator(pred_begin(), pred_end(), this, f); 498 } 499 500 filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const { 501 return filtered_succ_iterator(succ_begin(), succ_end(), this, f); 502 } 503 504 // Manipulation of block contents 505 506 void setTerminator(Stmt *Statement) { Terminator = Statement; } 507 void setLabel(Stmt *Statement) { Label = Statement; } 508 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; } 509 void setHasNoReturnElement() { HasNoReturnElement = true; } 510 511 CFGTerminator getTerminator() { return Terminator; } 512 const CFGTerminator getTerminator() const { return Terminator; } 513 514 Stmt *getTerminatorCondition(); 515 516 const Stmt *getTerminatorCondition() const { 517 return const_cast<CFGBlock*>(this)->getTerminatorCondition(); 518 } 519 520 const Stmt *getLoopTarget() const { return LoopTarget; } 521 522 Stmt *getLabel() { return Label; } 523 const Stmt *getLabel() const { return Label; } 524 525 bool hasNoReturnElement() const { return HasNoReturnElement; } 526 527 unsigned getBlockID() const { return BlockID; } 528 529 CFG *getParent() const { return Parent; } 530 531 void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const; 532 void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO, 533 bool ShowColors) const; 534 void printTerminator(raw_ostream &OS, const LangOptions &LO) const; 535 536 void addSuccessor(CFGBlock *Block, BumpVectorContext &C) { 537 if (Block) 538 Block->Preds.push_back(this, C); 539 Succs.push_back(Block, C); 540 } 541 542 void appendStmt(Stmt *statement, BumpVectorContext &C) { 543 Elements.push_back(CFGStmt(statement), C); 544 } 545 546 void appendInitializer(CXXCtorInitializer *initializer, 547 BumpVectorContext &C) { 548 Elements.push_back(CFGInitializer(initializer), C); 549 } 550 551 void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) { 552 Elements.push_back(CFGBaseDtor(BS), C); 553 } 554 555 void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) { 556 Elements.push_back(CFGMemberDtor(FD), C); 557 } 558 559 void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) { 560 Elements.push_back(CFGTemporaryDtor(E), C); 561 } 562 563 void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) { 564 Elements.push_back(CFGAutomaticObjDtor(VD, S), C); 565 } 566 567 // Destructors must be inserted in reversed order. So insertion is in two 568 // steps. First we prepare space for some number of elements, then we insert 569 // the elements beginning at the last position in prepared space. 570 iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt, 571 BumpVectorContext &C) { 572 return iterator(Elements.insert(I.base(), Cnt, CFGAutomaticObjDtor(0, 0), C)); 573 } 574 iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) { 575 *I = CFGAutomaticObjDtor(VD, S); 576 return ++I; 577 } 578 }; 579 580 /// CFG - Represents a source-level, intra-procedural CFG that represents the 581 /// control-flow of a Stmt. The Stmt can represent an entire function body, 582 /// or a single expression. A CFG will always contain one empty block that 583 /// represents the Exit point of the CFG. A CFG will also contain a designated 584 /// Entry block. The CFG solely represents control-flow; it consists of 585 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG 586 /// was constructed from. 587 class CFG { 588 public: 589 //===--------------------------------------------------------------------===// 590 // CFG Construction & Manipulation. 591 //===--------------------------------------------------------------------===// 592 593 class BuildOptions { 594 std::bitset<Stmt::lastStmtConstant> alwaysAddMask; 595 public: 596 typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs; 597 ForcedBlkExprs **forcedBlkExprs; 598 599 bool PruneTriviallyFalseEdges; 600 bool AddEHEdges; 601 bool AddInitializers; 602 bool AddImplicitDtors; 603 bool AddTemporaryDtors; 604 bool AddStaticInitBranches; 605 606 bool alwaysAdd(const Stmt *stmt) const { 607 return alwaysAddMask[stmt->getStmtClass()]; 608 } 609 610 BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) { 611 alwaysAddMask[stmtClass] = val; 612 return *this; 613 } 614 615 BuildOptions &setAllAlwaysAdd() { 616 alwaysAddMask.set(); 617 return *this; 618 } 619 620 BuildOptions() 621 : forcedBlkExprs(0), PruneTriviallyFalseEdges(true) 622 ,AddEHEdges(false) 623 ,AddInitializers(false) 624 ,AddImplicitDtors(false) 625 ,AddTemporaryDtors(false) 626 ,AddStaticInitBranches(false) {} 627 }; 628 629 /// \brief Provides a custom implementation of the iterator class to have the 630 /// same interface as Function::iterator - iterator returns CFGBlock 631 /// (not a pointer to CFGBlock). 632 class graph_iterator { 633 public: 634 typedef const CFGBlock value_type; 635 typedef value_type& reference; 636 typedef value_type* pointer; 637 typedef BumpVector<CFGBlock*>::iterator ImplTy; 638 639 graph_iterator(const ImplTy &i) : I(i) {} 640 641 bool operator==(const graph_iterator &X) const { return I == X.I; } 642 bool operator!=(const graph_iterator &X) const { return I != X.I; } 643 644 reference operator*() const { return **I; } 645 pointer operator->() const { return *I; } 646 operator CFGBlock* () { return *I; } 647 648 graph_iterator &operator++() { ++I; return *this; } 649 graph_iterator &operator--() { --I; return *this; } 650 651 private: 652 ImplTy I; 653 }; 654 655 class const_graph_iterator { 656 public: 657 typedef const CFGBlock value_type; 658 typedef value_type& reference; 659 typedef value_type* pointer; 660 typedef BumpVector<CFGBlock*>::const_iterator ImplTy; 661 662 const_graph_iterator(const ImplTy &i) : I(i) {} 663 664 bool operator==(const const_graph_iterator &X) const { return I == X.I; } 665 bool operator!=(const const_graph_iterator &X) const { return I != X.I; } 666 667 reference operator*() const { return **I; } 668 pointer operator->() const { return *I; } 669 operator CFGBlock* () const { return *I; } 670 671 const_graph_iterator &operator++() { ++I; return *this; } 672 const_graph_iterator &operator--() { --I; return *this; } 673 674 private: 675 ImplTy I; 676 }; 677 678 /// buildCFG - Builds a CFG from an AST. The responsibility to free the 679 /// constructed CFG belongs to the caller. 680 static CFG* buildCFG(const Decl *D, Stmt *AST, ASTContext *C, 681 const BuildOptions &BO); 682 683 /// createBlock - Create a new block in the CFG. The CFG owns the block; 684 /// the caller should not directly free it. 685 CFGBlock *createBlock(); 686 687 /// setEntry - Set the entry block of the CFG. This is typically used 688 /// only during CFG construction. Most CFG clients expect that the 689 /// entry block has no predecessors and contains no statements. 690 void setEntry(CFGBlock *B) { Entry = B; } 691 692 /// setIndirectGotoBlock - Set the block used for indirect goto jumps. 693 /// This is typically used only during CFG construction. 694 void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; } 695 696 //===--------------------------------------------------------------------===// 697 // Block Iterators 698 //===--------------------------------------------------------------------===// 699 700 typedef BumpVector<CFGBlock*> CFGBlockListTy; 701 typedef CFGBlockListTy::iterator iterator; 702 typedef CFGBlockListTy::const_iterator const_iterator; 703 typedef std::reverse_iterator<iterator> reverse_iterator; 704 typedef std::reverse_iterator<const_iterator> const_reverse_iterator; 705 706 CFGBlock & front() { return *Blocks.front(); } 707 CFGBlock & back() { return *Blocks.back(); } 708 709 iterator begin() { return Blocks.begin(); } 710 iterator end() { return Blocks.end(); } 711 const_iterator begin() const { return Blocks.begin(); } 712 const_iterator end() const { return Blocks.end(); } 713 714 graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); } 715 graph_iterator nodes_end() { return graph_iterator(Blocks.end()); } 716 const_graph_iterator nodes_begin() const { 717 return const_graph_iterator(Blocks.begin()); 718 } 719 const_graph_iterator nodes_end() const { 720 return const_graph_iterator(Blocks.end()); 721 } 722 723 reverse_iterator rbegin() { return Blocks.rbegin(); } 724 reverse_iterator rend() { return Blocks.rend(); } 725 const_reverse_iterator rbegin() const { return Blocks.rbegin(); } 726 const_reverse_iterator rend() const { return Blocks.rend(); } 727 728 CFGBlock & getEntry() { return *Entry; } 729 const CFGBlock & getEntry() const { return *Entry; } 730 CFGBlock & getExit() { return *Exit; } 731 const CFGBlock & getExit() const { return *Exit; } 732 733 CFGBlock * getIndirectGotoBlock() { return IndirectGotoBlock; } 734 const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; } 735 736 typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator; 737 try_block_iterator try_blocks_begin() const { 738 return TryDispatchBlocks.begin(); 739 } 740 try_block_iterator try_blocks_end() const { 741 return TryDispatchBlocks.end(); 742 } 743 744 void addTryDispatchBlock(const CFGBlock *block) { 745 TryDispatchBlocks.push_back(block); 746 } 747 748 /// Records a synthetic DeclStmt and the DeclStmt it was constructed from. 749 /// 750 /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains 751 /// multiple decls. 752 void addSyntheticDeclStmt(const DeclStmt *Synthetic, 753 const DeclStmt *Source) { 754 assert(Synthetic->isSingleDecl() && "Can handle single declarations only"); 755 assert(Synthetic != Source && "Don't include original DeclStmts in map"); 756 assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map"); 757 SyntheticDeclStmts[Synthetic] = Source; 758 } 759 760 typedef llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator 761 synthetic_stmt_iterator; 762 763 /// Iterates over synthetic DeclStmts in the CFG. 764 /// 765 /// Each element is a (synthetic statement, source statement) pair. 766 /// 767 /// \sa addSyntheticDeclStmt 768 synthetic_stmt_iterator synthetic_stmt_begin() const { 769 return SyntheticDeclStmts.begin(); 770 } 771 772 /// \sa synthetic_stmt_begin 773 synthetic_stmt_iterator synthetic_stmt_end() const { 774 return SyntheticDeclStmts.end(); 775 } 776 777 //===--------------------------------------------------------------------===// 778 // Member templates useful for various batch operations over CFGs. 779 //===--------------------------------------------------------------------===// 780 781 template <typename CALLBACK> 782 void VisitBlockStmts(CALLBACK& O) const { 783 for (const_iterator I=begin(), E=end(); I != E; ++I) 784 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end(); 785 BI != BE; ++BI) { 786 if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>()) 787 O(const_cast<Stmt*>(stmt->getStmt())); 788 } 789 } 790 791 //===--------------------------------------------------------------------===// 792 // CFG Introspection. 793 //===--------------------------------------------------------------------===// 794 795 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which 796 /// start at 0). 797 unsigned getNumBlockIDs() const { return NumBlockIDs; } 798 799 /// size - Return the total number of CFGBlocks within the CFG 800 /// This is simply a renaming of the getNumBlockIDs(). This is necessary 801 /// because the dominator implementation needs such an interface. 802 unsigned size() const { return NumBlockIDs; } 803 804 //===--------------------------------------------------------------------===// 805 // CFG Debugging: Pretty-Printing and Visualization. 806 //===--------------------------------------------------------------------===// 807 808 void viewCFG(const LangOptions &LO) const; 809 void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const; 810 void dump(const LangOptions &LO, bool ShowColors) const; 811 812 //===--------------------------------------------------------------------===// 813 // Internal: constructors and data. 814 //===--------------------------------------------------------------------===// 815 816 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0), 817 Blocks(BlkBVC, 10) {} 818 819 llvm::BumpPtrAllocator& getAllocator() { 820 return BlkBVC.getAllocator(); 821 } 822 823 BumpVectorContext &getBumpVectorContext() { 824 return BlkBVC; 825 } 826 827 private: 828 CFGBlock *Entry; 829 CFGBlock *Exit; 830 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch 831 // for indirect gotos 832 unsigned NumBlockIDs; 833 834 BumpVectorContext BlkBVC; 835 836 CFGBlockListTy Blocks; 837 838 /// C++ 'try' statements are modeled with an indirect dispatch block. 839 /// This is the collection of such blocks present in the CFG. 840 std::vector<const CFGBlock *> TryDispatchBlocks; 841 842 /// Collects DeclStmts synthesized for this CFG and maps each one back to its 843 /// source DeclStmt. 844 llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts; 845 }; 846 } // end namespace clang 847 848 //===----------------------------------------------------------------------===// 849 // GraphTraits specializations for CFG basic block graphs (source-level CFGs) 850 //===----------------------------------------------------------------------===// 851 852 namespace llvm { 853 854 /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from 855 /// CFGTerminator to a specific Stmt class. 856 template <> struct simplify_type< ::clang::CFGTerminator> { 857 typedef ::clang::Stmt *SimpleType; 858 static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) { 859 return Val.getStmt(); 860 } 861 }; 862 863 // Traits for: CFGBlock 864 865 template <> struct GraphTraits< ::clang::CFGBlock *> { 866 typedef ::clang::CFGBlock NodeType; 867 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType; 868 869 static NodeType* getEntryNode(::clang::CFGBlock *BB) 870 { return BB; } 871 872 static inline ChildIteratorType child_begin(NodeType* N) 873 { return N->succ_begin(); } 874 875 static inline ChildIteratorType child_end(NodeType* N) 876 { return N->succ_end(); } 877 }; 878 879 template <> struct GraphTraits< const ::clang::CFGBlock *> { 880 typedef const ::clang::CFGBlock NodeType; 881 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType; 882 883 static NodeType* getEntryNode(const clang::CFGBlock *BB) 884 { return BB; } 885 886 static inline ChildIteratorType child_begin(NodeType* N) 887 { return N->succ_begin(); } 888 889 static inline ChildIteratorType child_end(NodeType* N) 890 { return N->succ_end(); } 891 }; 892 893 template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > { 894 typedef ::clang::CFGBlock NodeType; 895 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType; 896 897 static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G) 898 { return G.Graph; } 899 900 static inline ChildIteratorType child_begin(NodeType* N) 901 { return N->pred_begin(); } 902 903 static inline ChildIteratorType child_end(NodeType* N) 904 { return N->pred_end(); } 905 }; 906 907 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > { 908 typedef const ::clang::CFGBlock NodeType; 909 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType; 910 911 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G) 912 { return G.Graph; } 913 914 static inline ChildIteratorType child_begin(NodeType* N) 915 { return N->pred_begin(); } 916 917 static inline ChildIteratorType child_end(NodeType* N) 918 { return N->pred_end(); } 919 }; 920 921 // Traits for: CFG 922 923 template <> struct GraphTraits< ::clang::CFG* > 924 : public GraphTraits< ::clang::CFGBlock *> { 925 926 typedef ::clang::CFG::graph_iterator nodes_iterator; 927 928 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); } 929 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();} 930 static nodes_iterator nodes_end(::clang::CFG* F) { return F->nodes_end(); } 931 static unsigned size(::clang::CFG* F) { return F->size(); } 932 }; 933 934 template <> struct GraphTraits<const ::clang::CFG* > 935 : public GraphTraits<const ::clang::CFGBlock *> { 936 937 typedef ::clang::CFG::const_graph_iterator nodes_iterator; 938 939 static NodeType *getEntryNode( const ::clang::CFG* F) { 940 return &F->getEntry(); 941 } 942 static nodes_iterator nodes_begin( const ::clang::CFG* F) { 943 return F->nodes_begin(); 944 } 945 static nodes_iterator nodes_end( const ::clang::CFG* F) { 946 return F->nodes_end(); 947 } 948 static unsigned size(const ::clang::CFG* F) { 949 return F->size(); 950 } 951 }; 952 953 template <> struct GraphTraits<Inverse< ::clang::CFG*> > 954 : public GraphTraits<Inverse< ::clang::CFGBlock*> > { 955 956 typedef ::clang::CFG::graph_iterator nodes_iterator; 957 958 static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); } 959 static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();} 960 static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); } 961 }; 962 963 template <> struct GraphTraits<Inverse<const ::clang::CFG*> > 964 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > { 965 966 typedef ::clang::CFG::const_graph_iterator nodes_iterator; 967 968 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); } 969 static nodes_iterator nodes_begin(const ::clang::CFG* F) { 970 return F->nodes_begin(); 971 } 972 static nodes_iterator nodes_end(const ::clang::CFG* F) { 973 return F->nodes_end(); 974 } 975 }; 976 } // end llvm namespace 977 #endif 978