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