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