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