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