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