CFG.cpp revision 971b75de8647f4bbce6b7580899eb0e222453409
1//===--- CFG.cpp - 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#include "clang/Analysis/Support/SaveAndRestore.h" 16#include "clang/Analysis/CFG.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/AST/PrettyPrinter.h" 20#include "llvm/Support/GraphWriter.h" 21#include "llvm/Support/Allocator.h" 22#include "llvm/Support/Format.h" 23#include "llvm/ADT/DenseMap.h" 24#include "llvm/ADT/SmallPtrSet.h" 25#include "llvm/ADT/OwningPtr.h" 26 27using namespace clang; 28 29namespace { 30 31static SourceLocation GetEndLoc(Decl* D) { 32 if (VarDecl* VD = dyn_cast<VarDecl>(D)) 33 if (Expr* Ex = VD->getInit()) 34 return Ex->getSourceRange().getEnd(); 35 36 return D->getLocation(); 37} 38 39class AddStmtChoice { 40public: 41 enum Kind { NotAlwaysAdd = 0, 42 AlwaysAdd = 1, 43 AsLValueNotAlwaysAdd = 2, 44 AlwaysAddAsLValue = 3 }; 45 46 AddStmtChoice(Kind kind) : k(kind) {} 47 48 bool alwaysAdd() const { return (unsigned)k & 0x1; } 49 bool asLValue() const { return k >= AsLValueNotAlwaysAdd; } 50 51private: 52 Kind k; 53}; 54 55/// LocalScope - Node in tree of local scopes created for C++ implicit 56/// destructor calls generation. It contains list of automatic variables 57/// declared in the scope and link to position in previous scope this scope 58/// began in. 59/// 60/// The process of creating local scopes is as follows: 61/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 62/// - Before processing statements in scope (e.g. CompoundStmt) create 63/// LocalScope object using CFGBuilder::ScopePos as link to previous scope 64/// and set CFGBuilder::ScopePos to the end of new scope, 65/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 66/// at this VarDecl, 67/// - For every normal (without jump) end of scope add to CFGBlock destructors 68/// for objects in the current scope, 69/// - For every jump add to CFGBlock destructors for objects 70/// between CFGBuilder::ScopePos and local scope position saved for jump 71/// target. Thanks to C++ restrictions on goto jumps we can be sure that 72/// jump target position will be on the path to root from CFGBuilder::ScopePos 73/// (adding any variable that doesn't need constructor to be called to 74/// LocalScope can break this assumption), 75/// 76class LocalScope { 77public: 78 typedef llvm::SmallVector<VarDecl*, 4> AutomaticVarsTy; 79 80 /// const_iterator - Iterates local scope backwards and jumps to previous 81 /// scope on reaching the beginning of currently iterated scope. 82 class const_iterator { 83 const LocalScope* Scope; 84 85 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 86 /// Invalid iterator (with null Scope) has VarIter equal to 0. 87 unsigned VarIter; 88 89 public: 90 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 91 /// Incrementing invalid iterator is allowed and will result in invalid 92 /// iterator. 93 const_iterator() 94 : Scope(NULL), VarIter(0) {} 95 96 /// Create valid iterator. In case when S.Prev is an invalid iterator and 97 /// I is equal to 0, this will create invalid iterator. 98 const_iterator(const LocalScope& S, unsigned I) 99 : Scope(&S), VarIter(I) { 100 // Iterator to "end" of scope is not allowed. Handle it by going up 101 // in scopes tree possibly up to invalid iterator in the root. 102 if (VarIter == 0 && Scope) 103 *this = Scope->Prev; 104 } 105 106 VarDecl* const* operator->() const { 107 assert (Scope && "Dereferencing invalid iterator is not allowed"); 108 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 109 return &Scope->Vars[VarIter - 1]; 110 } 111 VarDecl* operator*() const { 112 return *this->operator->(); 113 } 114 115 const_iterator& operator++() { 116 if (!Scope) 117 return *this; 118 119 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 120 --VarIter; 121 if (VarIter == 0) 122 *this = Scope->Prev; 123 return *this; 124 } 125 const_iterator operator++(int) { 126 const_iterator P = *this; 127 ++*this; 128 return P; 129 } 130 131 bool operator==(const const_iterator& rhs) const { 132 return Scope == rhs.Scope && VarIter == rhs.VarIter; 133 } 134 bool operator!=(const const_iterator& rhs) const { 135 return !(*this == rhs); 136 } 137 138 operator bool() const { 139 return *this != const_iterator(); 140 } 141 142 int distance(const_iterator L); 143 }; 144 145 friend class const_iterator; 146 147private: 148 /// Automatic variables in order of declaration. 149 AutomaticVarsTy Vars; 150 /// Iterator to variable in previous scope that was declared just before 151 /// begin of this scope. 152 const_iterator Prev; 153 154public: 155 /// Constructs empty scope linked to previous scope in specified place. 156 LocalScope(const_iterator P) 157 : Vars() 158 , Prev(P) {} 159 160 /// Begin of scope in direction of CFG building (backwards). 161 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 162 163 void addVar(VarDecl* VD) { 164 Vars.push_back(VD); 165 } 166}; 167 168/// distance - Calculates distance from this to L. L must be reachable from this 169/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 170/// number of scopes between this and L. 171int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 172 int D = 0; 173 const_iterator F = *this; 174 while (F.Scope != L.Scope) { 175 assert (F != const_iterator() 176 && "L iterator is not reachable from F iterator."); 177 D += F.VarIter; 178 F = F.Scope->Prev; 179 } 180 D += F.VarIter - L.VarIter; 181 return D; 182} 183 184/// BlockScopePosPair - Structure for specifying position in CFG during its 185/// build process. It consists of CFGBlock that specifies position in CFG graph 186/// and LocalScope::const_iterator that specifies position in LocalScope graph. 187struct BlockScopePosPair { 188 BlockScopePosPair() {} 189 BlockScopePosPair(CFGBlock* B, LocalScope::const_iterator S) 190 : Block(B), ScopePos(S) {} 191 192 CFGBlock* Block; 193 LocalScope::const_iterator ScopePos; 194}; 195 196/// CFGBuilder - This class implements CFG construction from an AST. 197/// The builder is stateful: an instance of the builder should be used to only 198/// construct a single CFG. 199/// 200/// Example usage: 201/// 202/// CFGBuilder builder; 203/// CFG* cfg = builder.BuildAST(stmt1); 204/// 205/// CFG construction is done via a recursive walk of an AST. We actually parse 206/// the AST in reverse order so that the successor of a basic block is 207/// constructed prior to its predecessor. This allows us to nicely capture 208/// implicit fall-throughs without extra basic blocks. 209/// 210class CFGBuilder { 211 typedef BlockScopePosPair JumpTarget; 212 typedef BlockScopePosPair JumpSource; 213 214 ASTContext *Context; 215 llvm::OwningPtr<CFG> cfg; 216 217 CFGBlock* Block; 218 CFGBlock* Succ; 219 JumpTarget ContinueJumpTarget; 220 JumpTarget BreakJumpTarget; 221 CFGBlock* SwitchTerminatedBlock; 222 CFGBlock* DefaultCaseBlock; 223 CFGBlock* TryTerminatedBlock; 224 225 // Current position in local scope. 226 LocalScope::const_iterator ScopePos; 227 228 // LabelMap records the mapping from Label expressions to their jump targets. 229 typedef llvm::DenseMap<LabelStmt*, JumpTarget> LabelMapTy; 230 LabelMapTy LabelMap; 231 232 // A list of blocks that end with a "goto" that must be backpatched to their 233 // resolved targets upon completion of CFG construction. 234 typedef std::vector<JumpSource> BackpatchBlocksTy; 235 BackpatchBlocksTy BackpatchBlocks; 236 237 // A list of labels whose address has been taken (for indirect gotos). 238 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy; 239 LabelSetTy AddressTakenLabels; 240 241 bool badCFG; 242 CFG::BuildOptions BuildOpts; 243 244public: 245 explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG 246 Block(NULL), Succ(NULL), 247 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL), 248 TryTerminatedBlock(NULL), badCFG(false) {} 249 250 // buildCFG - Used by external clients to construct the CFG. 251 CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, 252 CFG::BuildOptions BO); 253 254private: 255 // Visitors to walk an AST and construct the CFG. 256 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 257 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 258 CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc); 259 CFGBlock *VisitBreakStmt(BreakStmt *B); 260 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 261 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 262 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 263 CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc); 264 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 265 CFGBlock *VisitCaseStmt(CaseStmt *C); 266 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 267 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 268 CFGBlock *VisitConditionalOperator(ConditionalOperator *C, AddStmtChoice asc); 269 CFGBlock *VisitContinueStmt(ContinueStmt *C); 270 CFGBlock *VisitDeclStmt(DeclStmt *DS); 271 CFGBlock *VisitDeclSubExpr(Decl* D); 272 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 273 CFGBlock *VisitDoStmt(DoStmt *D); 274 CFGBlock *VisitForStmt(ForStmt *F); 275 CFGBlock *VisitGotoStmt(GotoStmt* G); 276 CFGBlock *VisitIfStmt(IfStmt *I); 277 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 278 CFGBlock *VisitLabelStmt(LabelStmt *L); 279 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 280 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 281 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 282 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 283 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 284 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 285 CFGBlock *VisitReturnStmt(ReturnStmt* R); 286 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc); 287 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 288 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 289 CFGBlock *VisitWhileStmt(WhileStmt *W); 290 291 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); 292 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 293 CFGBlock *VisitChildren(Stmt* S); 294 295 // NYS == Not Yet Supported 296 CFGBlock* NYS() { 297 badCFG = true; 298 return Block; 299 } 300 301 void autoCreateBlock() { if (!Block) Block = createBlock(); } 302 CFGBlock *createBlock(bool add_successor = true); 303 304 CFGBlock *addStmt(Stmt *S) { 305 return Visit(S, AddStmtChoice::AlwaysAdd); 306 } 307 308 void AppendStmt(CFGBlock *B, Stmt *S, 309 AddStmtChoice asc = AddStmtChoice::AlwaysAdd) { 310 B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue()); 311 } 312 313 void insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I, 314 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S); 315 void appendAutomaticObjDtors(CFGBlock* Blk, LocalScope::const_iterator B, 316 LocalScope::const_iterator E, Stmt* S); 317 void prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk, 318 LocalScope::const_iterator B, LocalScope::const_iterator E); 319 320 void AddSuccessor(CFGBlock *B, CFGBlock *S) { 321 B->addSuccessor(S, cfg->getBumpVectorContext()); 322 } 323 324 /// TryResult - a class representing a variant over the values 325 /// 'true', 'false', or 'unknown'. This is returned by TryEvaluateBool, 326 /// and is used by the CFGBuilder to decide if a branch condition 327 /// can be decided up front during CFG construction. 328 class TryResult { 329 int X; 330 public: 331 TryResult(bool b) : X(b ? 1 : 0) {} 332 TryResult() : X(-1) {} 333 334 bool isTrue() const { return X == 1; } 335 bool isFalse() const { return X == 0; } 336 bool isKnown() const { return X >= 0; } 337 void negate() { 338 assert(isKnown()); 339 X ^= 0x1; 340 } 341 }; 342 343 /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 344 /// if we can evaluate to a known value, otherwise return -1. 345 TryResult TryEvaluateBool(Expr *S) { 346 if (!BuildOpts.PruneTriviallyFalseEdges) 347 return TryResult(); 348 349 Expr::EvalResult Result; 350 if (!S->isTypeDependent() && !S->isValueDependent() && 351 S->Evaluate(Result, *Context) && Result.Val.isInt()) 352 return Result.Val.getInt().getBoolValue(); 353 354 return TryResult(); 355 } 356}; 357 358// FIXME: Add support for dependent-sized array types in C++? 359// Does it even make sense to build a CFG for an uninstantiated template? 360static VariableArrayType* FindVA(Type* t) { 361 while (ArrayType* vt = dyn_cast<ArrayType>(t)) { 362 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt)) 363 if (vat->getSizeExpr()) 364 return vat; 365 366 t = vt->getElementType().getTypePtr(); 367 } 368 369 return 0; 370} 371 372/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 373/// arbitrary statement. Examples include a single expression or a function 374/// body (compound statement). The ownership of the returned CFG is 375/// transferred to the caller. If CFG construction fails, this method returns 376/// NULL. 377CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C, 378 CFG::BuildOptions BO) { 379 380 Context = C; 381 assert(cfg.get()); 382 if (!Statement) 383 return NULL; 384 385 BuildOpts = BO; 386 if (!C->getLangOptions().CPlusPlus) 387 BuildOpts.AddImplicitDtors = false; 388 389 // Create an empty block that will serve as the exit block for the CFG. Since 390 // this is the first block added to the CFG, it will be implicitly registered 391 // as the exit block. 392 Succ = createBlock(); 393 assert(Succ == &cfg->getExit()); 394 Block = NULL; // the EXIT block is empty. Create all other blocks lazily. 395 396 // Visit the statements and create the CFG. 397 CFGBlock *B = addStmt(Statement); 398 399 if (badCFG) 400 return NULL; 401 402 if (B) 403 Succ = B; 404 405 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 406 // FIXME: Add code for base initializers and member initializers. 407 (void)CD; 408 } 409 410 // Backpatch the gotos whose label -> block mappings we didn't know when we 411 // encountered them. 412 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 413 E = BackpatchBlocks.end(); I != E; ++I ) { 414 415 CFGBlock* B = I->Block; 416 GotoStmt* G = cast<GotoStmt>(B->getTerminator()); 417 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 418 419 // If there is no target for the goto, then we are looking at an 420 // incomplete AST. Handle this by not registering a successor. 421 if (LI == LabelMap.end()) continue; 422 423 JumpTarget JT = LI->second; 424 AddSuccessor(B, JT.Block); 425 } 426 427 // Add successors to the Indirect Goto Dispatch block (if we have one). 428 if (CFGBlock* B = cfg->getIndirectGotoBlock()) 429 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 430 E = AddressTakenLabels.end(); I != E; ++I ) { 431 432 // Lookup the target block. 433 LabelMapTy::iterator LI = LabelMap.find(*I); 434 435 // If there is no target block that contains label, then we are looking 436 // at an incomplete AST. Handle this by not registering a successor. 437 if (LI == LabelMap.end()) continue; 438 439 AddSuccessor(B, LI->second.Block); 440 } 441 442 // Create an empty entry block that has no predecessors. 443 cfg->setEntry(createBlock()); 444 445 return cfg.take(); 446} 447 448/// createBlock - Used to lazily create blocks that are connected 449/// to the current (global) succcessor. 450CFGBlock* CFGBuilder::createBlock(bool add_successor) { 451 CFGBlock* B = cfg->createBlock(); 452 if (add_successor && Succ) 453 AddSuccessor(B, Succ); 454 return B; 455} 456 457/// insertAutomaticObjDtors - Insert destructor CFGElements for variables with 458/// automatic storage duration to CFGBlock's elements vector. Insertion will be 459/// performed in place specified with iterator. 460void CFGBuilder::insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I, 461 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) { 462 BumpVectorContext& C = cfg->getBumpVectorContext(); 463 I = Blk->beginAutomaticObjDtorsInsert(I, B.distance(E), C); 464 while (B != E) 465 I = Blk->insertAutomaticObjDtor(I, *B++, S); 466} 467 468/// appendAutomaticObjDtors - Append destructor CFGElements for variables with 469/// automatic storage duration to CFGBlock's elements vector. Elements will be 470/// appended to physical end of the vector which happens to be logical 471/// beginning. 472void CFGBuilder::appendAutomaticObjDtors(CFGBlock* Blk, 473 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) { 474 insertAutomaticObjDtors(Blk, Blk->begin(), B, E, S); 475} 476 477/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 478/// variables with automatic storage duration to CFGBlock's elements vector. 479/// Elements will be prepended to physical beginning of the vector which 480/// happens to be logical end. Use blocks terminator as statement that specifies 481/// destructors call site. 482void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk, 483 LocalScope::const_iterator B, LocalScope::const_iterator E) { 484 insertAutomaticObjDtors(Blk, Blk->end(), B, E, Blk->getTerminator()); 485} 486 487/// Visit - Walk the subtree of a statement and add extra 488/// blocks for ternary operators, &&, and ||. We also process "," and 489/// DeclStmts (which may contain nested control-flow). 490CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { 491tryAgain: 492 if (!S) { 493 badCFG = true; 494 return 0; 495 } 496 switch (S->getStmtClass()) { 497 default: 498 return VisitStmt(S, asc); 499 500 case Stmt::AddrLabelExprClass: 501 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 502 503 case Stmt::BinaryOperatorClass: 504 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 505 506 case Stmt::BlockExprClass: 507 return VisitBlockExpr(cast<BlockExpr>(S), asc); 508 509 case Stmt::BreakStmtClass: 510 return VisitBreakStmt(cast<BreakStmt>(S)); 511 512 case Stmt::CallExprClass: 513 case Stmt::CXXOperatorCallExprClass: 514 return VisitCallExpr(cast<CallExpr>(S), asc); 515 516 case Stmt::CaseStmtClass: 517 return VisitCaseStmt(cast<CaseStmt>(S)); 518 519 case Stmt::ChooseExprClass: 520 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 521 522 case Stmt::CompoundStmtClass: 523 return VisitCompoundStmt(cast<CompoundStmt>(S)); 524 525 case Stmt::ConditionalOperatorClass: 526 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 527 528 case Stmt::ContinueStmtClass: 529 return VisitContinueStmt(cast<ContinueStmt>(S)); 530 531 case Stmt::CXXCatchStmtClass: 532 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 533 534 case Stmt::CXXExprWithTemporariesClass: { 535 // FIXME: Handle temporaries. For now, just visit the subexpression 536 // so we don't artificially create extra blocks. 537 return Visit(cast<CXXExprWithTemporaries>(S)->getSubExpr(), asc); 538 } 539 540 case Stmt::CXXMemberCallExprClass: 541 return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc); 542 543 case Stmt::CXXThrowExprClass: 544 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 545 546 case Stmt::CXXTryStmtClass: 547 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 548 549 case Stmt::DeclStmtClass: 550 return VisitDeclStmt(cast<DeclStmt>(S)); 551 552 case Stmt::DefaultStmtClass: 553 return VisitDefaultStmt(cast<DefaultStmt>(S)); 554 555 case Stmt::DoStmtClass: 556 return VisitDoStmt(cast<DoStmt>(S)); 557 558 case Stmt::ForStmtClass: 559 return VisitForStmt(cast<ForStmt>(S)); 560 561 case Stmt::GotoStmtClass: 562 return VisitGotoStmt(cast<GotoStmt>(S)); 563 564 case Stmt::IfStmtClass: 565 return VisitIfStmt(cast<IfStmt>(S)); 566 567 case Stmt::IndirectGotoStmtClass: 568 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 569 570 case Stmt::LabelStmtClass: 571 return VisitLabelStmt(cast<LabelStmt>(S)); 572 573 case Stmt::MemberExprClass: 574 return VisitMemberExpr(cast<MemberExpr>(S), asc); 575 576 case Stmt::ObjCAtCatchStmtClass: 577 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 578 579 case Stmt::ObjCAtSynchronizedStmtClass: 580 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 581 582 case Stmt::ObjCAtThrowStmtClass: 583 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 584 585 case Stmt::ObjCAtTryStmtClass: 586 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 587 588 case Stmt::ObjCForCollectionStmtClass: 589 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 590 591 case Stmt::ParenExprClass: 592 S = cast<ParenExpr>(S)->getSubExpr(); 593 goto tryAgain; 594 595 case Stmt::NullStmtClass: 596 return Block; 597 598 case Stmt::ReturnStmtClass: 599 return VisitReturnStmt(cast<ReturnStmt>(S)); 600 601 case Stmt::SizeOfAlignOfExprClass: 602 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc); 603 604 case Stmt::StmtExprClass: 605 return VisitStmtExpr(cast<StmtExpr>(S), asc); 606 607 case Stmt::SwitchStmtClass: 608 return VisitSwitchStmt(cast<SwitchStmt>(S)); 609 610 case Stmt::WhileStmtClass: 611 return VisitWhileStmt(cast<WhileStmt>(S)); 612 } 613} 614 615CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 616 if (asc.alwaysAdd()) { 617 autoCreateBlock(); 618 AppendStmt(Block, S, asc); 619 } 620 621 return VisitChildren(S); 622} 623 624/// VisitChildren - Visit the children of a Stmt. 625CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) { 626 CFGBlock *B = Block; 627 for (Stmt::child_iterator I = Terminator->child_begin(), 628 E = Terminator->child_end(); I != E; ++I) { 629 if (*I) B = Visit(*I); 630 } 631 return B; 632} 633 634CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 635 AddStmtChoice asc) { 636 AddressTakenLabels.insert(A->getLabel()); 637 638 if (asc.alwaysAdd()) { 639 autoCreateBlock(); 640 AppendStmt(Block, A, asc); 641 } 642 643 return Block; 644} 645 646CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 647 AddStmtChoice asc) { 648 if (B->isLogicalOp()) { // && or || 649 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 650 AppendStmt(ConfluenceBlock, B, asc); 651 652 if (badCFG) 653 return 0; 654 655 // create the block evaluating the LHS 656 CFGBlock* LHSBlock = createBlock(false); 657 LHSBlock->setTerminator(B); 658 659 // create the block evaluating the RHS 660 Succ = ConfluenceBlock; 661 Block = NULL; 662 CFGBlock* RHSBlock = addStmt(B->getRHS()); 663 664 if (RHSBlock) { 665 if (badCFG) 666 return 0; 667 } 668 else { 669 // Create an empty block for cases where the RHS doesn't require 670 // any explicit statements in the CFG. 671 RHSBlock = createBlock(); 672 } 673 674 // See if this is a known constant. 675 TryResult KnownVal = TryEvaluateBool(B->getLHS()); 676 if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr)) 677 KnownVal.negate(); 678 679 // Now link the LHSBlock with RHSBlock. 680 if (B->getOpcode() == BO_LOr) { 681 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 682 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 683 } else { 684 assert(B->getOpcode() == BO_LAnd); 685 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 686 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 687 } 688 689 // Generate the blocks for evaluating the LHS. 690 Block = LHSBlock; 691 return addStmt(B->getLHS()); 692 } 693 else if (B->getOpcode() == BO_Comma) { // , 694 autoCreateBlock(); 695 AppendStmt(Block, B, asc); 696 addStmt(B->getRHS()); 697 return addStmt(B->getLHS()); 698 } 699 else if (B->isAssignmentOp()) { 700 if (asc.alwaysAdd()) { 701 autoCreateBlock(); 702 AppendStmt(Block, B, asc); 703 } 704 705 // If visiting RHS causes us to finish 'Block' and the LHS doesn't 706 // create a new block, then we should return RBlock. Otherwise 707 // we'll incorrectly return NULL. 708 CFGBlock *RBlock = Visit(B->getRHS()); 709 CFGBlock *LBlock = Visit(B->getLHS(), AddStmtChoice::AsLValueNotAlwaysAdd); 710 return LBlock ? LBlock : RBlock; 711 } 712 713 return VisitStmt(B, asc); 714} 715 716CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 717 if (asc.alwaysAdd()) { 718 autoCreateBlock(); 719 AppendStmt(Block, E, asc); 720 } 721 return Block; 722} 723 724CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 725 // "break" is a control-flow statement. Thus we stop processing the current 726 // block. 727 if (badCFG) 728 return 0; 729 730 // Now create a new block that ends with the break statement. 731 Block = createBlock(false); 732 Block->setTerminator(B); 733 734 // If there is no target for the break, then we are looking at an incomplete 735 // AST. This means that the CFG cannot be constructed. 736 if (BreakJumpTarget.Block) { 737 AddSuccessor(Block, BreakJumpTarget.Block); 738 } else 739 badCFG = true; 740 741 742 return Block; 743} 744 745static bool CanThrow(Expr *E) { 746 QualType Ty = E->getType(); 747 if (Ty->isFunctionPointerType()) 748 Ty = Ty->getAs<PointerType>()->getPointeeType(); 749 else if (Ty->isBlockPointerType()) 750 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 751 752 const FunctionType *FT = Ty->getAs<FunctionType>(); 753 if (FT) { 754 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 755 if (Proto->hasEmptyExceptionSpec()) 756 return false; 757 } 758 return true; 759} 760 761CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 762 // If this is a call to a no-return function, this stops the block here. 763 bool NoReturn = false; 764 if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) { 765 NoReturn = true; 766 } 767 768 bool AddEHEdge = false; 769 770 // Languages without exceptions are assumed to not throw. 771 if (Context->getLangOptions().Exceptions) { 772 if (BuildOpts.AddEHEdges) 773 AddEHEdge = true; 774 } 775 776 if (FunctionDecl *FD = C->getDirectCallee()) { 777 if (FD->hasAttr<NoReturnAttr>()) 778 NoReturn = true; 779 if (FD->hasAttr<NoThrowAttr>()) 780 AddEHEdge = false; 781 } 782 783 if (!CanThrow(C->getCallee())) 784 AddEHEdge = false; 785 786 if (!NoReturn && !AddEHEdge) { 787 if (asc.asLValue()) 788 return VisitStmt(C, AddStmtChoice::AlwaysAddAsLValue); 789 else 790 return VisitStmt(C, AddStmtChoice::AlwaysAdd); 791 } 792 793 if (Block) { 794 Succ = Block; 795 if (badCFG) 796 return 0; 797 } 798 799 Block = createBlock(!NoReturn); 800 AppendStmt(Block, C, asc); 801 802 if (NoReturn) { 803 // Wire this to the exit block directly. 804 AddSuccessor(Block, &cfg->getExit()); 805 } 806 if (AddEHEdge) { 807 // Add exceptional edges. 808 if (TryTerminatedBlock) 809 AddSuccessor(Block, TryTerminatedBlock); 810 else 811 AddSuccessor(Block, &cfg->getExit()); 812 } 813 814 return VisitChildren(C); 815} 816 817CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 818 AddStmtChoice asc) { 819 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 820 AppendStmt(ConfluenceBlock, C, asc); 821 if (badCFG) 822 return 0; 823 824 asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue 825 : AddStmtChoice::AlwaysAdd; 826 827 Succ = ConfluenceBlock; 828 Block = NULL; 829 CFGBlock* LHSBlock = Visit(C->getLHS(), asc); 830 if (badCFG) 831 return 0; 832 833 Succ = ConfluenceBlock; 834 Block = NULL; 835 CFGBlock* RHSBlock = Visit(C->getRHS(), asc); 836 if (badCFG) 837 return 0; 838 839 Block = createBlock(false); 840 // See if this is a known constant. 841 const TryResult& KnownVal = TryEvaluateBool(C->getCond()); 842 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 843 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 844 Block->setTerminator(C); 845 return addStmt(C->getCond()); 846} 847 848 849CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) { 850 CFGBlock* LastBlock = Block; 851 852 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 853 I != E; ++I ) { 854 // If we hit a segment of code just containing ';' (NullStmts), we can 855 // get a null block back. In such cases, just use the LastBlock 856 if (CFGBlock *newBlock = addStmt(*I)) 857 LastBlock = newBlock; 858 859 if (badCFG) 860 return NULL; 861 } 862 863 return LastBlock; 864} 865 866CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C, 867 AddStmtChoice asc) { 868 // Create the confluence block that will "merge" the results of the ternary 869 // expression. 870 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 871 AppendStmt(ConfluenceBlock, C, asc); 872 if (badCFG) 873 return 0; 874 875 asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue 876 : AddStmtChoice::AlwaysAdd; 877 878 // Create a block for the LHS expression if there is an LHS expression. A 879 // GCC extension allows LHS to be NULL, causing the condition to be the 880 // value that is returned instead. 881 // e.g: x ?: y is shorthand for: x ? x : y; 882 Succ = ConfluenceBlock; 883 Block = NULL; 884 CFGBlock* LHSBlock = NULL; 885 if (C->getLHS()) { 886 LHSBlock = Visit(C->getLHS(), asc); 887 if (badCFG) 888 return 0; 889 Block = NULL; 890 } 891 892 // Create the block for the RHS expression. 893 Succ = ConfluenceBlock; 894 CFGBlock* RHSBlock = Visit(C->getRHS(), asc); 895 if (badCFG) 896 return 0; 897 898 // Create the block that will contain the condition. 899 Block = createBlock(false); 900 901 // See if this is a known constant. 902 const TryResult& KnownVal = TryEvaluateBool(C->getCond()); 903 if (LHSBlock) { 904 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 905 } else { 906 if (KnownVal.isFalse()) { 907 // If we know the condition is false, add NULL as the successor for 908 // the block containing the condition. In this case, the confluence 909 // block will have just one predecessor. 910 AddSuccessor(Block, 0); 911 assert(ConfluenceBlock->pred_size() == 1); 912 } else { 913 // If we have no LHS expression, add the ConfluenceBlock as a direct 914 // successor for the block containing the condition. Moreover, we need to 915 // reverse the order of the predecessors in the ConfluenceBlock because 916 // the RHSBlock will have been added to the succcessors already, and we 917 // want the first predecessor to the the block containing the expression 918 // for the case when the ternary expression evaluates to true. 919 AddSuccessor(Block, ConfluenceBlock); 920 assert(ConfluenceBlock->pred_size() == 2); 921 std::reverse(ConfluenceBlock->pred_begin(), 922 ConfluenceBlock->pred_end()); 923 } 924 } 925 926 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 927 Block->setTerminator(C); 928 return addStmt(C->getCond()); 929} 930 931CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 932 autoCreateBlock(); 933 934 if (DS->isSingleDecl()) { 935 AppendStmt(Block, DS); 936 return VisitDeclSubExpr(DS->getSingleDecl()); 937 } 938 939 CFGBlock *B = 0; 940 941 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 942 typedef llvm::SmallVector<Decl*,10> BufTy; 943 BufTy Buf(DS->decl_begin(), DS->decl_end()); 944 945 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 946 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 947 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 948 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 949 950 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 951 // automatically freed with the CFG. 952 DeclGroupRef DG(*I); 953 Decl *D = *I; 954 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 955 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 956 957 // Append the fake DeclStmt to block. 958 AppendStmt(Block, DSNew); 959 B = VisitDeclSubExpr(D); 960 } 961 962 return B; 963} 964 965/// VisitDeclSubExpr - Utility method to add block-level expressions for 966/// initializers in Decls. 967CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) { 968 assert(Block); 969 970 VarDecl *VD = dyn_cast<VarDecl>(D); 971 972 if (!VD) 973 return Block; 974 975 Expr *Init = VD->getInit(); 976 977 if (Init) { 978 AddStmtChoice::Kind k = 979 VD->getType()->isReferenceType() ? AddStmtChoice::AsLValueNotAlwaysAdd 980 : AddStmtChoice::NotAlwaysAdd; 981 Visit(Init, AddStmtChoice(k)); 982 } 983 984 // If the type of VD is a VLA, then we must process its size expressions. 985 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0; 986 VA = FindVA(VA->getElementType().getTypePtr())) 987 Block = addStmt(VA->getSizeExpr()); 988 989 return Block; 990} 991 992CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) { 993 // We may see an if statement in the middle of a basic block, or it may be the 994 // first statement we are processing. In either case, we create a new basic 995 // block. First, we create the blocks for the then...else statements, and 996 // then we create the block containing the if statement. If we were in the 997 // middle of a block, we stop processing that block. That block is then the 998 // implicit successor for the "then" and "else" clauses. 999 1000 // The block we were proccessing is now finished. Make it the successor 1001 // block. 1002 if (Block) { 1003 Succ = Block; 1004 if (badCFG) 1005 return 0; 1006 } 1007 1008 // Process the false branch. 1009 CFGBlock* ElseBlock = Succ; 1010 1011 if (Stmt* Else = I->getElse()) { 1012 SaveAndRestore<CFGBlock*> sv(Succ); 1013 1014 // NULL out Block so that the recursive call to Visit will 1015 // create a new basic block. 1016 Block = NULL; 1017 ElseBlock = addStmt(Else); 1018 1019 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 1020 ElseBlock = sv.get(); 1021 else if (Block) { 1022 if (badCFG) 1023 return 0; 1024 } 1025 } 1026 1027 // Process the true branch. 1028 CFGBlock* ThenBlock; 1029 { 1030 Stmt* Then = I->getThen(); 1031 assert(Then); 1032 SaveAndRestore<CFGBlock*> sv(Succ); 1033 Block = NULL; 1034 ThenBlock = addStmt(Then); 1035 1036 if (!ThenBlock) { 1037 // We can reach here if the "then" body has all NullStmts. 1038 // Create an empty block so we can distinguish between true and false 1039 // branches in path-sensitive analyses. 1040 ThenBlock = createBlock(false); 1041 AddSuccessor(ThenBlock, sv.get()); 1042 } else if (Block) { 1043 if (badCFG) 1044 return 0; 1045 } 1046 } 1047 1048 // Now create a new block containing the if statement. 1049 Block = createBlock(false); 1050 1051 // Set the terminator of the new block to the If statement. 1052 Block->setTerminator(I); 1053 1054 // See if this is a known constant. 1055 const TryResult &KnownVal = TryEvaluateBool(I->getCond()); 1056 1057 // Now add the successors. 1058 AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 1059 AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 1060 1061 // Add the condition as the last statement in the new block. This may create 1062 // new blocks as the condition may contain control-flow. Any newly created 1063 // blocks will be pointed to be "Block". 1064 Block = addStmt(I->getCond()); 1065 1066 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 1067 // and the condition variable initialization to the CFG. 1068 if (VarDecl *VD = I->getConditionVariable()) { 1069 if (Expr *Init = VD->getInit()) { 1070 autoCreateBlock(); 1071 AppendStmt(Block, I, AddStmtChoice::AlwaysAdd); 1072 addStmt(Init); 1073 } 1074 } 1075 1076 return Block; 1077} 1078 1079 1080CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) { 1081 // If we were in the middle of a block we stop processing that block. 1082 // 1083 // NOTE: If a "return" appears in the middle of a block, this means that the 1084 // code afterwards is DEAD (unreachable). We still keep a basic block 1085 // for that code; a simple "mark-and-sweep" from the entry block will be 1086 // able to report such dead blocks. 1087 1088 // Create the new block. 1089 Block = createBlock(false); 1090 1091 // The Exit block is the only successor. 1092 AddSuccessor(Block, &cfg->getExit()); 1093 1094 // Add the return statement to the block. This may create new blocks if R 1095 // contains control-flow (short-circuit operations). 1096 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 1097} 1098 1099CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) { 1100 // Get the block of the labeled statement. Add it to our map. 1101 addStmt(L->getSubStmt()); 1102 CFGBlock* LabelBlock = Block; 1103 1104 if (!LabelBlock) // This can happen when the body is empty, i.e. 1105 LabelBlock = createBlock(); // scopes that only contains NullStmts. 1106 1107 assert(LabelMap.find(L) == LabelMap.end() && "label already in map"); 1108 LabelMap[ L ] = JumpTarget(LabelBlock, ScopePos); 1109 1110 // Labels partition blocks, so this is the end of the basic block we were 1111 // processing (L is the block's label). Because this is label (and we have 1112 // already processed the substatement) there is no extra control-flow to worry 1113 // about. 1114 LabelBlock->setLabel(L); 1115 if (badCFG) 1116 return 0; 1117 1118 // We set Block to NULL to allow lazy creation of a new block (if necessary); 1119 Block = NULL; 1120 1121 // This block is now the implicit successor of other blocks. 1122 Succ = LabelBlock; 1123 1124 return LabelBlock; 1125} 1126 1127CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) { 1128 // Goto is a control-flow statement. Thus we stop processing the current 1129 // block and create a new one. 1130 1131 Block = createBlock(false); 1132 Block->setTerminator(G); 1133 1134 // If we already know the mapping to the label block add the successor now. 1135 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 1136 1137 if (I == LabelMap.end()) 1138 // We will need to backpatch this block later. 1139 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 1140 else { 1141 JumpTarget JT = I->second; 1142 AddSuccessor(Block, JT.Block); 1143 } 1144 1145 return Block; 1146} 1147 1148CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) { 1149 CFGBlock* LoopSuccessor = NULL; 1150 1151 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1152 1153 // "for" is a control-flow statement. Thus we stop processing the current 1154 // block. 1155 if (Block) { 1156 if (badCFG) 1157 return 0; 1158 LoopSuccessor = Block; 1159 } else 1160 LoopSuccessor = Succ; 1161 1162 // Save the current value for the break targets. 1163 // All breaks should go to the code following the loop. 1164 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1165 BreakJumpTarget = JumpTarget(LoopSuccessor, LoopBeginScopePos); 1166 1167 // Because of short-circuit evaluation, the condition of the loop can span 1168 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1169 // evaluate the condition. 1170 CFGBlock* ExitConditionBlock = createBlock(false); 1171 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1172 1173 // Set the terminator for the "exit" condition block. 1174 ExitConditionBlock->setTerminator(F); 1175 1176 // Now add the actual condition to the condition block. Because the condition 1177 // itself may contain control-flow, new blocks may be created. 1178 if (Stmt* C = F->getCond()) { 1179 Block = ExitConditionBlock; 1180 EntryConditionBlock = addStmt(C); 1181 assert(Block == EntryConditionBlock || 1182 (Block == 0 && EntryConditionBlock == Succ)); 1183 1184 // If this block contains a condition variable, add both the condition 1185 // variable and initializer to the CFG. 1186 if (VarDecl *VD = F->getConditionVariable()) { 1187 if (Expr *Init = VD->getInit()) { 1188 autoCreateBlock(); 1189 AppendStmt(Block, F, AddStmtChoice::AlwaysAdd); 1190 EntryConditionBlock = addStmt(Init); 1191 assert(Block == EntryConditionBlock); 1192 } 1193 } 1194 1195 if (Block) { 1196 if (badCFG) 1197 return 0; 1198 } 1199 } 1200 1201 // The condition block is the implicit successor for the loop body as well as 1202 // any code above the loop. 1203 Succ = EntryConditionBlock; 1204 1205 // See if this is a known constant. 1206 TryResult KnownVal(true); 1207 1208 if (F->getCond()) 1209 KnownVal = TryEvaluateBool(F->getCond()); 1210 1211 // Now create the loop body. 1212 { 1213 assert(F->getBody()); 1214 1215 // Save the current values for Block, Succ, and continue targets. 1216 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1217 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 1218 1219 // Create a new block to contain the (bottom) of the loop body. 1220 Block = NULL; 1221 1222 if (Stmt* I = F->getInc()) { 1223 // Generate increment code in its own basic block. This is the target of 1224 // continue statements. 1225 Succ = addStmt(I); 1226 } else { 1227 // No increment code. Create a special, empty, block that is used as the 1228 // target block for "looping back" to the start of the loop. 1229 assert(Succ == EntryConditionBlock); 1230 Succ = createBlock(); 1231 } 1232 1233 // Finish up the increment (or empty) block if it hasn't been already. 1234 if (Block) { 1235 assert(Block == Succ); 1236 if (badCFG) 1237 return 0; 1238 Block = 0; 1239 } 1240 1241 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 1242 1243 // The starting block for the loop increment is the block that should 1244 // represent the 'loop target' for looping back to the start of the loop. 1245 ContinueJumpTarget.Block->setLoopTarget(F); 1246 1247 // Now populate the body block, and in the process create new blocks as we 1248 // walk the body of the loop. 1249 CFGBlock* BodyBlock = addStmt(F->getBody()); 1250 1251 if (!BodyBlock) 1252 BodyBlock = ContinueJumpTarget.Block;//can happen for "for (...;...;...);" 1253 else if (badCFG) 1254 return 0; 1255 1256 // This new body block is a successor to our "exit" condition block. 1257 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1258 } 1259 1260 // Link up the condition block with the code that follows the loop. (the 1261 // false branch). 1262 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1263 1264 // If the loop contains initialization, create a new block for those 1265 // statements. This block can also contain statements that precede the loop. 1266 if (Stmt* I = F->getInit()) { 1267 Block = createBlock(); 1268 return addStmt(I); 1269 } else { 1270 // There is no loop initialization. We are thus basically a while loop. 1271 // NULL out Block to force lazy block construction. 1272 Block = NULL; 1273 Succ = EntryConditionBlock; 1274 return EntryConditionBlock; 1275 } 1276} 1277 1278CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 1279 if (asc.alwaysAdd()) { 1280 autoCreateBlock(); 1281 AppendStmt(Block, M, asc); 1282 } 1283 return Visit(M->getBase(), 1284 M->isArrow() ? AddStmtChoice::NotAlwaysAdd 1285 : AddStmtChoice::AsLValueNotAlwaysAdd); 1286} 1287 1288CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { 1289 // Objective-C fast enumeration 'for' statements: 1290 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 1291 // 1292 // for ( Type newVariable in collection_expression ) { statements } 1293 // 1294 // becomes: 1295 // 1296 // prologue: 1297 // 1. collection_expression 1298 // T. jump to loop_entry 1299 // loop_entry: 1300 // 1. side-effects of element expression 1301 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1302 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1303 // TB: 1304 // statements 1305 // T. jump to loop_entry 1306 // FB: 1307 // what comes after 1308 // 1309 // and 1310 // 1311 // Type existingItem; 1312 // for ( existingItem in expression ) { statements } 1313 // 1314 // becomes: 1315 // 1316 // the same with newVariable replaced with existingItem; the binding works 1317 // the same except that for one ObjCForCollectionStmt::getElement() returns 1318 // a DeclStmt and the other returns a DeclRefExpr. 1319 // 1320 1321 CFGBlock* LoopSuccessor = 0; 1322 1323 if (Block) { 1324 if (badCFG) 1325 return 0; 1326 LoopSuccessor = Block; 1327 Block = 0; 1328 } else 1329 LoopSuccessor = Succ; 1330 1331 // Build the condition blocks. 1332 CFGBlock* ExitConditionBlock = createBlock(false); 1333 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1334 1335 // Set the terminator for the "exit" condition block. 1336 ExitConditionBlock->setTerminator(S); 1337 1338 // The last statement in the block should be the ObjCForCollectionStmt, which 1339 // performs the actual binding to 'element' and determines if there are any 1340 // more items in the collection. 1341 AppendStmt(ExitConditionBlock, S); 1342 Block = ExitConditionBlock; 1343 1344 // Walk the 'element' expression to see if there are any side-effects. We 1345 // generate new blocks as necesary. We DON'T add the statement by default to 1346 // the CFG unless it contains control-flow. 1347 EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd); 1348 if (Block) { 1349 if (badCFG) 1350 return 0; 1351 Block = 0; 1352 } 1353 1354 // The condition block is the implicit successor for the loop body as well as 1355 // any code above the loop. 1356 Succ = EntryConditionBlock; 1357 1358 // Now create the true branch. 1359 { 1360 // Save the current values for Succ, continue and break targets. 1361 SaveAndRestore<CFGBlock*> save_Succ(Succ); 1362 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1363 save_break(BreakJumpTarget); 1364 1365 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1366 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1367 1368 CFGBlock* BodyBlock = addStmt(S->getBody()); 1369 1370 if (!BodyBlock) 1371 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1372 else if (Block) { 1373 if (badCFG) 1374 return 0; 1375 } 1376 1377 // This new body block is a successor to our "exit" condition block. 1378 AddSuccessor(ExitConditionBlock, BodyBlock); 1379 } 1380 1381 // Link up the condition block with the code that follows the loop. 1382 // (the false branch). 1383 AddSuccessor(ExitConditionBlock, LoopSuccessor); 1384 1385 // Now create a prologue block to contain the collection expression. 1386 Block = createBlock(); 1387 return addStmt(S->getCollection()); 1388} 1389 1390CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) { 1391 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1392 1393 // Inline the body. 1394 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1395 1396 // The sync body starts its own basic block. This makes it a little easier 1397 // for diagnostic clients. 1398 if (SyncBlock) { 1399 if (badCFG) 1400 return 0; 1401 1402 Block = 0; 1403 Succ = SyncBlock; 1404 } 1405 1406 // Add the @synchronized to the CFG. 1407 autoCreateBlock(); 1408 AppendStmt(Block, S, AddStmtChoice::AlwaysAdd); 1409 1410 // Inline the sync expression. 1411 return addStmt(S->getSynchExpr()); 1412} 1413 1414CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) { 1415 // FIXME 1416 return NYS(); 1417} 1418 1419CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) { 1420 CFGBlock* LoopSuccessor = NULL; 1421 1422 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1423 1424 // "while" is a control-flow statement. Thus we stop processing the current 1425 // block. 1426 if (Block) { 1427 if (badCFG) 1428 return 0; 1429 LoopSuccessor = Block; 1430 } else 1431 LoopSuccessor = Succ; 1432 1433 // Because of short-circuit evaluation, the condition of the loop can span 1434 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1435 // evaluate the condition. 1436 CFGBlock* ExitConditionBlock = createBlock(false); 1437 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1438 1439 // Set the terminator for the "exit" condition block. 1440 ExitConditionBlock->setTerminator(W); 1441 1442 // Now add the actual condition to the condition block. Because the condition 1443 // itself may contain control-flow, new blocks may be created. Thus we update 1444 // "Succ" after adding the condition. 1445 if (Stmt* C = W->getCond()) { 1446 Block = ExitConditionBlock; 1447 EntryConditionBlock = addStmt(C); 1448 assert(Block == EntryConditionBlock); 1449 1450 // If this block contains a condition variable, add both the condition 1451 // variable and initializer to the CFG. 1452 if (VarDecl *VD = W->getConditionVariable()) { 1453 if (Expr *Init = VD->getInit()) { 1454 autoCreateBlock(); 1455 AppendStmt(Block, W, AddStmtChoice::AlwaysAdd); 1456 EntryConditionBlock = addStmt(Init); 1457 assert(Block == EntryConditionBlock); 1458 } 1459 } 1460 1461 if (Block) { 1462 if (badCFG) 1463 return 0; 1464 } 1465 } 1466 1467 // The condition block is the implicit successor for the loop body as well as 1468 // any code above the loop. 1469 Succ = EntryConditionBlock; 1470 1471 // See if this is a known constant. 1472 const TryResult& KnownVal = TryEvaluateBool(W->getCond()); 1473 1474 // Process the loop body. 1475 { 1476 assert(W->getBody()); 1477 1478 // Save the current values for Block, Succ, and continue and break targets 1479 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1480 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1481 save_break(BreakJumpTarget); 1482 1483 // Create an empty block to represent the transition block for looping back 1484 // to the head of the loop. 1485 Block = 0; 1486 assert(Succ == EntryConditionBlock); 1487 Succ = createBlock(); 1488 Succ->setLoopTarget(W); 1489 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 1490 1491 // All breaks should go to the code following the loop. 1492 BreakJumpTarget = JumpTarget(LoopSuccessor, LoopBeginScopePos); 1493 1494 // NULL out Block to force lazy instantiation of blocks for the body. 1495 Block = NULL; 1496 1497 // Create the body. The returned block is the entry to the loop body. 1498 CFGBlock* BodyBlock = addStmt(W->getBody()); 1499 1500 if (!BodyBlock) 1501 BodyBlock = ContinueJumpTarget.Block; // can happen for "while(...) ;" 1502 else if (Block) { 1503 if (badCFG) 1504 return 0; 1505 } 1506 1507 // Add the loop body entry as a successor to the condition. 1508 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1509 } 1510 1511 // Link up the condition block with the code that follows the loop. (the 1512 // false branch). 1513 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1514 1515 // There can be no more statements in the condition block since we loop back 1516 // to this block. NULL out Block to force lazy creation of another block. 1517 Block = NULL; 1518 1519 // Return the condition block, which is the dominating block for the loop. 1520 Succ = EntryConditionBlock; 1521 return EntryConditionBlock; 1522} 1523 1524 1525CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { 1526 // FIXME: For now we pretend that @catch and the code it contains does not 1527 // exit. 1528 return Block; 1529} 1530 1531CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { 1532 // FIXME: This isn't complete. We basically treat @throw like a return 1533 // statement. 1534 1535 // If we were in the middle of a block we stop processing that block. 1536 if (badCFG) 1537 return 0; 1538 1539 // Create the new block. 1540 Block = createBlock(false); 1541 1542 // The Exit block is the only successor. 1543 AddSuccessor(Block, &cfg->getExit()); 1544 1545 // Add the statement to the block. This may create new blocks if S contains 1546 // control-flow (short-circuit operations). 1547 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 1548} 1549 1550CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) { 1551 // If we were in the middle of a block we stop processing that block. 1552 if (badCFG) 1553 return 0; 1554 1555 // Create the new block. 1556 Block = createBlock(false); 1557 1558 if (TryTerminatedBlock) 1559 // The current try statement is the only successor. 1560 AddSuccessor(Block, TryTerminatedBlock); 1561 else 1562 // otherwise the Exit block is the only successor. 1563 AddSuccessor(Block, &cfg->getExit()); 1564 1565 // Add the statement to the block. This may create new blocks if S contains 1566 // control-flow (short-circuit operations). 1567 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 1568} 1569 1570CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) { 1571 CFGBlock* LoopSuccessor = NULL; 1572 1573 // "do...while" is a control-flow statement. Thus we stop processing the 1574 // current block. 1575 if (Block) { 1576 if (badCFG) 1577 return 0; 1578 LoopSuccessor = Block; 1579 } else 1580 LoopSuccessor = Succ; 1581 1582 // Because of short-circuit evaluation, the condition of the loop can span 1583 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1584 // evaluate the condition. 1585 CFGBlock* ExitConditionBlock = createBlock(false); 1586 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1587 1588 // Set the terminator for the "exit" condition block. 1589 ExitConditionBlock->setTerminator(D); 1590 1591 // Now add the actual condition to the condition block. Because the condition 1592 // itself may contain control-flow, new blocks may be created. 1593 if (Stmt* C = D->getCond()) { 1594 Block = ExitConditionBlock; 1595 EntryConditionBlock = addStmt(C); 1596 if (Block) { 1597 if (badCFG) 1598 return 0; 1599 } 1600 } 1601 1602 // The condition block is the implicit successor for the loop body. 1603 Succ = EntryConditionBlock; 1604 1605 // See if this is a known constant. 1606 const TryResult &KnownVal = TryEvaluateBool(D->getCond()); 1607 1608 // Process the loop body. 1609 CFGBlock* BodyBlock = NULL; 1610 { 1611 assert(D->getBody()); 1612 1613 // Save the current values for Block, Succ, and continue and break targets 1614 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1615 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1616 save_break(BreakJumpTarget); 1617 1618 // All continues within this loop should go to the condition block 1619 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1620 1621 // All breaks should go to the code following the loop. 1622 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1623 1624 // NULL out Block to force lazy instantiation of blocks for the body. 1625 Block = NULL; 1626 1627 // Create the body. The returned block is the entry to the loop body. 1628 BodyBlock = addStmt(D->getBody()); 1629 1630 if (!BodyBlock) 1631 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 1632 else if (Block) { 1633 if (badCFG) 1634 return 0; 1635 } 1636 1637 if (!KnownVal.isFalse()) { 1638 // Add an intermediate block between the BodyBlock and the 1639 // ExitConditionBlock to represent the "loop back" transition. Create an 1640 // empty block to represent the transition block for looping back to the 1641 // head of the loop. 1642 // FIXME: Can we do this more efficiently without adding another block? 1643 Block = NULL; 1644 Succ = BodyBlock; 1645 CFGBlock *LoopBackBlock = createBlock(); 1646 LoopBackBlock->setLoopTarget(D); 1647 1648 // Add the loop body entry as a successor to the condition. 1649 AddSuccessor(ExitConditionBlock, LoopBackBlock); 1650 } 1651 else 1652 AddSuccessor(ExitConditionBlock, NULL); 1653 } 1654 1655 // Link up the condition block with the code that follows the loop. 1656 // (the false branch). 1657 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1658 1659 // There can be no more statements in the body block(s) since we loop back to 1660 // the body. NULL out Block to force lazy creation of another block. 1661 Block = NULL; 1662 1663 // Return the loop body, which is the dominating block for the loop. 1664 Succ = BodyBlock; 1665 return BodyBlock; 1666} 1667 1668CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) { 1669 // "continue" is a control-flow statement. Thus we stop processing the 1670 // current block. 1671 if (badCFG) 1672 return 0; 1673 1674 // Now create a new block that ends with the continue statement. 1675 Block = createBlock(false); 1676 Block->setTerminator(C); 1677 1678 // If there is no target for the continue, then we are looking at an 1679 // incomplete AST. This means the CFG cannot be constructed. 1680 if (ContinueJumpTarget.Block) { 1681 AddSuccessor(Block, ContinueJumpTarget.Block); 1682 } else 1683 badCFG = true; 1684 1685 return Block; 1686} 1687 1688CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, 1689 AddStmtChoice asc) { 1690 1691 if (asc.alwaysAdd()) { 1692 autoCreateBlock(); 1693 AppendStmt(Block, E); 1694 } 1695 1696 // VLA types have expressions that must be evaluated. 1697 if (E->isArgumentType()) { 1698 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr()); 1699 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1700 addStmt(VA->getSizeExpr()); 1701 } 1702 1703 return Block; 1704} 1705 1706/// VisitStmtExpr - Utility method to handle (nested) statement 1707/// expressions (a GCC extension). 1708CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 1709 if (asc.alwaysAdd()) { 1710 autoCreateBlock(); 1711 AppendStmt(Block, SE); 1712 } 1713 return VisitCompoundStmt(SE->getSubStmt()); 1714} 1715 1716CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) { 1717 // "switch" is a control-flow statement. Thus we stop processing the current 1718 // block. 1719 CFGBlock* SwitchSuccessor = NULL; 1720 1721 if (Block) { 1722 if (badCFG) 1723 return 0; 1724 SwitchSuccessor = Block; 1725 } else SwitchSuccessor = Succ; 1726 1727 // Save the current "switch" context. 1728 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 1729 save_default(DefaultCaseBlock); 1730 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1731 1732 // Set the "default" case to be the block after the switch statement. If the 1733 // switch statement contains a "default:", this value will be overwritten with 1734 // the block for that code. 1735 DefaultCaseBlock = SwitchSuccessor; 1736 1737 // Create a new block that will contain the switch statement. 1738 SwitchTerminatedBlock = createBlock(false); 1739 1740 // Now process the switch body. The code after the switch is the implicit 1741 // successor. 1742 Succ = SwitchSuccessor; 1743 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 1744 1745 // When visiting the body, the case statements should automatically get linked 1746 // up to the switch. We also don't keep a pointer to the body, since all 1747 // control-flow from the switch goes to case/default statements. 1748 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 1749 Block = NULL; 1750 addStmt(Terminator->getBody()); 1751 if (Block) { 1752 if (badCFG) 1753 return 0; 1754 } 1755 1756 // If we have no "default:" case, the default transition is to the code 1757 // following the switch body. 1758 AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock); 1759 1760 // Add the terminator and condition in the switch block. 1761 SwitchTerminatedBlock->setTerminator(Terminator); 1762 assert(Terminator->getCond() && "switch condition must be non-NULL"); 1763 Block = SwitchTerminatedBlock; 1764 Block = addStmt(Terminator->getCond()); 1765 1766 // Finally, if the SwitchStmt contains a condition variable, add both the 1767 // SwitchStmt and the condition variable initialization to the CFG. 1768 if (VarDecl *VD = Terminator->getConditionVariable()) { 1769 if (Expr *Init = VD->getInit()) { 1770 autoCreateBlock(); 1771 AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd); 1772 addStmt(Init); 1773 } 1774 } 1775 1776 return Block; 1777} 1778 1779CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { 1780 // CaseStmts are essentially labels, so they are the first statement in a 1781 // block. 1782 CFGBlock *TopBlock = 0, *LastBlock = 0; 1783 1784 if (Stmt *Sub = CS->getSubStmt()) { 1785 // For deeply nested chains of CaseStmts, instead of doing a recursion 1786 // (which can blow out the stack), manually unroll and create blocks 1787 // along the way. 1788 while (isa<CaseStmt>(Sub)) { 1789 CFGBlock *CurrentBlock = createBlock(false); 1790 CurrentBlock->setLabel(CS); 1791 1792 if (TopBlock) 1793 AddSuccessor(LastBlock, CurrentBlock); 1794 else 1795 TopBlock = CurrentBlock; 1796 1797 AddSuccessor(SwitchTerminatedBlock, CurrentBlock); 1798 LastBlock = CurrentBlock; 1799 1800 CS = cast<CaseStmt>(Sub); 1801 Sub = CS->getSubStmt(); 1802 } 1803 1804 addStmt(Sub); 1805 } 1806 1807 CFGBlock* CaseBlock = Block; 1808 if (!CaseBlock) 1809 CaseBlock = createBlock(); 1810 1811 // Cases statements partition blocks, so this is the top of the basic block we 1812 // were processing (the "case XXX:" is the label). 1813 CaseBlock->setLabel(CS); 1814 1815 if (badCFG) 1816 return 0; 1817 1818 // Add this block to the list of successors for the block with the switch 1819 // statement. 1820 assert(SwitchTerminatedBlock); 1821 AddSuccessor(SwitchTerminatedBlock, CaseBlock); 1822 1823 // We set Block to NULL to allow lazy creation of a new block (if necessary) 1824 Block = NULL; 1825 1826 if (TopBlock) { 1827 AddSuccessor(LastBlock, CaseBlock); 1828 Succ = TopBlock; 1829 } 1830 else { 1831 // This block is now the implicit successor of other blocks. 1832 Succ = CaseBlock; 1833 } 1834 1835 return Succ; 1836} 1837 1838CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { 1839 if (Terminator->getSubStmt()) 1840 addStmt(Terminator->getSubStmt()); 1841 1842 DefaultCaseBlock = Block; 1843 1844 if (!DefaultCaseBlock) 1845 DefaultCaseBlock = createBlock(); 1846 1847 // Default statements partition blocks, so this is the top of the basic block 1848 // we were processing (the "default:" is the label). 1849 DefaultCaseBlock->setLabel(Terminator); 1850 1851 if (badCFG) 1852 return 0; 1853 1854 // Unlike case statements, we don't add the default block to the successors 1855 // for the switch statement immediately. This is done when we finish 1856 // processing the switch statement. This allows for the default case 1857 // (including a fall-through to the code after the switch statement) to always 1858 // be the last successor of a switch-terminated block. 1859 1860 // We set Block to NULL to allow lazy creation of a new block (if necessary) 1861 Block = NULL; 1862 1863 // This block is now the implicit successor of other blocks. 1864 Succ = DefaultCaseBlock; 1865 1866 return DefaultCaseBlock; 1867} 1868 1869CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 1870 // "try"/"catch" is a control-flow statement. Thus we stop processing the 1871 // current block. 1872 CFGBlock* TrySuccessor = NULL; 1873 1874 if (Block) { 1875 if (badCFG) 1876 return 0; 1877 TrySuccessor = Block; 1878 } else TrySuccessor = Succ; 1879 1880 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 1881 1882 // Create a new block that will contain the try statement. 1883 CFGBlock *NewTryTerminatedBlock = createBlock(false); 1884 // Add the terminator in the try block. 1885 NewTryTerminatedBlock->setTerminator(Terminator); 1886 1887 bool HasCatchAll = false; 1888 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 1889 // The code after the try is the implicit successor. 1890 Succ = TrySuccessor; 1891 CXXCatchStmt *CS = Terminator->getHandler(h); 1892 if (CS->getExceptionDecl() == 0) { 1893 HasCatchAll = true; 1894 } 1895 Block = NULL; 1896 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 1897 if (CatchBlock == 0) 1898 return 0; 1899 // Add this block to the list of successors for the block with the try 1900 // statement. 1901 AddSuccessor(NewTryTerminatedBlock, CatchBlock); 1902 } 1903 if (!HasCatchAll) { 1904 if (PrevTryTerminatedBlock) 1905 AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 1906 else 1907 AddSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 1908 } 1909 1910 // The code after the try is the implicit successor. 1911 Succ = TrySuccessor; 1912 1913 // Save the current "try" context. 1914 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock); 1915 TryTerminatedBlock = NewTryTerminatedBlock; 1916 1917 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 1918 Block = NULL; 1919 Block = addStmt(Terminator->getTryBlock()); 1920 return Block; 1921} 1922 1923CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) { 1924 // CXXCatchStmt are treated like labels, so they are the first statement in a 1925 // block. 1926 1927 if (CS->getHandlerBlock()) 1928 addStmt(CS->getHandlerBlock()); 1929 1930 CFGBlock* CatchBlock = Block; 1931 if (!CatchBlock) 1932 CatchBlock = createBlock(); 1933 1934 CatchBlock->setLabel(CS); 1935 1936 if (badCFG) 1937 return 0; 1938 1939 // We set Block to NULL to allow lazy creation of a new block (if necessary) 1940 Block = NULL; 1941 1942 return CatchBlock; 1943} 1944 1945CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C, 1946 AddStmtChoice asc) { 1947 AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue 1948 : AddStmtChoice::AlwaysAdd; 1949 autoCreateBlock(); 1950 AppendStmt(Block, C, AddStmtChoice(K)); 1951 return VisitChildren(C); 1952} 1953 1954CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { 1955 // Lazily create the indirect-goto dispatch block if there isn't one already. 1956 CFGBlock* IBlock = cfg->getIndirectGotoBlock(); 1957 1958 if (!IBlock) { 1959 IBlock = createBlock(false); 1960 cfg->setIndirectGotoBlock(IBlock); 1961 } 1962 1963 // IndirectGoto is a control-flow statement. Thus we stop processing the 1964 // current block and create a new one. 1965 if (badCFG) 1966 return 0; 1967 1968 Block = createBlock(false); 1969 Block->setTerminator(I); 1970 AddSuccessor(Block, IBlock); 1971 return addStmt(I->getTarget()); 1972} 1973 1974} // end anonymous namespace 1975 1976/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 1977/// no successors or predecessors. If this is the first block created in the 1978/// CFG, it is automatically set to be the Entry and Exit of the CFG. 1979CFGBlock* CFG::createBlock() { 1980 bool first_block = begin() == end(); 1981 1982 // Create the block. 1983 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 1984 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 1985 Blocks.push_back(Mem, BlkBVC); 1986 1987 // If this is the first block, set it as the Entry and Exit. 1988 if (first_block) 1989 Entry = Exit = &back(); 1990 1991 // Return the block. 1992 return &back(); 1993} 1994 1995/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 1996/// CFG is returned to the caller. 1997CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C, 1998 BuildOptions BO) { 1999 CFGBuilder Builder; 2000 return Builder.buildCFG(D, Statement, C, BO); 2001} 2002 2003//===----------------------------------------------------------------------===// 2004// CFG: Queries for BlkExprs. 2005//===----------------------------------------------------------------------===// 2006 2007namespace { 2008 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 2009} 2010 2011static void FindSubExprAssignments(Stmt *S, 2012 llvm::SmallPtrSet<Expr*,50>& Set) { 2013 if (!S) 2014 return; 2015 2016 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) { 2017 Stmt *child = *I; 2018 if (!child) 2019 continue; 2020 2021 if (BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 2022 if (B->isAssignmentOp()) Set.insert(B); 2023 2024 FindSubExprAssignments(child, Set); 2025 } 2026} 2027 2028static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 2029 BlkExprMapTy* M = new BlkExprMapTy(); 2030 2031 // Look for assignments that are used as subexpressions. These are the only 2032 // assignments that we want to *possibly* register as a block-level 2033 // expression. Basically, if an assignment occurs both in a subexpression and 2034 // at the block-level, it is a block-level expression. 2035 llvm::SmallPtrSet<Expr*,50> SubExprAssignments; 2036 2037 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 2038 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 2039 if (CFGStmt S = BI->getAs<CFGStmt>()) 2040 FindSubExprAssignments(S, SubExprAssignments); 2041 2042 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 2043 2044 // Iterate over the statements again on identify the Expr* and Stmt* at the 2045 // block-level that are block-level expressions. 2046 2047 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 2048 CFGStmt CS = BI->getAs<CFGStmt>(); 2049 if (!CS.isValid()) 2050 continue; 2051 if (Expr* Exp = dyn_cast<Expr>(CS.getStmt())) { 2052 2053 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 2054 // Assignment expressions that are not nested within another 2055 // expression are really "statements" whose value is never used by 2056 // another expression. 2057 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 2058 continue; 2059 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { 2060 // Special handling for statement expressions. The last statement in 2061 // the statement expression is also a block-level expr. 2062 const CompoundStmt* C = Terminator->getSubStmt(); 2063 if (!C->body_empty()) { 2064 unsigned x = M->size(); 2065 (*M)[C->body_back()] = x; 2066 } 2067 } 2068 2069 unsigned x = M->size(); 2070 (*M)[Exp] = x; 2071 } 2072 } 2073 2074 // Look at terminators. The condition is a block-level expression. 2075 2076 Stmt* S = (*I)->getTerminatorCondition(); 2077 2078 if (S && M->find(S) == M->end()) { 2079 unsigned x = M->size(); 2080 (*M)[S] = x; 2081 } 2082 } 2083 2084 return M; 2085} 2086 2087CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { 2088 assert(S != NULL); 2089 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 2090 2091 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 2092 BlkExprMapTy::iterator I = M->find(S); 2093 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 2094} 2095 2096unsigned CFG::getNumBlkExprs() { 2097 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 2098 return M->size(); 2099 else { 2100 // We assume callers interested in the number of BlkExprs will want 2101 // the map constructed if it doesn't already exist. 2102 BlkExprMap = (void*) PopulateBlkExprMap(*this); 2103 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 2104 } 2105} 2106 2107//===----------------------------------------------------------------------===// 2108// Filtered walking of the CFG. 2109//===----------------------------------------------------------------------===// 2110 2111bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 2112 const CFGBlock *From, const CFGBlock *To) { 2113 2114 if (F.IgnoreDefaultsWithCoveredEnums) { 2115 // If the 'To' has no label or is labeled but the label isn't a 2116 // CaseStmt then filter this edge. 2117 if (const SwitchStmt *S = 2118 dyn_cast_or_null<SwitchStmt>(From->getTerminator())) { 2119 if (S->isAllEnumCasesCovered()) { 2120 const Stmt *L = To->getLabel(); 2121 if (!L || !isa<CaseStmt>(L)) 2122 return true; 2123 } 2124 } 2125 } 2126 2127 return false; 2128} 2129 2130//===----------------------------------------------------------------------===// 2131// Cleanup: CFG dstor. 2132//===----------------------------------------------------------------------===// 2133 2134CFG::~CFG() { 2135 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 2136} 2137 2138//===----------------------------------------------------------------------===// 2139// CFG pretty printing 2140//===----------------------------------------------------------------------===// 2141 2142namespace { 2143 2144class StmtPrinterHelper : public PrinterHelper { 2145 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 2146 typedef llvm::DenseMap<Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 2147 StmtMapTy StmtMap; 2148 DeclMapTy DeclMap; 2149 signed CurrentBlock; 2150 unsigned CurrentStmt; 2151 const LangOptions &LangOpts; 2152public: 2153 2154 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 2155 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) { 2156 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 2157 unsigned j = 1; 2158 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 2159 BI != BEnd; ++BI, ++j ) { 2160 if (CFGStmt SE = BI->getAs<CFGStmt>()) { 2161 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 2162 StmtMap[SE] = P; 2163 2164 if (DeclStmt* DS = dyn_cast<DeclStmt>(SE.getStmt())) { 2165 DeclMap[DS->getSingleDecl()] = P; 2166 2167 } else if (IfStmt* IS = dyn_cast<IfStmt>(SE.getStmt())) { 2168 if (VarDecl* VD = IS->getConditionVariable()) 2169 DeclMap[VD] = P; 2170 2171 } else if (ForStmt* FS = dyn_cast<ForStmt>(SE.getStmt())) { 2172 if (VarDecl* VD = FS->getConditionVariable()) 2173 DeclMap[VD] = P; 2174 2175 } else if (WhileStmt* WS = dyn_cast<WhileStmt>(SE.getStmt())) { 2176 if (VarDecl* VD = WS->getConditionVariable()) 2177 DeclMap[VD] = P; 2178 2179 } else if (SwitchStmt* SS = dyn_cast<SwitchStmt>(SE.getStmt())) { 2180 if (VarDecl* VD = SS->getConditionVariable()) 2181 DeclMap[VD] = P; 2182 2183 } else if (CXXCatchStmt* CS = dyn_cast<CXXCatchStmt>(SE.getStmt())) { 2184 if (VarDecl* VD = CS->getExceptionDecl()) 2185 DeclMap[VD] = P; 2186 } 2187 } 2188 } 2189 } 2190 } 2191 2192 virtual ~StmtPrinterHelper() {} 2193 2194 const LangOptions &getLangOpts() const { return LangOpts; } 2195 void setBlockID(signed i) { CurrentBlock = i; } 2196 void setStmtID(unsigned i) { CurrentStmt = i; } 2197 2198 virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) { 2199 StmtMapTy::iterator I = StmtMap.find(S); 2200 2201 if (I == StmtMap.end()) 2202 return false; 2203 2204 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock 2205 && I->second.second == CurrentStmt) { 2206 return false; 2207 } 2208 2209 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2210 return true; 2211 } 2212 2213 bool handleDecl(Decl* D, llvm::raw_ostream& OS) { 2214 DeclMapTy::iterator I = DeclMap.find(D); 2215 2216 if (I == DeclMap.end()) 2217 return false; 2218 2219 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock 2220 && I->second.second == CurrentStmt) { 2221 return false; 2222 } 2223 2224 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2225 return true; 2226 } 2227}; 2228} // end anonymous namespace 2229 2230 2231namespace { 2232class CFGBlockTerminatorPrint 2233 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 2234 2235 llvm::raw_ostream& OS; 2236 StmtPrinterHelper* Helper; 2237 PrintingPolicy Policy; 2238public: 2239 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper, 2240 const PrintingPolicy &Policy) 2241 : OS(os), Helper(helper), Policy(Policy) {} 2242 2243 void VisitIfStmt(IfStmt* I) { 2244 OS << "if "; 2245 I->getCond()->printPretty(OS,Helper,Policy); 2246 } 2247 2248 // Default case. 2249 void VisitStmt(Stmt* Terminator) { 2250 Terminator->printPretty(OS, Helper, Policy); 2251 } 2252 2253 void VisitForStmt(ForStmt* F) { 2254 OS << "for (" ; 2255 if (F->getInit()) 2256 OS << "..."; 2257 OS << "; "; 2258 if (Stmt* C = F->getCond()) 2259 C->printPretty(OS, Helper, Policy); 2260 OS << "; "; 2261 if (F->getInc()) 2262 OS << "..."; 2263 OS << ")"; 2264 } 2265 2266 void VisitWhileStmt(WhileStmt* W) { 2267 OS << "while " ; 2268 if (Stmt* C = W->getCond()) 2269 C->printPretty(OS, Helper, Policy); 2270 } 2271 2272 void VisitDoStmt(DoStmt* D) { 2273 OS << "do ... while "; 2274 if (Stmt* C = D->getCond()) 2275 C->printPretty(OS, Helper, Policy); 2276 } 2277 2278 void VisitSwitchStmt(SwitchStmt* Terminator) { 2279 OS << "switch "; 2280 Terminator->getCond()->printPretty(OS, Helper, Policy); 2281 } 2282 2283 void VisitCXXTryStmt(CXXTryStmt* CS) { 2284 OS << "try ..."; 2285 } 2286 2287 void VisitConditionalOperator(ConditionalOperator* C) { 2288 C->getCond()->printPretty(OS, Helper, Policy); 2289 OS << " ? ... : ..."; 2290 } 2291 2292 void VisitChooseExpr(ChooseExpr* C) { 2293 OS << "__builtin_choose_expr( "; 2294 C->getCond()->printPretty(OS, Helper, Policy); 2295 OS << " )"; 2296 } 2297 2298 void VisitIndirectGotoStmt(IndirectGotoStmt* I) { 2299 OS << "goto *"; 2300 I->getTarget()->printPretty(OS, Helper, Policy); 2301 } 2302 2303 void VisitBinaryOperator(BinaryOperator* B) { 2304 if (!B->isLogicalOp()) { 2305 VisitExpr(B); 2306 return; 2307 } 2308 2309 B->getLHS()->printPretty(OS, Helper, Policy); 2310 2311 switch (B->getOpcode()) { 2312 case BO_LOr: 2313 OS << " || ..."; 2314 return; 2315 case BO_LAnd: 2316 OS << " && ..."; 2317 return; 2318 default: 2319 assert(false && "Invalid logical operator."); 2320 } 2321 } 2322 2323 void VisitExpr(Expr* E) { 2324 E->printPretty(OS, Helper, Policy); 2325 } 2326}; 2327} // end anonymous namespace 2328 2329static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper, 2330 const CFGElement &E) { 2331 if (CFGStmt CS = E.getAs<CFGStmt>()) { 2332 Stmt *S = CS; 2333 2334 if (Helper) { 2335 2336 // special printing for statement-expressions. 2337 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) { 2338 CompoundStmt* Sub = SE->getSubStmt(); 2339 2340 if (Sub->child_begin() != Sub->child_end()) { 2341 OS << "({ ... ; "; 2342 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 2343 OS << " })\n"; 2344 return; 2345 } 2346 } 2347 // special printing for comma expressions. 2348 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 2349 if (B->getOpcode() == BO_Comma) { 2350 OS << "... , "; 2351 Helper->handledStmt(B->getRHS(),OS); 2352 OS << '\n'; 2353 return; 2354 } 2355 } 2356 } 2357 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 2358 2359 if (isa<CXXOperatorCallExpr>(S)) { 2360 OS << " (OperatorCall)"; 2361 } 2362 else if (isa<CXXBindTemporaryExpr>(S)) { 2363 OS << " (BindTemporary)"; 2364 } 2365 2366 // Expressions need a newline. 2367 if (isa<Expr>(S)) 2368 OS << '\n'; 2369 2370 } else if (CFGInitializer IE = E.getAs<CFGInitializer>()) { 2371 CXXBaseOrMemberInitializer* I = IE; 2372 if (I->isBaseInitializer()) 2373 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 2374 else OS << I->getMember()->getName(); 2375 2376 OS << "("; 2377 if (Expr* IE = I->getInit()) 2378 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 2379 OS << ")"; 2380 2381 if (I->isBaseInitializer()) 2382 OS << " (Base initializer)\n"; 2383 else OS << " (Member initializer)\n"; 2384 2385 } else if (CFGAutomaticObjDtor DE = E.getAs<CFGAutomaticObjDtor>()){ 2386 VarDecl* VD = DE.getVarDecl(); 2387 Helper->handleDecl(VD, OS); 2388 2389 Type* T = VD->getType().getTypePtr(); 2390 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 2391 T = RT->getPointeeType().getTypePtr(); 2392 2393 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 2394 OS << " (Implicit destructor)\n"; 2395 } 2396 } 2397 2398static void print_block(llvm::raw_ostream& OS, const CFG* cfg, 2399 const CFGBlock& B, 2400 StmtPrinterHelper* Helper, bool print_edges) { 2401 2402 if (Helper) Helper->setBlockID(B.getBlockID()); 2403 2404 // Print the header. 2405 OS << "\n [ B" << B.getBlockID(); 2406 2407 if (&B == &cfg->getEntry()) 2408 OS << " (ENTRY) ]\n"; 2409 else if (&B == &cfg->getExit()) 2410 OS << " (EXIT) ]\n"; 2411 else if (&B == cfg->getIndirectGotoBlock()) 2412 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 2413 else 2414 OS << " ]\n"; 2415 2416 // Print the label of this block. 2417 if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) { 2418 2419 if (print_edges) 2420 OS << " "; 2421 2422 if (LabelStmt* L = dyn_cast<LabelStmt>(Label)) 2423 OS << L->getName(); 2424 else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 2425 OS << "case "; 2426 C->getLHS()->printPretty(OS, Helper, 2427 PrintingPolicy(Helper->getLangOpts())); 2428 if (C->getRHS()) { 2429 OS << " ... "; 2430 C->getRHS()->printPretty(OS, Helper, 2431 PrintingPolicy(Helper->getLangOpts())); 2432 } 2433 } else if (isa<DefaultStmt>(Label)) 2434 OS << "default"; 2435 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 2436 OS << "catch ("; 2437 if (CS->getExceptionDecl()) 2438 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 2439 0); 2440 else 2441 OS << "..."; 2442 OS << ")"; 2443 2444 } else 2445 assert(false && "Invalid label statement in CFGBlock."); 2446 2447 OS << ":\n"; 2448 } 2449 2450 // Iterate through the statements in the block and print them. 2451 unsigned j = 1; 2452 2453 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 2454 I != E ; ++I, ++j ) { 2455 2456 // Print the statement # in the basic block and the statement itself. 2457 if (print_edges) 2458 OS << " "; 2459 2460 OS << llvm::format("%3d", j) << ": "; 2461 2462 if (Helper) 2463 Helper->setStmtID(j); 2464 2465 print_elem(OS,Helper,*I); 2466 } 2467 2468 // Print the terminator of this block. 2469 if (B.getTerminator()) { 2470 if (print_edges) 2471 OS << " "; 2472 2473 OS << " T: "; 2474 2475 if (Helper) Helper->setBlockID(-1); 2476 2477 CFGBlockTerminatorPrint TPrinter(OS, Helper, 2478 PrintingPolicy(Helper->getLangOpts())); 2479 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator())); 2480 OS << '\n'; 2481 } 2482 2483 if (print_edges) { 2484 // Print the predecessors of this block. 2485 OS << " Predecessors (" << B.pred_size() << "):"; 2486 unsigned i = 0; 2487 2488 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 2489 I != E; ++I, ++i) { 2490 2491 if (i == 8 || (i-8) == 0) 2492 OS << "\n "; 2493 2494 OS << " B" << (*I)->getBlockID(); 2495 } 2496 2497 OS << '\n'; 2498 2499 // Print the successors of this block. 2500 OS << " Successors (" << B.succ_size() << "):"; 2501 i = 0; 2502 2503 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 2504 I != E; ++I, ++i) { 2505 2506 if (i == 8 || (i-8) % 10 == 0) 2507 OS << "\n "; 2508 2509 if (*I) 2510 OS << " B" << (*I)->getBlockID(); 2511 else 2512 OS << " NULL"; 2513 } 2514 2515 OS << '\n'; 2516 } 2517} 2518 2519 2520/// dump - A simple pretty printer of a CFG that outputs to stderr. 2521void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 2522 2523/// print - A simple pretty printer of a CFG that outputs to an ostream. 2524void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const { 2525 StmtPrinterHelper Helper(this, LO); 2526 2527 // Print the entry block. 2528 print_block(OS, this, getEntry(), &Helper, true); 2529 2530 // Iterate through the CFGBlocks and print them one by one. 2531 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 2532 // Skip the entry block, because we already printed it. 2533 if (&(**I) == &getEntry() || &(**I) == &getExit()) 2534 continue; 2535 2536 print_block(OS, this, **I, &Helper, true); 2537 } 2538 2539 // Print the exit block. 2540 print_block(OS, this, getExit(), &Helper, true); 2541 OS.flush(); 2542} 2543 2544/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 2545void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 2546 print(llvm::errs(), cfg, LO); 2547} 2548 2549/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 2550/// Generally this will only be called from CFG::print. 2551void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg, 2552 const LangOptions &LO) const { 2553 StmtPrinterHelper Helper(cfg, LO); 2554 print_block(OS, cfg, *this, &Helper, true); 2555} 2556 2557/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 2558void CFGBlock::printTerminator(llvm::raw_ostream &OS, 2559 const LangOptions &LO) const { 2560 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 2561 TPrinter.Visit(const_cast<Stmt*>(getTerminator())); 2562} 2563 2564Stmt* CFGBlock::getTerminatorCondition() { 2565 2566 if (!Terminator) 2567 return NULL; 2568 2569 Expr* E = NULL; 2570 2571 switch (Terminator->getStmtClass()) { 2572 default: 2573 break; 2574 2575 case Stmt::ForStmtClass: 2576 E = cast<ForStmt>(Terminator)->getCond(); 2577 break; 2578 2579 case Stmt::WhileStmtClass: 2580 E = cast<WhileStmt>(Terminator)->getCond(); 2581 break; 2582 2583 case Stmt::DoStmtClass: 2584 E = cast<DoStmt>(Terminator)->getCond(); 2585 break; 2586 2587 case Stmt::IfStmtClass: 2588 E = cast<IfStmt>(Terminator)->getCond(); 2589 break; 2590 2591 case Stmt::ChooseExprClass: 2592 E = cast<ChooseExpr>(Terminator)->getCond(); 2593 break; 2594 2595 case Stmt::IndirectGotoStmtClass: 2596 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 2597 break; 2598 2599 case Stmt::SwitchStmtClass: 2600 E = cast<SwitchStmt>(Terminator)->getCond(); 2601 break; 2602 2603 case Stmt::ConditionalOperatorClass: 2604 E = cast<ConditionalOperator>(Terminator)->getCond(); 2605 break; 2606 2607 case Stmt::BinaryOperatorClass: // '&&' and '||' 2608 E = cast<BinaryOperator>(Terminator)->getLHS(); 2609 break; 2610 2611 case Stmt::ObjCForCollectionStmtClass: 2612 return Terminator; 2613 } 2614 2615 return E ? E->IgnoreParens() : NULL; 2616} 2617 2618bool CFGBlock::hasBinaryBranchTerminator() const { 2619 2620 if (!Terminator) 2621 return false; 2622 2623 Expr* E = NULL; 2624 2625 switch (Terminator->getStmtClass()) { 2626 default: 2627 return false; 2628 2629 case Stmt::ForStmtClass: 2630 case Stmt::WhileStmtClass: 2631 case Stmt::DoStmtClass: 2632 case Stmt::IfStmtClass: 2633 case Stmt::ChooseExprClass: 2634 case Stmt::ConditionalOperatorClass: 2635 case Stmt::BinaryOperatorClass: 2636 return true; 2637 } 2638 2639 return E ? E->IgnoreParens() : NULL; 2640} 2641 2642 2643//===----------------------------------------------------------------------===// 2644// CFG Graphviz Visualization 2645//===----------------------------------------------------------------------===// 2646 2647 2648#ifndef NDEBUG 2649static StmtPrinterHelper* GraphHelper; 2650#endif 2651 2652void CFG::viewCFG(const LangOptions &LO) const { 2653#ifndef NDEBUG 2654 StmtPrinterHelper H(this, LO); 2655 GraphHelper = &H; 2656 llvm::ViewGraph(this,"CFG"); 2657 GraphHelper = NULL; 2658#endif 2659} 2660 2661namespace llvm { 2662template<> 2663struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 2664 2665 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 2666 2667 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) { 2668 2669#ifndef NDEBUG 2670 std::string OutSStr; 2671 llvm::raw_string_ostream Out(OutSStr); 2672 print_block(Out,Graph, *Node, GraphHelper, false); 2673 std::string& OutStr = Out.str(); 2674 2675 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 2676 2677 // Process string output to make it nicer... 2678 for (unsigned i = 0; i != OutStr.length(); ++i) 2679 if (OutStr[i] == '\n') { // Left justify 2680 OutStr[i] = '\\'; 2681 OutStr.insert(OutStr.begin()+i+1, 'l'); 2682 } 2683 2684 return OutStr; 2685#else 2686 return ""; 2687#endif 2688 } 2689}; 2690} // end namespace llvm 2691