CFG.cpp revision fefb9f7009702befaf715e7a8debc9505c3c8634
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/CFG.h" 16#include "clang/AST/StmtVisitor.h" 17#include "clang/AST/PrettyPrinter.h" 18#include "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/SmallPtrSet.h" 20#include "llvm/Support/GraphWriter.h" 21#include "llvm/Support/Streams.h" 22#include "llvm/Support/Compiler.h" 23#include <llvm/Support/Allocator.h> 24#include <llvm/Support/Format.h> 25 26using namespace clang; 27 28namespace { 29 30// SaveAndRestore - A utility class that uses RIIA to save and restore 31// the value of a variable. 32template<typename T> 33struct VISIBILITY_HIDDEN SaveAndRestore { 34 SaveAndRestore(T& x) : X(x), old_value(x) {} 35 ~SaveAndRestore() { X = old_value; } 36 T get() { return old_value; } 37 38 T& X; 39 T old_value; 40}; 41 42static SourceLocation GetEndLoc(Decl* D) { 43 if (VarDecl* VD = dyn_cast<VarDecl>(D)) 44 if (Expr* Ex = VD->getInit()) 45 return Ex->getSourceRange().getEnd(); 46 47 return D->getLocation(); 48} 49 50/// CFGBuilder - This class implements CFG construction from an AST. 51/// The builder is stateful: an instance of the builder should be used to only 52/// construct a single CFG. 53/// 54/// Example usage: 55/// 56/// CFGBuilder builder; 57/// CFG* cfg = builder.BuildAST(stmt1); 58/// 59/// CFG construction is done via a recursive walk of an AST. We actually parse 60/// the AST in reverse order so that the successor of a basic block is 61/// constructed prior to its predecessor. This allows us to nicely capture 62/// implicit fall-throughs without extra basic blocks. 63/// 64class VISIBILITY_HIDDEN CFGBuilder { 65 ASTContext *Context; 66 CFG* cfg; 67 CFGBlock* Block; 68 CFGBlock* Succ; 69 CFGBlock* ContinueTargetBlock; 70 CFGBlock* BreakTargetBlock; 71 CFGBlock* SwitchTerminatedBlock; 72 CFGBlock* DefaultCaseBlock; 73 74 // LabelMap records the mapping from Label expressions to their blocks. 75 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy; 76 LabelMapTy LabelMap; 77 78 // A list of blocks that end with a "goto" that must be backpatched to their 79 // resolved targets upon completion of CFG construction. 80 typedef std::vector<CFGBlock*> BackpatchBlocksTy; 81 BackpatchBlocksTy BackpatchBlocks; 82 83 // A list of labels whose address has been taken (for indirect gotos). 84 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy; 85 LabelSetTy AddressTakenLabels; 86 87public: 88 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL), 89 ContinueTargetBlock(NULL), BreakTargetBlock(NULL), 90 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) { 91 // Create an empty CFG. 92 cfg = new CFG(); 93 } 94 95 ~CFGBuilder() { delete cfg; } 96 97 // buildCFG - Used by external clients to construct the CFG. 98 CFG* buildCFG(Stmt *Statement, ASTContext *C); 99 100private: 101 // Visitors to walk an AST and construct the CFG. 102 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd); 103 CFGBlock *VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd); 104 CFGBlock *VisitBlockExpr(BlockExpr* E, bool alwaysAdd); 105 CFGBlock *VisitBlockDeclRefExpr(BlockDeclRefExpr* E, bool alwaysAdd); 106 CFGBlock *VisitBreakStmt(BreakStmt *B); 107 CFGBlock *VisitCallExpr(CallExpr *C, bool alwaysAdd); 108 CFGBlock *VisitCaseStmt(CaseStmt *C); 109 CFGBlock *VisitChooseExpr(ChooseExpr *C); 110 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 111 CFGBlock *VisitConditionalOperator(ConditionalOperator *C); 112 CFGBlock *VisitContinueStmt(ContinueStmt *C); 113 CFGBlock *VisitDeclStmt(DeclStmt *DS); 114 CFGBlock *VisitDeclSubExpr(Decl* D); 115 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 116 CFGBlock *VisitDoStmt(DoStmt *D); 117 CFGBlock *VisitForStmt(ForStmt *F); 118 CFGBlock *VisitGotoStmt(GotoStmt* G); 119 CFGBlock *VisitIfStmt(IfStmt *I); 120 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 121 CFGBlock *VisitLabelStmt(LabelStmt *L); 122 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 123 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 124 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 125 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 126 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 127 CFGBlock *VisitReturnStmt(ReturnStmt* R); 128 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, bool alwaysAdd); 129 CFGBlock *VisitStmtExpr(StmtExpr *S, bool alwaysAdd); 130 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 131 CFGBlock *VisitWhileStmt(WhileStmt *W); 132 133 CFGBlock *Visit(Stmt *S, bool alwaysAdd = false); 134 CFGBlock *VisitStmt(Stmt *S, bool alwaysAdd); 135 CFGBlock *VisitChildren(Stmt* S); 136 137 // NYS == Not Yet Supported 138 CFGBlock* NYS() { 139 badCFG = true; 140 return Block; 141 } 142 143 void autoCreateBlock() { if (!Block) Block = createBlock(); } 144 CFGBlock *createBlock(bool add_successor = true); 145 bool FinishBlock(CFGBlock* B); 146 CFGBlock *addStmt(Stmt *S) { return Visit(S, true); } 147 148 bool badCFG; 149}; 150 151// FIXME: Add support for dependent-sized array types in C++? 152// Does it even make sense to build a CFG for an uninstantiated template? 153static VariableArrayType* FindVA(Type* t) { 154 while (ArrayType* vt = dyn_cast<ArrayType>(t)) { 155 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt)) 156 if (vat->getSizeExpr()) 157 return vat; 158 159 t = vt->getElementType().getTypePtr(); 160 } 161 162 return 0; 163} 164 165/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 166/// arbitrary statement. Examples include a single expression or a function 167/// body (compound statement). The ownership of the returned CFG is 168/// transferred to the caller. If CFG construction fails, this method returns 169/// NULL. 170CFG* CFGBuilder::buildCFG(Stmt* Statement, ASTContext* C) { 171 Context = C; 172 assert(cfg); 173 if (!Statement) 174 return NULL; 175 176 badCFG = false; 177 178 // Create an empty block that will serve as the exit block for the CFG. Since 179 // this is the first block added to the CFG, it will be implicitly registered 180 // as the exit block. 181 Succ = createBlock(); 182 assert (Succ == &cfg->getExit()); 183 Block = NULL; // the EXIT block is empty. Create all other blocks lazily. 184 185 // Visit the statements and create the CFG. 186 CFGBlock* B = addStmt(Statement); 187 if (!B) B = Succ; 188 189 if (B) { 190 // Finalize the last constructed block. This usually involves reversing the 191 // order of the statements in the block. 192 if (Block) FinishBlock(B); 193 194 // Backpatch the gotos whose label -> block mappings we didn't know when we 195 // encountered them. 196 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 197 E = BackpatchBlocks.end(); I != E; ++I ) { 198 199 CFGBlock* B = *I; 200 GotoStmt* G = cast<GotoStmt>(B->getTerminator()); 201 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 202 203 // If there is no target for the goto, then we are looking at an 204 // incomplete AST. Handle this by not registering a successor. 205 if (LI == LabelMap.end()) continue; 206 207 B->addSuccessor(LI->second); 208 } 209 210 // Add successors to the Indirect Goto Dispatch block (if we have one). 211 if (CFGBlock* B = cfg->getIndirectGotoBlock()) 212 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 213 E = AddressTakenLabels.end(); I != E; ++I ) { 214 215 // Lookup the target block. 216 LabelMapTy::iterator LI = LabelMap.find(*I); 217 218 // If there is no target block that contains label, then we are looking 219 // at an incomplete AST. Handle this by not registering a successor. 220 if (LI == LabelMap.end()) continue; 221 222 B->addSuccessor(LI->second); 223 } 224 225 Succ = B; 226 } 227 228 // Create an empty entry block that has no predecessors. 229 cfg->setEntry(createBlock()); 230 231 if (badCFG) { 232 delete cfg; 233 cfg = NULL; 234 return NULL; 235 } 236 237 // NULL out cfg so that repeated calls to the builder will fail and that the 238 // ownership of the constructed CFG is passed to the caller. 239 CFG* t = cfg; 240 cfg = NULL; 241 return t; 242} 243 244/// createBlock - Used to lazily create blocks that are connected 245/// to the current (global) succcessor. 246CFGBlock* CFGBuilder::createBlock(bool add_successor) { 247 CFGBlock* B = cfg->createBlock(); 248 if (add_successor && Succ) 249 B->addSuccessor(Succ); 250 return B; 251} 252 253/// FinishBlock - When the last statement has been added to the block, we must 254/// reverse the statements because they have been inserted in reverse order. 255bool CFGBuilder::FinishBlock(CFGBlock* B) { 256 if (badCFG) 257 return false; 258 259 assert(B); 260 B->reverseStmts(); 261 return true; 262} 263 264/// Visit - Walk the subtree of a statement and add extra 265/// blocks for ternary operators, &&, and ||. We also process "," and 266/// DeclStmts (which may contain nested control-flow). 267CFGBlock* CFGBuilder::Visit(Stmt * S, bool alwaysAdd) { 268tryAgain: 269 switch (S->getStmtClass()) { 270 default: 271 return VisitStmt(S, alwaysAdd); 272 273 case Stmt::AddrLabelExprClass: 274 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), alwaysAdd); 275 276 case Stmt::BinaryOperatorClass: 277 return VisitBinaryOperator(cast<BinaryOperator>(S), alwaysAdd); 278 279 case Stmt::BlockExprClass: 280 return VisitBlockExpr(cast<BlockExpr>(S), alwaysAdd); 281 282 case Stmt::BlockDeclRefExprClass: 283 return VisitBlockDeclRefExpr(cast<BlockDeclRefExpr>(S), alwaysAdd); 284 285 case Stmt::BreakStmtClass: 286 return VisitBreakStmt(cast<BreakStmt>(S)); 287 288 case Stmt::CallExprClass: 289 return VisitCallExpr(cast<CallExpr>(S), alwaysAdd); 290 291 case Stmt::CaseStmtClass: 292 return VisitCaseStmt(cast<CaseStmt>(S)); 293 294 case Stmt::ChooseExprClass: 295 return VisitChooseExpr(cast<ChooseExpr>(S)); 296 297 case Stmt::CompoundStmtClass: 298 return VisitCompoundStmt(cast<CompoundStmt>(S)); 299 300 case Stmt::ConditionalOperatorClass: 301 return VisitConditionalOperator(cast<ConditionalOperator>(S)); 302 303 case Stmt::ContinueStmtClass: 304 return VisitContinueStmt(cast<ContinueStmt>(S)); 305 306 case Stmt::DeclStmtClass: 307 return VisitDeclStmt(cast<DeclStmt>(S)); 308 309 case Stmt::DefaultStmtClass: 310 return VisitDefaultStmt(cast<DefaultStmt>(S)); 311 312 case Stmt::DoStmtClass: 313 return VisitDoStmt(cast<DoStmt>(S)); 314 315 case Stmt::ForStmtClass: 316 return VisitForStmt(cast<ForStmt>(S)); 317 318 case Stmt::GotoStmtClass: 319 return VisitGotoStmt(cast<GotoStmt>(S)); 320 321 case Stmt::IfStmtClass: 322 return VisitIfStmt(cast<IfStmt>(S)); 323 324 case Stmt::IndirectGotoStmtClass: 325 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 326 327 case Stmt::LabelStmtClass: 328 return VisitLabelStmt(cast<LabelStmt>(S)); 329 330 case Stmt::ObjCAtCatchStmtClass: 331 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 332 333 case Stmt::ObjCAtSynchronizedStmtClass: 334 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 335 336 case Stmt::ObjCAtThrowStmtClass: 337 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 338 339 case Stmt::ObjCAtTryStmtClass: 340 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 341 342 case Stmt::ObjCForCollectionStmtClass: 343 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 344 345 case Stmt::ParenExprClass: 346 S = cast<ParenExpr>(S)->getSubExpr(); 347 goto tryAgain; 348 349 case Stmt::NullStmtClass: 350 return Block; 351 352 case Stmt::ReturnStmtClass: 353 return VisitReturnStmt(cast<ReturnStmt>(S)); 354 355 case Stmt::SizeOfAlignOfExprClass: 356 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), alwaysAdd); 357 358 case Stmt::StmtExprClass: 359 return VisitStmtExpr(cast<StmtExpr>(S), alwaysAdd); 360 361 case Stmt::SwitchStmtClass: 362 return VisitSwitchStmt(cast<SwitchStmt>(S)); 363 364 case Stmt::WhileStmtClass: 365 return VisitWhileStmt(cast<WhileStmt>(S)); 366 } 367} 368 369CFGBlock *CFGBuilder::VisitStmt(Stmt *S, bool alwaysAdd) { 370 if (alwaysAdd) { 371 autoCreateBlock(); 372 Block->appendStmt(S); 373 } 374 375 return VisitChildren(S); 376} 377 378/// VisitChildren - Visit the children of a Stmt. 379CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) { 380 CFGBlock *B = Block; 381 for (Stmt::child_iterator I = Terminator->child_begin(), 382 E = Terminator->child_end(); I != E; ++I) { 383 if (*I) B = Visit(*I); 384 } 385 return B; 386} 387 388CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) { 389 AddressTakenLabels.insert(A->getLabel()); 390 391 if (alwaysAdd) { 392 autoCreateBlock(); 393 Block->appendStmt(A); 394 } 395 396 return Block; 397} 398 399CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) { 400 if (B->isLogicalOp()) { // && or || 401 402 // See if this is a known constant. 403 bool KnownTrue = false; 404 bool KnownFalse = false; 405 Expr::EvalResult Result; 406 if (B->getLHS()->Evaluate(Result, *Context) 407 && Result.Val.isInt()) { 408 if ((B->getOpcode() == BinaryOperator::LAnd) 409 == Result.Val.getInt().getBoolValue()) 410 KnownTrue = true; 411 else 412 KnownFalse = true; 413 } 414 415 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 416 ConfluenceBlock->appendStmt(B); 417 418 if (!FinishBlock(ConfluenceBlock)) 419 return 0; 420 421 // create the block evaluating the LHS 422 CFGBlock* LHSBlock = createBlock(false); 423 LHSBlock->setTerminator(B); 424 425 // create the block evaluating the RHS 426 Succ = ConfluenceBlock; 427 Block = NULL; 428 CFGBlock* RHSBlock = addStmt(B->getRHS()); 429 if (!FinishBlock(RHSBlock)) 430 return 0; 431 432 // Now link the LHSBlock with RHSBlock. 433 if (B->getOpcode() == BinaryOperator::LOr) { 434 if (KnownTrue) 435 LHSBlock->addSuccessor(0); 436 else 437 LHSBlock->addSuccessor(ConfluenceBlock); 438 if (KnownFalse) 439 LHSBlock->addSuccessor(0); 440 else 441 LHSBlock->addSuccessor(RHSBlock); 442 } else { 443 assert (B->getOpcode() == BinaryOperator::LAnd); 444 if (KnownFalse) 445 LHSBlock->addSuccessor(0); 446 else 447 LHSBlock->addSuccessor(RHSBlock); 448 if (KnownTrue) 449 LHSBlock->addSuccessor(0); 450 else 451 LHSBlock->addSuccessor(ConfluenceBlock); 452 } 453 454 // Generate the blocks for evaluating the LHS. 455 Block = LHSBlock; 456 return addStmt(B->getLHS()); 457 } 458 else if (B->getOpcode() == BinaryOperator::Comma) { // , 459 autoCreateBlock(); 460 Block->appendStmt(B); 461 addStmt(B->getRHS()); 462 return addStmt(B->getLHS()); 463 } 464 465 return VisitStmt(B, alwaysAdd); 466} 467 468CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr* E, bool alwaysAdd) { 469 // FIXME 470 return NYS(); 471} 472 473CFGBlock *CFGBuilder::VisitBlockDeclRefExpr(BlockDeclRefExpr* E, 474 bool alwaysAdd) { 475 // FIXME 476 return NYS(); 477} 478 479CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 480 // "break" is a control-flow statement. Thus we stop processing the current 481 // block. 482 if (Block && !FinishBlock(Block)) 483 return 0; 484 485 // Now create a new block that ends with the break statement. 486 Block = createBlock(false); 487 Block->setTerminator(B); 488 489 // If there is no target for the break, then we are looking at an incomplete 490 // AST. This means that the CFG cannot be constructed. 491 if (BreakTargetBlock) 492 Block->addSuccessor(BreakTargetBlock); 493 else 494 badCFG = true; 495 496 497 return Block; 498} 499 500CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) { 501 // If this is a call to a no-return function, this stops the block here. 502 if (FunctionDecl *FD = C->getDirectCallee()) { 503 504 if (!FD->hasAttr<NoReturnAttr>()) 505 return VisitStmt(C, alwaysAdd); 506 507 if (Block && !FinishBlock(Block)) 508 return 0; 509 510 // Create new block with no successor for the remaining pieces. 511 Block = createBlock(false); 512 Block->appendStmt(C); 513 514 // Wire this to the exit block directly. 515 Block->addSuccessor(&cfg->getExit()); 516 517 return VisitChildren(C); 518 } 519 520 return VisitStmt(C, alwaysAdd); 521} 522 523CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C) { 524 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 525 ConfluenceBlock->appendStmt(C); 526 if (!FinishBlock(ConfluenceBlock)) 527 return 0; 528 529 Succ = ConfluenceBlock; 530 Block = NULL; 531 CFGBlock* LHSBlock = addStmt(C->getLHS()); 532 if (!FinishBlock(LHSBlock)) 533 return 0; 534 535 Succ = ConfluenceBlock; 536 Block = NULL; 537 CFGBlock* RHSBlock = addStmt(C->getRHS()); 538 if (!FinishBlock(RHSBlock)) 539 return 0; 540 541 Block = createBlock(false); 542 Block->addSuccessor(LHSBlock); 543 Block->addSuccessor(RHSBlock); 544 Block->setTerminator(C); 545 return addStmt(C->getCond()); 546} 547 548 549CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) { 550 CFGBlock* LastBlock = Block; 551 552 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 553 I != E; ++I ) { 554 LastBlock = addStmt(*I); 555 } 556 return LastBlock; 557} 558 559CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) { 560 // See if this is a known constant. 561 bool KnownTrue = false; 562 bool KnownFalse = false; 563 Expr::EvalResult Result; 564 if (C->getCond()->Evaluate(Result, *Context) 565 && Result.Val.isInt()) { 566 if (Result.Val.getInt().getBoolValue()) 567 KnownTrue = true; 568 else 569 KnownFalse = true; 570 } 571 572 // Create the confluence block that will "merge" the results of the ternary 573 // expression. 574 CFGBlock* ConfluenceBlock = Block ? Block : createBlock(); 575 ConfluenceBlock->appendStmt(C); 576 if (!FinishBlock(ConfluenceBlock)) 577 return 0; 578 579 // Create a block for the LHS expression if there is an LHS expression. A 580 // GCC extension allows LHS to be NULL, causing the condition to be the 581 // value that is returned instead. 582 // e.g: x ?: y is shorthand for: x ? x : y; 583 Succ = ConfluenceBlock; 584 Block = NULL; 585 CFGBlock* LHSBlock = NULL; 586 if (C->getLHS()) { 587 LHSBlock = addStmt(C->getLHS()); 588 if (!FinishBlock(LHSBlock)) 589 return 0; 590 Block = NULL; 591 } 592 593 // Create the block for the RHS expression. 594 Succ = ConfluenceBlock; 595 CFGBlock* RHSBlock = addStmt(C->getRHS()); 596 if (!FinishBlock(RHSBlock)) 597 return 0; 598 599 // Create the block that will contain the condition. 600 Block = createBlock(false); 601 602 if (LHSBlock) { 603 if (KnownFalse) 604 Block->addSuccessor(0); 605 else 606 Block->addSuccessor(LHSBlock); 607 } else { 608 if (KnownFalse) { 609 // If we know the condition is false, add NULL as the successor for 610 // the block containing the condition. In this case, the confluence 611 // block will have just one predecessor. 612 Block->addSuccessor(0); 613 assert (ConfluenceBlock->pred_size() == 1); 614 } else { 615 // If we have no LHS expression, add the ConfluenceBlock as a direct 616 // successor for the block containing the condition. Moreover, we need to 617 // reverse the order of the predecessors in the ConfluenceBlock because 618 // the RHSBlock will have been added to the succcessors already, and we 619 // want the first predecessor to the the block containing the expression 620 // for the case when the ternary expression evaluates to true. 621 Block->addSuccessor(ConfluenceBlock); 622 assert (ConfluenceBlock->pred_size() == 2); 623 std::reverse(ConfluenceBlock->pred_begin(), 624 ConfluenceBlock->pred_end()); 625 } 626 } 627 628 if (KnownTrue) 629 Block->addSuccessor(0); 630 else 631 Block->addSuccessor(RHSBlock); 632 633 Block->setTerminator(C); 634 return addStmt(C->getCond()); 635} 636 637CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 638 autoCreateBlock(); 639 640 if (DS->isSingleDecl()) { 641 Block->appendStmt(DS); 642 return VisitDeclSubExpr(DS->getSingleDecl()); 643 } 644 645 CFGBlock *B = 0; 646 647 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 648 typedef llvm::SmallVector<Decl*,10> BufTy; 649 BufTy Buf(DS->decl_begin(), DS->decl_end()); 650 651 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 652 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 653 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 654 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 655 656 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 657 // automatically freed with the CFG. 658 DeclGroupRef DG(*I); 659 Decl *D = *I; 660 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 661 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 662 663 // Append the fake DeclStmt to block. 664 Block->appendStmt(DSNew); 665 B = VisitDeclSubExpr(D); 666 } 667 668 return B; 669} 670 671/// VisitDeclSubExpr - Utility method to add block-level expressions for 672/// initializers in Decls. 673CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) { 674 assert(Block); 675 676 VarDecl *VD = dyn_cast<VarDecl>(D); 677 678 if (!VD) 679 return Block; 680 681 Expr *Init = VD->getInit(); 682 683 if (Init) { 684 // Optimization: Don't create separate block-level statements for literals. 685 switch (Init->getStmtClass()) { 686 case Stmt::IntegerLiteralClass: 687 case Stmt::CharacterLiteralClass: 688 case Stmt::StringLiteralClass: 689 break; 690 default: 691 Block = addStmt(Init); 692 } 693 } 694 695 // If the type of VD is a VLA, then we must process its size expressions. 696 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0; 697 VA = FindVA(VA->getElementType().getTypePtr())) 698 Block = addStmt(VA->getSizeExpr()); 699 700 return Block; 701} 702 703CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) { 704 // See if this is a known constant. 705 bool KnownTrue = false; 706 bool KnownFalse = false; 707 Expr::EvalResult Result; 708 if (I->getCond()->Evaluate(Result, *Context) 709 && Result.Val.isInt()) { 710 if (Result.Val.getInt().getBoolValue()) 711 KnownTrue = true; 712 else 713 KnownFalse = true; 714 } 715 716 // We may see an if statement in the middle of a basic block, or it may be the 717 // first statement we are processing. In either case, we create a new basic 718 // block. First, we create the blocks for the then...else statements, and 719 // then we create the block containing the if statement. If we were in the 720 // middle of a block, we stop processing that block and reverse its 721 // statements. That block is then the implicit successor for the "then" and 722 // "else" clauses. 723 724 // The block we were proccessing is now finished. Make it the successor 725 // block. 726 if (Block) { 727 Succ = Block; 728 if (!FinishBlock(Block)) 729 return 0; 730 } 731 732 // Process the false branch. 733 CFGBlock* ElseBlock = Succ; 734 735 if (Stmt* Else = I->getElse()) { 736 SaveAndRestore<CFGBlock*> sv(Succ); 737 738 // NULL out Block so that the recursive call to Visit will 739 // create a new basic block. 740 Block = NULL; 741 ElseBlock = addStmt(Else); 742 743 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 744 ElseBlock = sv.get(); 745 else if (Block) { 746 if (!FinishBlock(ElseBlock)) 747 return 0; 748 } 749 } 750 751 // Process the true branch. 752 CFGBlock* ThenBlock; 753 { 754 Stmt* Then = I->getThen(); 755 assert (Then); 756 SaveAndRestore<CFGBlock*> sv(Succ); 757 Block = NULL; 758 ThenBlock = addStmt(Then); 759 760 if (!ThenBlock) { 761 // We can reach here if the "then" body has all NullStmts. 762 // Create an empty block so we can distinguish between true and false 763 // branches in path-sensitive analyses. 764 ThenBlock = createBlock(false); 765 ThenBlock->addSuccessor(sv.get()); 766 } else if (Block) { 767 if (!FinishBlock(ThenBlock)) 768 return 0; 769 } 770 } 771 772 // Now create a new block containing the if statement. 773 Block = createBlock(false); 774 775 // Set the terminator of the new block to the If statement. 776 Block->setTerminator(I); 777 778 // Now add the successors. 779 if (KnownFalse) 780 Block->addSuccessor(0); 781 else 782 Block->addSuccessor(ThenBlock); 783 if (KnownTrue) 784 Block->addSuccessor(0); 785 else 786 Block->addSuccessor(ElseBlock); 787 788 // Add the condition as the last statement in the new block. This may create 789 // new blocks as the condition may contain control-flow. Any newly created 790 // blocks will be pointed to be "Block". 791 return addStmt(I->getCond()); 792} 793 794 795CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) { 796 // If we were in the middle of a block we stop processing that block and 797 // reverse its statements. 798 // 799 // NOTE: If a "return" appears in the middle of a block, this means that the 800 // code afterwards is DEAD (unreachable). We still keep a basic block 801 // for that code; a simple "mark-and-sweep" from the entry block will be 802 // able to report such dead blocks. 803 if (Block) FinishBlock(Block); 804 805 // Create the new block. 806 Block = createBlock(false); 807 808 // The Exit block is the only successor. 809 Block->addSuccessor(&cfg->getExit()); 810 811 // Add the return statement to the block. This may create new blocks if R 812 // contains control-flow (short-circuit operations). 813 return VisitStmt(R, true); 814} 815 816CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) { 817 // Get the block of the labeled statement. Add it to our map. 818 addStmt(L->getSubStmt()); 819 CFGBlock* LabelBlock = Block; 820 821 if (!LabelBlock) // This can happen when the body is empty, i.e. 822 LabelBlock = createBlock(); // scopes that only contains NullStmts. 823 824 assert(LabelMap.find(L) == LabelMap.end() && "label already in map"); 825 LabelMap[ L ] = LabelBlock; 826 827 // Labels partition blocks, so this is the end of the basic block we were 828 // processing (L is the block's label). Because this is label (and we have 829 // already processed the substatement) there is no extra control-flow to worry 830 // about. 831 LabelBlock->setLabel(L); 832 if (!FinishBlock(LabelBlock)) 833 return 0; 834 835 // We set Block to NULL to allow lazy creation of a new block (if necessary); 836 Block = NULL; 837 838 // This block is now the implicit successor of other blocks. 839 Succ = LabelBlock; 840 841 return LabelBlock; 842} 843 844CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) { 845 // Goto is a control-flow statement. Thus we stop processing the current 846 // block and create a new one. 847 if (Block) 848 FinishBlock(Block); 849 850 Block = createBlock(false); 851 Block->setTerminator(G); 852 853 // If we already know the mapping to the label block add the successor now. 854 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 855 856 if (I == LabelMap.end()) 857 // We will need to backpatch this block later. 858 BackpatchBlocks.push_back(Block); 859 else 860 Block->addSuccessor(I->second); 861 862 return Block; 863} 864 865CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) { 866 // See if this is a known constant. 867 bool KnownTrue = false; 868 bool KnownFalse = false; 869 Expr::EvalResult Result; 870 if (F->getCond() && F->getCond()->Evaluate(Result, *Context) 871 && Result.Val.isInt()) { 872 if (Result.Val.getInt().getBoolValue()) 873 KnownTrue = true; 874 else 875 KnownFalse = true; 876 } 877 if (F->getCond() == 0) 878 KnownTrue = true; 879 880 CFGBlock* LoopSuccessor = NULL; 881 882 // "for" is a control-flow statement. Thus we stop processing the current 883 // block. 884 if (Block) { 885 if (!FinishBlock(Block)) 886 return 0; 887 LoopSuccessor = Block; 888 } else 889 LoopSuccessor = Succ; 890 891 // Because of short-circuit evaluation, the condition of the loop can span 892 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 893 // evaluate the condition. 894 CFGBlock* ExitConditionBlock = createBlock(false); 895 CFGBlock* EntryConditionBlock = ExitConditionBlock; 896 897 // Set the terminator for the "exit" condition block. 898 ExitConditionBlock->setTerminator(F); 899 900 // Now add the actual condition to the condition block. Because the condition 901 // itself may contain control-flow, new blocks may be created. 902 if (Stmt* C = F->getCond()) { 903 Block = ExitConditionBlock; 904 EntryConditionBlock = addStmt(C); 905 if (Block) { 906 if (!FinishBlock(EntryConditionBlock)) 907 return 0; 908 } 909 } 910 911 // The condition block is the implicit successor for the loop body as well as 912 // any code above the loop. 913 Succ = EntryConditionBlock; 914 915 // Now create the loop body. 916 { 917 assert (F->getBody()); 918 919 // Save the current values for Block, Succ, and continue and break targets 920 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), 921 save_continue(ContinueTargetBlock), 922 save_break(BreakTargetBlock); 923 924 // Create a new block to contain the (bottom) of the loop body. 925 Block = NULL; 926 927 if (Stmt* I = F->getInc()) { 928 // Generate increment code in its own basic block. This is the target of 929 // continue statements. 930 Succ = addStmt(I); 931 } else { 932 // No increment code. Create a special, empty, block that is used as the 933 // target block for "looping back" to the start of the loop. 934 assert(Succ == EntryConditionBlock); 935 Succ = createBlock(); 936 } 937 938 // Finish up the increment (or empty) block if it hasn't been already. 939 if (Block) { 940 assert(Block == Succ); 941 if (!FinishBlock(Block)) 942 return 0; 943 Block = 0; 944 } 945 946 ContinueTargetBlock = Succ; 947 948 // The starting block for the loop increment is the block that should 949 // represent the 'loop target' for looping back to the start of the loop. 950 ContinueTargetBlock->setLoopTarget(F); 951 952 // All breaks should go to the code following the loop. 953 BreakTargetBlock = LoopSuccessor; 954 955 // Now populate the body block, and in the process create new blocks as we 956 // walk the body of the loop. 957 CFGBlock* BodyBlock = addStmt(F->getBody()); 958 959 if (!BodyBlock) 960 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;" 961 else if (Block) { 962 if (!FinishBlock(BodyBlock)) 963 return 0; 964 } 965 966 if (KnownFalse) 967 ExitConditionBlock->addSuccessor(0); 968 else { 969 // This new body block is a successor to our "exit" condition block. 970 ExitConditionBlock->addSuccessor(BodyBlock); 971 } 972 } 973 974 if (KnownTrue) 975 ExitConditionBlock->addSuccessor(0); 976 else { 977 // Link up the condition block with the code that follows the loop. (the 978 // false branch). 979 ExitConditionBlock->addSuccessor(LoopSuccessor); 980 } 981 982 // If the loop contains initialization, create a new block for those 983 // statements. This block can also contain statements that precede the loop. 984 if (Stmt* I = F->getInit()) { 985 Block = createBlock(); 986 return addStmt(I); 987 } else { 988 // There is no loop initialization. We are thus basically a while loop. 989 // NULL out Block to force lazy block construction. 990 Block = NULL; 991 Succ = EntryConditionBlock; 992 return EntryConditionBlock; 993 } 994} 995 996CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { 997 // Objective-C fast enumeration 'for' statements: 998 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 999 // 1000 // for ( Type newVariable in collection_expression ) { statements } 1001 // 1002 // becomes: 1003 // 1004 // prologue: 1005 // 1. collection_expression 1006 // T. jump to loop_entry 1007 // loop_entry: 1008 // 1. side-effects of element expression 1009 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1010 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1011 // TB: 1012 // statements 1013 // T. jump to loop_entry 1014 // FB: 1015 // what comes after 1016 // 1017 // and 1018 // 1019 // Type existingItem; 1020 // for ( existingItem in expression ) { statements } 1021 // 1022 // becomes: 1023 // 1024 // the same with newVariable replaced with existingItem; the binding works 1025 // the same except that for one ObjCForCollectionStmt::getElement() returns 1026 // a DeclStmt and the other returns a DeclRefExpr. 1027 // 1028 1029 CFGBlock* LoopSuccessor = 0; 1030 1031 if (Block) { 1032 if (!FinishBlock(Block)) 1033 return 0; 1034 LoopSuccessor = Block; 1035 Block = 0; 1036 } else 1037 LoopSuccessor = Succ; 1038 1039 // Build the condition blocks. 1040 CFGBlock* ExitConditionBlock = createBlock(false); 1041 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1042 1043 // Set the terminator for the "exit" condition block. 1044 ExitConditionBlock->setTerminator(S); 1045 1046 // The last statement in the block should be the ObjCForCollectionStmt, which 1047 // performs the actual binding to 'element' and determines if there are any 1048 // more items in the collection. 1049 ExitConditionBlock->appendStmt(S); 1050 Block = ExitConditionBlock; 1051 1052 // Walk the 'element' expression to see if there are any side-effects. We 1053 // generate new blocks as necesary. We DON'T add the statement by default to 1054 // the CFG unless it contains control-flow. 1055 EntryConditionBlock = Visit(S->getElement(), false); 1056 if (Block) { 1057 if (!FinishBlock(EntryConditionBlock)) 1058 return 0; 1059 Block = 0; 1060 } 1061 1062 // The condition block is the implicit successor for the loop body as well as 1063 // any code above the loop. 1064 Succ = EntryConditionBlock; 1065 1066 // Now create the true branch. 1067 { 1068 // Save the current values for Succ, continue and break targets. 1069 SaveAndRestore<CFGBlock*> save_Succ(Succ), 1070 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock); 1071 1072 BreakTargetBlock = LoopSuccessor; 1073 ContinueTargetBlock = EntryConditionBlock; 1074 1075 CFGBlock* BodyBlock = addStmt(S->getBody()); 1076 1077 if (!BodyBlock) 1078 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1079 else if (Block) { 1080 if (!FinishBlock(BodyBlock)) 1081 return 0; 1082 } 1083 1084 // This new body block is a successor to our "exit" condition block. 1085 ExitConditionBlock->addSuccessor(BodyBlock); 1086 } 1087 1088 // Link up the condition block with the code that follows the loop. 1089 // (the false branch). 1090 ExitConditionBlock->addSuccessor(LoopSuccessor); 1091 1092 // Now create a prologue block to contain the collection expression. 1093 Block = createBlock(); 1094 return addStmt(S->getCollection()); 1095} 1096 1097CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) { 1098 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1099 1100 // Inline the body. 1101 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1102 1103 // The sync body starts its own basic block. This makes it a little easier 1104 // for diagnostic clients. 1105 if (SyncBlock) { 1106 if (!FinishBlock(SyncBlock)) 1107 return 0; 1108 1109 Block = 0; 1110 } 1111 1112 Succ = SyncBlock; 1113 1114 // Inline the sync expression. 1115 return addStmt(S->getSynchExpr()); 1116} 1117 1118CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) { 1119 // FIXME 1120 return NYS(); 1121} 1122 1123CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) { 1124 // See if this is a known constant. 1125 bool KnownTrue = false; 1126 bool KnownFalse = false; 1127 Expr::EvalResult Result; 1128 if (W->getCond()->Evaluate(Result, *Context) 1129 && Result.Val.isInt()) { 1130 if (Result.Val.getInt().getBoolValue()) 1131 KnownTrue = true; 1132 else 1133 KnownFalse = true; 1134 } 1135 1136 CFGBlock* LoopSuccessor = NULL; 1137 1138 // "while" is a control-flow statement. Thus we stop processing the current 1139 // block. 1140 if (Block) { 1141 if (!FinishBlock(Block)) 1142 return 0; 1143 LoopSuccessor = Block; 1144 } else 1145 LoopSuccessor = Succ; 1146 1147 // Because of short-circuit evaluation, the condition of the loop can span 1148 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1149 // evaluate the condition. 1150 CFGBlock* ExitConditionBlock = createBlock(false); 1151 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1152 1153 // Set the terminator for the "exit" condition block. 1154 ExitConditionBlock->setTerminator(W); 1155 1156 // Now add the actual condition to the condition block. Because the condition 1157 // itself may contain control-flow, new blocks may be created. Thus we update 1158 // "Succ" after adding the condition. 1159 if (Stmt* C = W->getCond()) { 1160 Block = ExitConditionBlock; 1161 EntryConditionBlock = addStmt(C); 1162 assert(Block == EntryConditionBlock); 1163 if (Block) { 1164 if (!FinishBlock(EntryConditionBlock)) 1165 return 0; 1166 } 1167 } 1168 1169 // The condition block is the implicit successor for the loop body as well as 1170 // any code above the loop. 1171 Succ = EntryConditionBlock; 1172 1173 // Process the loop body. 1174 { 1175 assert(W->getBody()); 1176 1177 // Save the current values for Block, Succ, and continue and break targets 1178 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), 1179 save_continue(ContinueTargetBlock), 1180 save_break(BreakTargetBlock); 1181 1182 // Create an empty block to represent the transition block for looping back 1183 // to the head of the loop. 1184 Block = 0; 1185 assert(Succ == EntryConditionBlock); 1186 Succ = createBlock(); 1187 Succ->setLoopTarget(W); 1188 ContinueTargetBlock = Succ; 1189 1190 // All breaks should go to the code following the loop. 1191 BreakTargetBlock = LoopSuccessor; 1192 1193 // NULL out Block to force lazy instantiation of blocks for the body. 1194 Block = NULL; 1195 1196 // Create the body. The returned block is the entry to the loop body. 1197 CFGBlock* BodyBlock = addStmt(W->getBody()); 1198 1199 if (!BodyBlock) 1200 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;" 1201 else if (Block) { 1202 if (!FinishBlock(BodyBlock)) 1203 return 0; 1204 } 1205 1206 if (KnownFalse) 1207 ExitConditionBlock->addSuccessor(0); 1208 else { 1209 // Add the loop body entry as a successor to the condition. 1210 ExitConditionBlock->addSuccessor(BodyBlock); 1211 } 1212 } 1213 1214 if (KnownTrue) 1215 ExitConditionBlock->addSuccessor(0); 1216 else { 1217 // Link up the condition block with the code that follows the loop. (the 1218 // false branch). 1219 ExitConditionBlock->addSuccessor(LoopSuccessor); 1220 } 1221 1222 // There can be no more statements in the condition block since we loop back 1223 // to this block. NULL out Block to force lazy creation of another block. 1224 Block = NULL; 1225 1226 // Return the condition block, which is the dominating block for the loop. 1227 Succ = EntryConditionBlock; 1228 return EntryConditionBlock; 1229} 1230 1231 1232CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { 1233 // FIXME: For now we pretend that @catch and the code it contains does not 1234 // exit. 1235 return Block; 1236} 1237 1238CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { 1239 // FIXME: This isn't complete. We basically treat @throw like a return 1240 // statement. 1241 1242 // If we were in the middle of a block we stop processing that block and 1243 // reverse its statements. 1244 if (Block && !FinishBlock(Block)) 1245 return 0; 1246 1247 // Create the new block. 1248 Block = createBlock(false); 1249 1250 // The Exit block is the only successor. 1251 Block->addSuccessor(&cfg->getExit()); 1252 1253 // Add the statement to the block. This may create new blocks if S contains 1254 // control-flow (short-circuit operations). 1255 return VisitStmt(S, true); 1256} 1257 1258CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) { 1259 // "do...while" is a control-flow statement. Thus we stop processing the 1260 // current block. 1261 1262 CFGBlock* LoopSuccessor = NULL; 1263 1264 if (Block) { 1265 if (!FinishBlock(Block)) 1266 return 0; 1267 LoopSuccessor = Block; 1268 } else 1269 LoopSuccessor = Succ; 1270 1271 // Because of short-circuit evaluation, the condition of the loop can span 1272 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1273 // evaluate the condition. 1274 CFGBlock* ExitConditionBlock = createBlock(false); 1275 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1276 1277 // Set the terminator for the "exit" condition block. 1278 ExitConditionBlock->setTerminator(D); 1279 1280 // Now add the actual condition to the condition block. Because the condition 1281 // itself may contain control-flow, new blocks may be created. 1282 if (Stmt* C = D->getCond()) { 1283 Block = ExitConditionBlock; 1284 EntryConditionBlock = addStmt(C); 1285 if (Block) { 1286 if (!FinishBlock(EntryConditionBlock)) 1287 return 0; 1288 } 1289 } 1290 1291 // The condition block is the implicit successor for the loop body. 1292 Succ = EntryConditionBlock; 1293 1294 // Process the loop body. 1295 CFGBlock* BodyBlock = NULL; 1296 { 1297 assert (D->getBody()); 1298 1299 // Save the current values for Block, Succ, and continue and break targets 1300 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ), 1301 save_continue(ContinueTargetBlock), 1302 save_break(BreakTargetBlock); 1303 1304 // All continues within this loop should go to the condition block 1305 ContinueTargetBlock = EntryConditionBlock; 1306 1307 // All breaks should go to the code following the loop. 1308 BreakTargetBlock = LoopSuccessor; 1309 1310 // NULL out Block to force lazy instantiation of blocks for the body. 1311 Block = NULL; 1312 1313 // Create the body. The returned block is the entry to the loop body. 1314 BodyBlock = addStmt(D->getBody()); 1315 1316 if (!BodyBlock) 1317 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 1318 else if (Block) { 1319 if (!FinishBlock(BodyBlock)) 1320 return 0; 1321 } 1322 1323 // Add an intermediate block between the BodyBlock and the 1324 // ExitConditionBlock to represent the "loop back" transition. Create an 1325 // empty block to represent the transition block for looping back to the 1326 // head of the loop. 1327 // FIXME: Can we do this more efficiently without adding another block? 1328 Block = NULL; 1329 Succ = BodyBlock; 1330 CFGBlock *LoopBackBlock = createBlock(); 1331 LoopBackBlock->setLoopTarget(D); 1332 1333 // Add the loop body entry as a successor to the condition. 1334 ExitConditionBlock->addSuccessor(LoopBackBlock); 1335 } 1336 1337 // Link up the condition block with the code that follows the loop. 1338 // (the false branch). 1339 ExitConditionBlock->addSuccessor(LoopSuccessor); 1340 1341 // There can be no more statements in the body block(s) since we loop back to 1342 // the body. NULL out Block to force lazy creation of another block. 1343 Block = NULL; 1344 1345 // Return the loop body, which is the dominating block for the loop. 1346 Succ = BodyBlock; 1347 return BodyBlock; 1348} 1349 1350CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) { 1351 // "continue" is a control-flow statement. Thus we stop processing the 1352 // current block. 1353 if (Block && !FinishBlock(Block)) 1354 return 0; 1355 1356 // Now create a new block that ends with the continue statement. 1357 Block = createBlock(false); 1358 Block->setTerminator(C); 1359 1360 // If there is no target for the continue, then we are looking at an 1361 // incomplete AST. This means the CFG cannot be constructed. 1362 if (ContinueTargetBlock) 1363 Block->addSuccessor(ContinueTargetBlock); 1364 else 1365 badCFG = true; 1366 1367 return Block; 1368} 1369 1370CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, 1371 bool alwaysAdd) { 1372 1373 if (alwaysAdd) { 1374 autoCreateBlock(); 1375 Block->appendStmt(E); 1376 } 1377 1378 // VLA types have expressions that must be evaluated. 1379 if (E->isArgumentType()) { 1380 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr()); 1381 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1382 addStmt(VA->getSizeExpr()); 1383 } 1384 1385 return Block; 1386} 1387 1388/// VisitStmtExpr - Utility method to handle (nested) statement 1389/// expressions (a GCC extension). 1390CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, bool alwaysAdd) { 1391 if (alwaysAdd) { 1392 autoCreateBlock(); 1393 Block->appendStmt(SE); 1394 } 1395 return VisitCompoundStmt(SE->getSubStmt()); 1396} 1397 1398CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) { 1399 // "switch" is a control-flow statement. Thus we stop processing the current 1400 // block. 1401 CFGBlock* SwitchSuccessor = NULL; 1402 1403 if (Block) { 1404 if (!FinishBlock(Block)) 1405 return 0; 1406 SwitchSuccessor = Block; 1407 } else SwitchSuccessor = Succ; 1408 1409 // Save the current "switch" context. 1410 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 1411 save_break(BreakTargetBlock), 1412 save_default(DefaultCaseBlock); 1413 1414 // Set the "default" case to be the block after the switch statement. If the 1415 // switch statement contains a "default:", this value will be overwritten with 1416 // the block for that code. 1417 DefaultCaseBlock = SwitchSuccessor; 1418 1419 // Create a new block that will contain the switch statement. 1420 SwitchTerminatedBlock = createBlock(false); 1421 1422 // Now process the switch body. The code after the switch is the implicit 1423 // successor. 1424 Succ = SwitchSuccessor; 1425 BreakTargetBlock = SwitchSuccessor; 1426 1427 // When visiting the body, the case statements should automatically get linked 1428 // up to the switch. We also don't keep a pointer to the body, since all 1429 // control-flow from the switch goes to case/default statements. 1430 assert (Terminator->getBody() && "switch must contain a non-NULL body"); 1431 Block = NULL; 1432 CFGBlock *BodyBlock = addStmt(Terminator->getBody()); 1433 if (Block) { 1434 if (!FinishBlock(BodyBlock)) 1435 return 0; 1436 } 1437 1438 // If we have no "default:" case, the default transition is to the code 1439 // following the switch body. 1440 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock); 1441 1442 // Add the terminator and condition in the switch block. 1443 SwitchTerminatedBlock->setTerminator(Terminator); 1444 assert (Terminator->getCond() && "switch condition must be non-NULL"); 1445 Block = SwitchTerminatedBlock; 1446 1447 return addStmt(Terminator->getCond()); 1448} 1449 1450CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { 1451 // CaseStmts are essentially labels, so they are the first statement in a 1452 // block. 1453 1454 if (CS->getSubStmt()) 1455 addStmt(CS->getSubStmt()); 1456 1457 CFGBlock* CaseBlock = Block; 1458 if (!CaseBlock) 1459 CaseBlock = createBlock(); 1460 1461 // Cases statements partition blocks, so this is the top of the basic block we 1462 // were processing (the "case XXX:" is the label). 1463 CaseBlock->setLabel(CS); 1464 1465 if (!FinishBlock(CaseBlock)) 1466 return 0; 1467 1468 // Add this block to the list of successors for the block with the switch 1469 // statement. 1470 assert(SwitchTerminatedBlock); 1471 SwitchTerminatedBlock->addSuccessor(CaseBlock); 1472 1473 // We set Block to NULL to allow lazy creation of a new block (if necessary) 1474 Block = NULL; 1475 1476 // This block is now the implicit successor of other blocks. 1477 Succ = CaseBlock; 1478 1479 return CaseBlock; 1480} 1481 1482CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { 1483 if (Terminator->getSubStmt()) 1484 addStmt(Terminator->getSubStmt()); 1485 1486 DefaultCaseBlock = Block; 1487 1488 if (!DefaultCaseBlock) 1489 DefaultCaseBlock = createBlock(); 1490 1491 // Default statements partition blocks, so this is the top of the basic block 1492 // we were processing (the "default:" is the label). 1493 DefaultCaseBlock->setLabel(Terminator); 1494 1495 if (!FinishBlock(DefaultCaseBlock)) 1496 return 0; 1497 1498 // Unlike case statements, we don't add the default block to the successors 1499 // for the switch statement immediately. This is done when we finish 1500 // processing the switch statement. This allows for the default case 1501 // (including a fall-through to the code after the switch statement) to always 1502 // be the last successor of a switch-terminated block. 1503 1504 // We set Block to NULL to allow lazy creation of a new block (if necessary) 1505 Block = NULL; 1506 1507 // This block is now the implicit successor of other blocks. 1508 Succ = DefaultCaseBlock; 1509 1510 return DefaultCaseBlock; 1511} 1512 1513CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { 1514 // Lazily create the indirect-goto dispatch block if there isn't one already. 1515 CFGBlock* IBlock = cfg->getIndirectGotoBlock(); 1516 1517 if (!IBlock) { 1518 IBlock = createBlock(false); 1519 cfg->setIndirectGotoBlock(IBlock); 1520 } 1521 1522 // IndirectGoto is a control-flow statement. Thus we stop processing the 1523 // current block and create a new one. 1524 if (Block && !FinishBlock(Block)) 1525 return 0; 1526 1527 Block = createBlock(false); 1528 Block->setTerminator(I); 1529 Block->addSuccessor(IBlock); 1530 return addStmt(I->getTarget()); 1531} 1532 1533} // end anonymous namespace 1534 1535/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 1536/// no successors or predecessors. If this is the first block created in the 1537/// CFG, it is automatically set to be the Entry and Exit of the CFG. 1538CFGBlock* CFG::createBlock() { 1539 bool first_block = begin() == end(); 1540 1541 // Create the block. 1542 Blocks.push_front(CFGBlock(NumBlockIDs++)); 1543 1544 // If this is the first block, set it as the Entry and Exit. 1545 if (first_block) Entry = Exit = &front(); 1546 1547 // Return the block. 1548 return &front(); 1549} 1550 1551/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 1552/// CFG is returned to the caller. 1553CFG* CFG::buildCFG(Stmt* Statement, ASTContext *C) { 1554 CFGBuilder Builder; 1555 return Builder.buildCFG(Statement, C); 1556} 1557 1558/// reverseStmts - Reverses the orders of statements within a CFGBlock. 1559void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); } 1560 1561//===----------------------------------------------------------------------===// 1562// CFG: Queries for BlkExprs. 1563//===----------------------------------------------------------------------===// 1564 1565namespace { 1566 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 1567} 1568 1569static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) { 1570 if (!Terminator) 1571 return; 1572 1573 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) { 1574 if (!*I) continue; 1575 1576 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I)) 1577 if (B->isAssignmentOp()) Set.insert(B); 1578 1579 FindSubExprAssignments(*I, Set); 1580 } 1581} 1582 1583static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 1584 BlkExprMapTy* M = new BlkExprMapTy(); 1585 1586 // Look for assignments that are used as subexpressions. These are the only 1587 // assignments that we want to *possibly* register as a block-level 1588 // expression. Basically, if an assignment occurs both in a subexpression and 1589 // at the block-level, it is a block-level expression. 1590 llvm::SmallPtrSet<Expr*,50> SubExprAssignments; 1591 1592 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 1593 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI) 1594 FindSubExprAssignments(*BI, SubExprAssignments); 1595 1596 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 1597 1598 // Iterate over the statements again on identify the Expr* and Stmt* at the 1599 // block-level that are block-level expressions. 1600 1601 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI) 1602 if (Expr* Exp = dyn_cast<Expr>(*BI)) { 1603 1604 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 1605 // Assignment expressions that are not nested within another 1606 // expression are really "statements" whose value is never used by 1607 // another expression. 1608 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 1609 continue; 1610 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { 1611 // Special handling for statement expressions. The last statement in 1612 // the statement expression is also a block-level expr. 1613 const CompoundStmt* C = Terminator->getSubStmt(); 1614 if (!C->body_empty()) { 1615 unsigned x = M->size(); 1616 (*M)[C->body_back()] = x; 1617 } 1618 } 1619 1620 unsigned x = M->size(); 1621 (*M)[Exp] = x; 1622 } 1623 1624 // Look at terminators. The condition is a block-level expression. 1625 1626 Stmt* S = I->getTerminatorCondition(); 1627 1628 if (S && M->find(S) == M->end()) { 1629 unsigned x = M->size(); 1630 (*M)[S] = x; 1631 } 1632 } 1633 1634 return M; 1635} 1636 1637CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { 1638 assert(S != NULL); 1639 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 1640 1641 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 1642 BlkExprMapTy::iterator I = M->find(S); 1643 1644 if (I == M->end()) return CFG::BlkExprNumTy(); 1645 else return CFG::BlkExprNumTy(I->second); 1646} 1647 1648unsigned CFG::getNumBlkExprs() { 1649 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 1650 return M->size(); 1651 else { 1652 // We assume callers interested in the number of BlkExprs will want 1653 // the map constructed if it doesn't already exist. 1654 BlkExprMap = (void*) PopulateBlkExprMap(*this); 1655 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 1656 } 1657} 1658 1659//===----------------------------------------------------------------------===// 1660// Cleanup: CFG dstor. 1661//===----------------------------------------------------------------------===// 1662 1663CFG::~CFG() { 1664 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 1665} 1666 1667//===----------------------------------------------------------------------===// 1668// CFG pretty printing 1669//===----------------------------------------------------------------------===// 1670 1671namespace { 1672 1673class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper { 1674 1675 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 1676 StmtMapTy StmtMap; 1677 signed CurrentBlock; 1678 unsigned CurrentStmt; 1679 const LangOptions &LangOpts; 1680public: 1681 1682 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 1683 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) { 1684 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 1685 unsigned j = 1; 1686 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ; 1687 BI != BEnd; ++BI, ++j ) 1688 StmtMap[*BI] = std::make_pair(I->getBlockID(),j); 1689 } 1690 } 1691 1692 virtual ~StmtPrinterHelper() {} 1693 1694 const LangOptions &getLangOpts() const { return LangOpts; } 1695 void setBlockID(signed i) { CurrentBlock = i; } 1696 void setStmtID(unsigned i) { CurrentStmt = i; } 1697 1698 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) { 1699 1700 StmtMapTy::iterator I = StmtMap.find(Terminator); 1701 1702 if (I == StmtMap.end()) 1703 return false; 1704 1705 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock 1706 && I->second.second == CurrentStmt) 1707 return false; 1708 1709 OS << "[B" << I->second.first << "." << I->second.second << "]"; 1710 return true; 1711 } 1712}; 1713} // end anonymous namespace 1714 1715 1716namespace { 1717class VISIBILITY_HIDDEN CFGBlockTerminatorPrint 1718 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 1719 1720 llvm::raw_ostream& OS; 1721 StmtPrinterHelper* Helper; 1722 PrintingPolicy Policy; 1723 1724public: 1725 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper, 1726 const PrintingPolicy &Policy) 1727 : OS(os), Helper(helper), Policy(Policy) {} 1728 1729 void VisitIfStmt(IfStmt* I) { 1730 OS << "if "; 1731 I->getCond()->printPretty(OS,Helper,Policy); 1732 } 1733 1734 // Default case. 1735 void VisitStmt(Stmt* Terminator) { 1736 Terminator->printPretty(OS, Helper, Policy); 1737 } 1738 1739 void VisitForStmt(ForStmt* F) { 1740 OS << "for (" ; 1741 if (F->getInit()) OS << "..."; 1742 OS << "; "; 1743 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy); 1744 OS << "; "; 1745 if (F->getInc()) OS << "..."; 1746 OS << ")"; 1747 } 1748 1749 void VisitWhileStmt(WhileStmt* W) { 1750 OS << "while " ; 1751 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy); 1752 } 1753 1754 void VisitDoStmt(DoStmt* D) { 1755 OS << "do ... while "; 1756 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy); 1757 } 1758 1759 void VisitSwitchStmt(SwitchStmt* Terminator) { 1760 OS << "switch "; 1761 Terminator->getCond()->printPretty(OS, Helper, Policy); 1762 } 1763 1764 void VisitConditionalOperator(ConditionalOperator* C) { 1765 C->getCond()->printPretty(OS, Helper, Policy); 1766 OS << " ? ... : ..."; 1767 } 1768 1769 void VisitChooseExpr(ChooseExpr* C) { 1770 OS << "__builtin_choose_expr( "; 1771 C->getCond()->printPretty(OS, Helper, Policy); 1772 OS << " )"; 1773 } 1774 1775 void VisitIndirectGotoStmt(IndirectGotoStmt* I) { 1776 OS << "goto *"; 1777 I->getTarget()->printPretty(OS, Helper, Policy); 1778 } 1779 1780 void VisitBinaryOperator(BinaryOperator* B) { 1781 if (!B->isLogicalOp()) { 1782 VisitExpr(B); 1783 return; 1784 } 1785 1786 B->getLHS()->printPretty(OS, Helper, Policy); 1787 1788 switch (B->getOpcode()) { 1789 case BinaryOperator::LOr: 1790 OS << " || ..."; 1791 return; 1792 case BinaryOperator::LAnd: 1793 OS << " && ..."; 1794 return; 1795 default: 1796 assert(false && "Invalid logical operator."); 1797 } 1798 } 1799 1800 void VisitExpr(Expr* E) { 1801 E->printPretty(OS, Helper, Policy); 1802 } 1803}; 1804} // end anonymous namespace 1805 1806 1807static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper, 1808 Stmt* Terminator) { 1809 if (Helper) { 1810 // special printing for statement-expressions. 1811 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) { 1812 CompoundStmt* Sub = SE->getSubStmt(); 1813 1814 if (Sub->child_begin() != Sub->child_end()) { 1815 OS << "({ ... ; "; 1816 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 1817 OS << " })\n"; 1818 return; 1819 } 1820 } 1821 1822 // special printing for comma expressions. 1823 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) { 1824 if (B->getOpcode() == BinaryOperator::Comma) { 1825 OS << "... , "; 1826 Helper->handledStmt(B->getRHS(),OS); 1827 OS << '\n'; 1828 return; 1829 } 1830 } 1831 } 1832 1833 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 1834 1835 // Expressions need a newline. 1836 if (isa<Expr>(Terminator)) OS << '\n'; 1837} 1838 1839static void print_block(llvm::raw_ostream& OS, const CFG* cfg, 1840 const CFGBlock& B, 1841 StmtPrinterHelper* Helper, bool print_edges) { 1842 1843 if (Helper) Helper->setBlockID(B.getBlockID()); 1844 1845 // Print the header. 1846 OS << "\n [ B" << B.getBlockID(); 1847 1848 if (&B == &cfg->getEntry()) 1849 OS << " (ENTRY) ]\n"; 1850 else if (&B == &cfg->getExit()) 1851 OS << " (EXIT) ]\n"; 1852 else if (&B == cfg->getIndirectGotoBlock()) 1853 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 1854 else 1855 OS << " ]\n"; 1856 1857 // Print the label of this block. 1858 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) { 1859 1860 if (print_edges) 1861 OS << " "; 1862 1863 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator)) 1864 OS << L->getName(); 1865 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) { 1866 OS << "case "; 1867 C->getLHS()->printPretty(OS, Helper, 1868 PrintingPolicy(Helper->getLangOpts())); 1869 if (C->getRHS()) { 1870 OS << " ... "; 1871 C->getRHS()->printPretty(OS, Helper, 1872 PrintingPolicy(Helper->getLangOpts())); 1873 } 1874 } else if (isa<DefaultStmt>(Terminator)) 1875 OS << "default"; 1876 else 1877 assert(false && "Invalid label statement in CFGBlock."); 1878 1879 OS << ":\n"; 1880 } 1881 1882 // Iterate through the statements in the block and print them. 1883 unsigned j = 1; 1884 1885 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 1886 I != E ; ++I, ++j ) { 1887 1888 // Print the statement # in the basic block and the statement itself. 1889 if (print_edges) 1890 OS << " "; 1891 1892 OS << llvm::format("%3d", j) << ": "; 1893 1894 if (Helper) 1895 Helper->setStmtID(j); 1896 1897 print_stmt(OS,Helper,*I); 1898 } 1899 1900 // Print the terminator of this block. 1901 if (B.getTerminator()) { 1902 if (print_edges) 1903 OS << " "; 1904 1905 OS << " T: "; 1906 1907 if (Helper) Helper->setBlockID(-1); 1908 1909 CFGBlockTerminatorPrint TPrinter(OS, Helper, 1910 PrintingPolicy(Helper->getLangOpts())); 1911 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator())); 1912 OS << '\n'; 1913 } 1914 1915 if (print_edges) { 1916 // Print the predecessors of this block. 1917 OS << " Predecessors (" << B.pred_size() << "):"; 1918 unsigned i = 0; 1919 1920 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 1921 I != E; ++I, ++i) { 1922 1923 if (i == 8 || (i-8) == 0) 1924 OS << "\n "; 1925 1926 OS << " B" << (*I)->getBlockID(); 1927 } 1928 1929 OS << '\n'; 1930 1931 // Print the successors of this block. 1932 OS << " Successors (" << B.succ_size() << "):"; 1933 i = 0; 1934 1935 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 1936 I != E; ++I, ++i) { 1937 1938 if (i == 8 || (i-8) % 10 == 0) 1939 OS << "\n "; 1940 1941 if (*I) 1942 OS << " B" << (*I)->getBlockID(); 1943 else 1944 OS << " NULL"; 1945 } 1946 1947 OS << '\n'; 1948 } 1949} 1950 1951 1952/// dump - A simple pretty printer of a CFG that outputs to stderr. 1953void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 1954 1955/// print - A simple pretty printer of a CFG that outputs to an ostream. 1956void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const { 1957 StmtPrinterHelper Helper(this, LO); 1958 1959 // Print the entry block. 1960 print_block(OS, this, getEntry(), &Helper, true); 1961 1962 // Iterate through the CFGBlocks and print them one by one. 1963 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 1964 // Skip the entry block, because we already printed it. 1965 if (&(*I) == &getEntry() || &(*I) == &getExit()) 1966 continue; 1967 1968 print_block(OS, this, *I, &Helper, true); 1969 } 1970 1971 // Print the exit block. 1972 print_block(OS, this, getExit(), &Helper, true); 1973 OS.flush(); 1974} 1975 1976/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 1977void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 1978 print(llvm::errs(), cfg, LO); 1979} 1980 1981/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 1982/// Generally this will only be called from CFG::print. 1983void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg, 1984 const LangOptions &LO) const { 1985 StmtPrinterHelper Helper(cfg, LO); 1986 print_block(OS, cfg, *this, &Helper, true); 1987} 1988 1989/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 1990void CFGBlock::printTerminator(llvm::raw_ostream &OS, 1991 const LangOptions &LO) const { 1992 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 1993 TPrinter.Visit(const_cast<Stmt*>(getTerminator())); 1994} 1995 1996Stmt* CFGBlock::getTerminatorCondition() { 1997 1998 if (!Terminator) 1999 return NULL; 2000 2001 Expr* E = NULL; 2002 2003 switch (Terminator->getStmtClass()) { 2004 default: 2005 break; 2006 2007 case Stmt::ForStmtClass: 2008 E = cast<ForStmt>(Terminator)->getCond(); 2009 break; 2010 2011 case Stmt::WhileStmtClass: 2012 E = cast<WhileStmt>(Terminator)->getCond(); 2013 break; 2014 2015 case Stmt::DoStmtClass: 2016 E = cast<DoStmt>(Terminator)->getCond(); 2017 break; 2018 2019 case Stmt::IfStmtClass: 2020 E = cast<IfStmt>(Terminator)->getCond(); 2021 break; 2022 2023 case Stmt::ChooseExprClass: 2024 E = cast<ChooseExpr>(Terminator)->getCond(); 2025 break; 2026 2027 case Stmt::IndirectGotoStmtClass: 2028 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 2029 break; 2030 2031 case Stmt::SwitchStmtClass: 2032 E = cast<SwitchStmt>(Terminator)->getCond(); 2033 break; 2034 2035 case Stmt::ConditionalOperatorClass: 2036 E = cast<ConditionalOperator>(Terminator)->getCond(); 2037 break; 2038 2039 case Stmt::BinaryOperatorClass: // '&&' and '||' 2040 E = cast<BinaryOperator>(Terminator)->getLHS(); 2041 break; 2042 2043 case Stmt::ObjCForCollectionStmtClass: 2044 return Terminator; 2045 } 2046 2047 return E ? E->IgnoreParens() : NULL; 2048} 2049 2050bool CFGBlock::hasBinaryBranchTerminator() const { 2051 2052 if (!Terminator) 2053 return false; 2054 2055 Expr* E = NULL; 2056 2057 switch (Terminator->getStmtClass()) { 2058 default: 2059 return false; 2060 2061 case Stmt::ForStmtClass: 2062 case Stmt::WhileStmtClass: 2063 case Stmt::DoStmtClass: 2064 case Stmt::IfStmtClass: 2065 case Stmt::ChooseExprClass: 2066 case Stmt::ConditionalOperatorClass: 2067 case Stmt::BinaryOperatorClass: 2068 return true; 2069 } 2070 2071 return E ? E->IgnoreParens() : NULL; 2072} 2073 2074 2075//===----------------------------------------------------------------------===// 2076// CFG Graphviz Visualization 2077//===----------------------------------------------------------------------===// 2078 2079 2080#ifndef NDEBUG 2081static StmtPrinterHelper* GraphHelper; 2082#endif 2083 2084void CFG::viewCFG(const LangOptions &LO) const { 2085#ifndef NDEBUG 2086 StmtPrinterHelper H(this, LO); 2087 GraphHelper = &H; 2088 llvm::ViewGraph(this,"CFG"); 2089 GraphHelper = NULL; 2090#endif 2091} 2092 2093namespace llvm { 2094template<> 2095struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 2096 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph, 2097 bool ShortNames) { 2098 2099#ifndef NDEBUG 2100 std::string OutSStr; 2101 llvm::raw_string_ostream Out(OutSStr); 2102 print_block(Out,Graph, *Node, GraphHelper, false); 2103 std::string& OutStr = Out.str(); 2104 2105 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 2106 2107 // Process string output to make it nicer... 2108 for (unsigned i = 0; i != OutStr.length(); ++i) 2109 if (OutStr[i] == '\n') { // Left justify 2110 OutStr[i] = '\\'; 2111 OutStr.insert(OutStr.begin()+i+1, 'l'); 2112 } 2113 2114 return OutStr; 2115#else 2116 return ""; 2117#endif 2118 } 2119}; 2120} // end namespace llvm 2121