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