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