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