CFG.cpp revision 3ff5b26ddd5857a50db4bfacdd198fb32eaebdac
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 if (!C->isElidable()) 2396 AppendStmt(Block, C, AddStmtChoice(K)); 2397 return VisitChildren(C); 2398} 2399 2400CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2401 AddStmtChoice asc) { 2402 if (asc.alwaysAdd()) { 2403 autoCreateBlock(); 2404 AppendStmt(Block, E, asc); 2405 // We do not want to propagate the AlwaysAdd property. 2406 asc = AddStmtChoice(asc.asLValue() ? AddStmtChoice::AsLValueNotAlwaysAdd 2407 : AddStmtChoice::NotAlwaysAdd); 2408 } 2409 return Visit(E->getSubExpr(), asc); 2410} 2411 2412CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2413 AddStmtChoice asc) { 2414 AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue 2415 : AddStmtChoice::AlwaysAdd; 2416 autoCreateBlock(); 2417 AppendStmt(Block, C, AddStmtChoice(K)); 2418 return VisitChildren(C); 2419} 2420 2421CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C, 2422 AddStmtChoice asc) { 2423 AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue 2424 : AddStmtChoice::AlwaysAdd; 2425 autoCreateBlock(); 2426 AppendStmt(Block, C, AddStmtChoice(K)); 2427 return VisitChildren(C); 2428} 2429 2430CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2431 AddStmtChoice asc) { 2432 if (asc.alwaysAdd()) { 2433 autoCreateBlock(); 2434 AppendStmt(Block, E, asc); 2435 // We do not want to propagate the AlwaysAdd property. 2436 asc = AddStmtChoice(asc.asLValue() ? AddStmtChoice::AsLValueNotAlwaysAdd 2437 : AddStmtChoice::NotAlwaysAdd); 2438 } 2439 return Visit(E->getSubExpr(), asc); 2440} 2441 2442CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { 2443 // Lazily create the indirect-goto dispatch block if there isn't one already. 2444 CFGBlock* IBlock = cfg->getIndirectGotoBlock(); 2445 2446 if (!IBlock) { 2447 IBlock = createBlock(false); 2448 cfg->setIndirectGotoBlock(IBlock); 2449 } 2450 2451 // IndirectGoto is a control-flow statement. Thus we stop processing the 2452 // current block and create a new one. 2453 if (badCFG) 2454 return 0; 2455 2456 Block = createBlock(false); 2457 Block->setTerminator(I); 2458 AddSuccessor(Block, IBlock); 2459 return addStmt(I->getTarget()); 2460} 2461 2462CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2463tryAgain: 2464 if (!E) { 2465 badCFG = true; 2466 return NULL; 2467 } 2468 switch (E->getStmtClass()) { 2469 default: 2470 return VisitChildrenForTemporaryDtors(E); 2471 2472 case Stmt::BinaryOperatorClass: 2473 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2474 2475 case Stmt::CXXBindTemporaryExprClass: 2476 return VisitCXXBindTemporaryExprForTemporaryDtors( 2477 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2478 2479 case Stmt::ConditionalOperatorClass: 2480 return VisitConditionalOperatorForTemporaryDtors( 2481 cast<ConditionalOperator>(E), BindToTemporary); 2482 2483 case Stmt::ImplicitCastExprClass: 2484 // For implicit cast we want BindToTemporary to be passed further. 2485 E = cast<CastExpr>(E)->getSubExpr(); 2486 goto tryAgain; 2487 2488 case Stmt::ParenExprClass: 2489 E = cast<ParenExpr>(E)->getSubExpr(); 2490 goto tryAgain; 2491 } 2492} 2493 2494CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2495 // When visiting children for destructors we want to visit them in reverse 2496 // order. Because there's no reverse iterator for children must to reverse 2497 // them in helper vector. 2498 typedef llvm::SmallVector<Stmt *, 4> ChildrenVect; 2499 ChildrenVect ChildrenRev; 2500 for (Stmt::child_iterator I = E->child_begin(), L = E->child_end(); 2501 I != L; ++I) { 2502 if (*I) ChildrenRev.push_back(*I); 2503 } 2504 2505 CFGBlock *B = Block; 2506 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2507 L = ChildrenRev.rend(); I != L; ++I) { 2508 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2509 B = R; 2510 } 2511 return B; 2512} 2513 2514CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2515 if (E->isLogicalOp()) { 2516 // Destructors for temporaries in LHS expression should be called after 2517 // those for RHS expression. Even if this will unnecessarily create a block, 2518 // this block will be used at least by the full expression. 2519 autoCreateBlock(); 2520 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2521 if (badCFG) 2522 return NULL; 2523 2524 Succ = ConfluenceBlock; 2525 Block = NULL; 2526 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2527 2528 if (RHSBlock) { 2529 if (badCFG) 2530 return NULL; 2531 2532 // If RHS expression did produce destructors we need to connect created 2533 // blocks to CFG in same manner as for binary operator itself. 2534 CFGBlock *LHSBlock = createBlock(false); 2535 LHSBlock->setTerminator(CFGTerminator(E, true)); 2536 2537 // For binary operator LHS block is before RHS in list of predecessors 2538 // of ConfluenceBlock. 2539 std::reverse(ConfluenceBlock->pred_begin(), 2540 ConfluenceBlock->pred_end()); 2541 2542 // See if this is a known constant. 2543 TryResult KnownVal = TryEvaluateBool(E->getLHS()); 2544 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2545 KnownVal.negate(); 2546 2547 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2548 // itself. 2549 if (E->getOpcode() == BO_LOr) { 2550 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2551 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2552 } else { 2553 assert (E->getOpcode() == BO_LAnd); 2554 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2555 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2556 } 2557 2558 Block = LHSBlock; 2559 return LHSBlock; 2560 } 2561 2562 Block = ConfluenceBlock; 2563 return ConfluenceBlock; 2564 } 2565 2566 else if (E->isAssignmentOp()) { 2567 // For assignment operator (=) LHS expression is visited 2568 // before RHS expression. For destructors visit them in reverse order. 2569 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2570 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2571 return LHSBlock ? LHSBlock : RHSBlock; 2572 } 2573 2574 // For any other binary operator RHS expression is visited before 2575 // LHS expression (order of children). For destructors visit them in reverse 2576 // order. 2577 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2578 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2579 return RHSBlock ? RHSBlock : LHSBlock; 2580} 2581 2582CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2583 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2584 // First add destructors for temporaries in subexpression. 2585 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2586 if (!BindToTemporary) { 2587 // If lifetime of temporary is not prolonged (by assigning to constant 2588 // reference) add destructor for it. 2589 autoCreateBlock(); 2590 appendTemporaryDtor(Block, E); 2591 B = Block; 2592 } 2593 return B; 2594} 2595 2596CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2597 ConditionalOperator *E, bool BindToTemporary) { 2598 // First add destructors for condition expression. Even if this will 2599 // unnecessarily create a block, this block will be used at least by the full 2600 // expression. 2601 autoCreateBlock(); 2602 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 2603 if (badCFG) 2604 return NULL; 2605 2606 // Try to add block with destructors for LHS expression. 2607 CFGBlock *LHSBlock = NULL; 2608 if (E->getLHS()) { 2609 Succ = ConfluenceBlock; 2610 Block = NULL; 2611 LHSBlock = VisitForTemporaryDtors(E->getLHS(), BindToTemporary); 2612 if (badCFG) 2613 return NULL; 2614 } 2615 2616 // Try to add block with destructors for RHS expression; 2617 Succ = ConfluenceBlock; 2618 Block = NULL; 2619 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), BindToTemporary); 2620 if (badCFG) 2621 return NULL; 2622 2623 if (!RHSBlock && !LHSBlock) { 2624 // If neither LHS nor RHS expression had temporaries to destroy don't create 2625 // more blocks. 2626 Block = ConfluenceBlock; 2627 return Block; 2628 } 2629 2630 Block = createBlock(false); 2631 Block->setTerminator(CFGTerminator(E, true)); 2632 2633 // See if this is a known constant. 2634 const TryResult &KnownVal = TryEvaluateBool(E->getCond()); 2635 2636 if (LHSBlock) { 2637 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 2638 } else if (KnownVal.isFalse()) { 2639 AddSuccessor(Block, NULL); 2640 } else { 2641 AddSuccessor(Block, ConfluenceBlock); 2642 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 2643 } 2644 2645 if (!RHSBlock) 2646 RHSBlock = ConfluenceBlock; 2647 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 2648 2649 return Block; 2650} 2651 2652} // end anonymous namespace 2653 2654/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 2655/// no successors or predecessors. If this is the first block created in the 2656/// CFG, it is automatically set to be the Entry and Exit of the CFG. 2657CFGBlock* CFG::createBlock() { 2658 bool first_block = begin() == end(); 2659 2660 // Create the block. 2661 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 2662 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 2663 Blocks.push_back(Mem, BlkBVC); 2664 2665 // If this is the first block, set it as the Entry and Exit. 2666 if (first_block) 2667 Entry = Exit = &back(); 2668 2669 // Return the block. 2670 return &back(); 2671} 2672 2673/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 2674/// CFG is returned to the caller. 2675CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C, 2676 BuildOptions BO) { 2677 CFGBuilder Builder; 2678 return Builder.buildCFG(D, Statement, C, BO); 2679} 2680 2681//===----------------------------------------------------------------------===// 2682// CFG: Queries for BlkExprs. 2683//===----------------------------------------------------------------------===// 2684 2685namespace { 2686 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 2687} 2688 2689static void FindSubExprAssignments(Stmt *S, 2690 llvm::SmallPtrSet<Expr*,50>& Set) { 2691 if (!S) 2692 return; 2693 2694 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) { 2695 Stmt *child = *I; 2696 if (!child) 2697 continue; 2698 2699 if (BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 2700 if (B->isAssignmentOp()) Set.insert(B); 2701 2702 FindSubExprAssignments(child, Set); 2703 } 2704} 2705 2706static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 2707 BlkExprMapTy* M = new BlkExprMapTy(); 2708 2709 // Look for assignments that are used as subexpressions. These are the only 2710 // assignments that we want to *possibly* register as a block-level 2711 // expression. Basically, if an assignment occurs both in a subexpression and 2712 // at the block-level, it is a block-level expression. 2713 llvm::SmallPtrSet<Expr*,50> SubExprAssignments; 2714 2715 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 2716 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 2717 if (CFGStmt S = BI->getAs<CFGStmt>()) 2718 FindSubExprAssignments(S, SubExprAssignments); 2719 2720 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 2721 2722 // Iterate over the statements again on identify the Expr* and Stmt* at the 2723 // block-level that are block-level expressions. 2724 2725 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 2726 CFGStmt CS = BI->getAs<CFGStmt>(); 2727 if (!CS.isValid()) 2728 continue; 2729 if (Expr* Exp = dyn_cast<Expr>(CS.getStmt())) { 2730 2731 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 2732 // Assignment expressions that are not nested within another 2733 // expression are really "statements" whose value is never used by 2734 // another expression. 2735 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 2736 continue; 2737 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { 2738 // Special handling for statement expressions. The last statement in 2739 // the statement expression is also a block-level expr. 2740 const CompoundStmt* C = Terminator->getSubStmt(); 2741 if (!C->body_empty()) { 2742 unsigned x = M->size(); 2743 (*M)[C->body_back()] = x; 2744 } 2745 } 2746 2747 unsigned x = M->size(); 2748 (*M)[Exp] = x; 2749 } 2750 } 2751 2752 // Look at terminators. The condition is a block-level expression. 2753 2754 Stmt* S = (*I)->getTerminatorCondition(); 2755 2756 if (S && M->find(S) == M->end()) { 2757 unsigned x = M->size(); 2758 (*M)[S] = x; 2759 } 2760 } 2761 2762 return M; 2763} 2764 2765CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { 2766 assert(S != NULL); 2767 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 2768 2769 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 2770 BlkExprMapTy::iterator I = M->find(S); 2771 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 2772} 2773 2774unsigned CFG::getNumBlkExprs() { 2775 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 2776 return M->size(); 2777 else { 2778 // We assume callers interested in the number of BlkExprs will want 2779 // the map constructed if it doesn't already exist. 2780 BlkExprMap = (void*) PopulateBlkExprMap(*this); 2781 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 2782 } 2783} 2784 2785//===----------------------------------------------------------------------===// 2786// Filtered walking of the CFG. 2787//===----------------------------------------------------------------------===// 2788 2789bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 2790 const CFGBlock *From, const CFGBlock *To) { 2791 2792 if (F.IgnoreDefaultsWithCoveredEnums) { 2793 // If the 'To' has no label or is labeled but the label isn't a 2794 // CaseStmt then filter this edge. 2795 if (const SwitchStmt *S = 2796 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 2797 if (S->isAllEnumCasesCovered()) { 2798 const Stmt *L = To->getLabel(); 2799 if (!L || !isa<CaseStmt>(L)) 2800 return true; 2801 } 2802 } 2803 } 2804 2805 return false; 2806} 2807 2808//===----------------------------------------------------------------------===// 2809// Cleanup: CFG dstor. 2810//===----------------------------------------------------------------------===// 2811 2812CFG::~CFG() { 2813 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 2814} 2815 2816//===----------------------------------------------------------------------===// 2817// CFG pretty printing 2818//===----------------------------------------------------------------------===// 2819 2820namespace { 2821 2822class StmtPrinterHelper : public PrinterHelper { 2823 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 2824 typedef llvm::DenseMap<Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 2825 StmtMapTy StmtMap; 2826 DeclMapTy DeclMap; 2827 signed CurrentBlock; 2828 unsigned CurrentStmt; 2829 const LangOptions &LangOpts; 2830public: 2831 2832 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 2833 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) { 2834 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 2835 unsigned j = 1; 2836 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 2837 BI != BEnd; ++BI, ++j ) { 2838 if (CFGStmt SE = BI->getAs<CFGStmt>()) { 2839 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 2840 StmtMap[SE] = P; 2841 2842 if (DeclStmt* DS = dyn_cast<DeclStmt>(SE.getStmt())) { 2843 DeclMap[DS->getSingleDecl()] = P; 2844 2845 } else if (IfStmt* IS = dyn_cast<IfStmt>(SE.getStmt())) { 2846 if (VarDecl* VD = IS->getConditionVariable()) 2847 DeclMap[VD] = P; 2848 2849 } else if (ForStmt* FS = dyn_cast<ForStmt>(SE.getStmt())) { 2850 if (VarDecl* VD = FS->getConditionVariable()) 2851 DeclMap[VD] = P; 2852 2853 } else if (WhileStmt* WS = dyn_cast<WhileStmt>(SE.getStmt())) { 2854 if (VarDecl* VD = WS->getConditionVariable()) 2855 DeclMap[VD] = P; 2856 2857 } else if (SwitchStmt* SS = dyn_cast<SwitchStmt>(SE.getStmt())) { 2858 if (VarDecl* VD = SS->getConditionVariable()) 2859 DeclMap[VD] = P; 2860 2861 } else if (CXXCatchStmt* CS = dyn_cast<CXXCatchStmt>(SE.getStmt())) { 2862 if (VarDecl* VD = CS->getExceptionDecl()) 2863 DeclMap[VD] = P; 2864 } 2865 } 2866 } 2867 } 2868 } 2869 2870 virtual ~StmtPrinterHelper() {} 2871 2872 const LangOptions &getLangOpts() const { return LangOpts; } 2873 void setBlockID(signed i) { CurrentBlock = i; } 2874 void setStmtID(unsigned i) { CurrentStmt = i; } 2875 2876 virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) { 2877 StmtMapTy::iterator I = StmtMap.find(S); 2878 2879 if (I == StmtMap.end()) 2880 return false; 2881 2882 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock 2883 && I->second.second == CurrentStmt) { 2884 return false; 2885 } 2886 2887 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2888 return true; 2889 } 2890 2891 bool handleDecl(Decl* D, llvm::raw_ostream& OS) { 2892 DeclMapTy::iterator I = DeclMap.find(D); 2893 2894 if (I == DeclMap.end()) 2895 return false; 2896 2897 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock 2898 && I->second.second == CurrentStmt) { 2899 return false; 2900 } 2901 2902 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2903 return true; 2904 } 2905}; 2906} // end anonymous namespace 2907 2908 2909namespace { 2910class CFGBlockTerminatorPrint 2911 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 2912 2913 llvm::raw_ostream& OS; 2914 StmtPrinterHelper* Helper; 2915 PrintingPolicy Policy; 2916public: 2917 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper, 2918 const PrintingPolicy &Policy) 2919 : OS(os), Helper(helper), Policy(Policy) {} 2920 2921 void VisitIfStmt(IfStmt* I) { 2922 OS << "if "; 2923 I->getCond()->printPretty(OS,Helper,Policy); 2924 } 2925 2926 // Default case. 2927 void VisitStmt(Stmt* Terminator) { 2928 Terminator->printPretty(OS, Helper, Policy); 2929 } 2930 2931 void VisitForStmt(ForStmt* F) { 2932 OS << "for (" ; 2933 if (F->getInit()) 2934 OS << "..."; 2935 OS << "; "; 2936 if (Stmt* C = F->getCond()) 2937 C->printPretty(OS, Helper, Policy); 2938 OS << "; "; 2939 if (F->getInc()) 2940 OS << "..."; 2941 OS << ")"; 2942 } 2943 2944 void VisitWhileStmt(WhileStmt* W) { 2945 OS << "while " ; 2946 if (Stmt* C = W->getCond()) 2947 C->printPretty(OS, Helper, Policy); 2948 } 2949 2950 void VisitDoStmt(DoStmt* D) { 2951 OS << "do ... while "; 2952 if (Stmt* C = D->getCond()) 2953 C->printPretty(OS, Helper, Policy); 2954 } 2955 2956 void VisitSwitchStmt(SwitchStmt* Terminator) { 2957 OS << "switch "; 2958 Terminator->getCond()->printPretty(OS, Helper, Policy); 2959 } 2960 2961 void VisitCXXTryStmt(CXXTryStmt* CS) { 2962 OS << "try ..."; 2963 } 2964 2965 void VisitConditionalOperator(ConditionalOperator* C) { 2966 C->getCond()->printPretty(OS, Helper, Policy); 2967 OS << " ? ... : ..."; 2968 } 2969 2970 void VisitChooseExpr(ChooseExpr* C) { 2971 OS << "__builtin_choose_expr( "; 2972 C->getCond()->printPretty(OS, Helper, Policy); 2973 OS << " )"; 2974 } 2975 2976 void VisitIndirectGotoStmt(IndirectGotoStmt* I) { 2977 OS << "goto *"; 2978 I->getTarget()->printPretty(OS, Helper, Policy); 2979 } 2980 2981 void VisitBinaryOperator(BinaryOperator* B) { 2982 if (!B->isLogicalOp()) { 2983 VisitExpr(B); 2984 return; 2985 } 2986 2987 B->getLHS()->printPretty(OS, Helper, Policy); 2988 2989 switch (B->getOpcode()) { 2990 case BO_LOr: 2991 OS << " || ..."; 2992 return; 2993 case BO_LAnd: 2994 OS << " && ..."; 2995 return; 2996 default: 2997 assert(false && "Invalid logical operator."); 2998 } 2999 } 3000 3001 void VisitExpr(Expr* E) { 3002 E->printPretty(OS, Helper, Policy); 3003 } 3004}; 3005} // end anonymous namespace 3006 3007static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper, 3008 const CFGElement &E) { 3009 if (CFGStmt CS = E.getAs<CFGStmt>()) { 3010 Stmt *S = CS; 3011 3012 if (Helper) { 3013 3014 // special printing for statement-expressions. 3015 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) { 3016 CompoundStmt* Sub = SE->getSubStmt(); 3017 3018 if (Sub->child_begin() != Sub->child_end()) { 3019 OS << "({ ... ; "; 3020 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3021 OS << " })\n"; 3022 return; 3023 } 3024 } 3025 // special printing for comma expressions. 3026 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3027 if (B->getOpcode() == BO_Comma) { 3028 OS << "... , "; 3029 Helper->handledStmt(B->getRHS(),OS); 3030 OS << '\n'; 3031 return; 3032 } 3033 } 3034 } 3035 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3036 3037 if (isa<CXXOperatorCallExpr>(S)) { 3038 OS << " (OperatorCall)"; 3039 } 3040 else if (isa<CXXBindTemporaryExpr>(S)) { 3041 OS << " (BindTemporary)"; 3042 } 3043 3044 // Expressions need a newline. 3045 if (isa<Expr>(S)) 3046 OS << '\n'; 3047 3048 } else if (CFGInitializer IE = E.getAs<CFGInitializer>()) { 3049 CXXBaseOrMemberInitializer* I = IE; 3050 if (I->isBaseInitializer()) 3051 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3052 else OS << I->getMember()->getName(); 3053 3054 OS << "("; 3055 if (Expr* IE = I->getInit()) 3056 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3057 OS << ")"; 3058 3059 if (I->isBaseInitializer()) 3060 OS << " (Base initializer)\n"; 3061 else OS << " (Member initializer)\n"; 3062 3063 } else if (CFGAutomaticObjDtor DE = E.getAs<CFGAutomaticObjDtor>()){ 3064 VarDecl* VD = DE.getVarDecl(); 3065 Helper->handleDecl(VD, OS); 3066 3067 const Type* T = VD->getType().getTypePtr(); 3068 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3069 T = RT->getPointeeType().getTypePtr(); 3070 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3071 T = ET; 3072 3073 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3074 OS << " (Implicit destructor)\n"; 3075 3076 } else if (CFGBaseDtor BE = E.getAs<CFGBaseDtor>()) { 3077 const CXXBaseSpecifier *BS = BE.getBaseSpecifier(); 3078 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3079 OS << " (Base object destructor)\n"; 3080 3081 } else if (CFGMemberDtor ME = E.getAs<CFGMemberDtor>()) { 3082 FieldDecl *FD = ME.getFieldDecl(); 3083 3084 const Type *T = FD->getType().getTypePtr(); 3085 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3086 T = ET; 3087 3088 OS << "this->" << FD->getName(); 3089 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3090 OS << " (Member object destructor)\n"; 3091 3092 } else if (CFGTemporaryDtor TE = E.getAs<CFGTemporaryDtor>()) { 3093 CXXBindTemporaryExpr *BT = TE.getBindTemporaryExpr(); 3094 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3095 OS << " (Temporary object destructor)\n"; 3096 } 3097} 3098 3099static void print_block(llvm::raw_ostream& OS, const CFG* cfg, 3100 const CFGBlock& B, 3101 StmtPrinterHelper* Helper, bool print_edges) { 3102 3103 if (Helper) Helper->setBlockID(B.getBlockID()); 3104 3105 // Print the header. 3106 OS << "\n [ B" << B.getBlockID(); 3107 3108 if (&B == &cfg->getEntry()) 3109 OS << " (ENTRY) ]\n"; 3110 else if (&B == &cfg->getExit()) 3111 OS << " (EXIT) ]\n"; 3112 else if (&B == cfg->getIndirectGotoBlock()) 3113 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 3114 else 3115 OS << " ]\n"; 3116 3117 // Print the label of this block. 3118 if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) { 3119 3120 if (print_edges) 3121 OS << " "; 3122 3123 if (LabelStmt* L = dyn_cast<LabelStmt>(Label)) 3124 OS << L->getName(); 3125 else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 3126 OS << "case "; 3127 C->getLHS()->printPretty(OS, Helper, 3128 PrintingPolicy(Helper->getLangOpts())); 3129 if (C->getRHS()) { 3130 OS << " ... "; 3131 C->getRHS()->printPretty(OS, Helper, 3132 PrintingPolicy(Helper->getLangOpts())); 3133 } 3134 } else if (isa<DefaultStmt>(Label)) 3135 OS << "default"; 3136 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3137 OS << "catch ("; 3138 if (CS->getExceptionDecl()) 3139 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3140 0); 3141 else 3142 OS << "..."; 3143 OS << ")"; 3144 3145 } else 3146 assert(false && "Invalid label statement in CFGBlock."); 3147 3148 OS << ":\n"; 3149 } 3150 3151 // Iterate through the statements in the block and print them. 3152 unsigned j = 1; 3153 3154 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3155 I != E ; ++I, ++j ) { 3156 3157 // Print the statement # in the basic block and the statement itself. 3158 if (print_edges) 3159 OS << " "; 3160 3161 OS << llvm::format("%3d", j) << ": "; 3162 3163 if (Helper) 3164 Helper->setStmtID(j); 3165 3166 print_elem(OS,Helper,*I); 3167 } 3168 3169 // Print the terminator of this block. 3170 if (B.getTerminator()) { 3171 if (print_edges) 3172 OS << " "; 3173 3174 OS << " T: "; 3175 3176 if (Helper) Helper->setBlockID(-1); 3177 3178 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3179 PrintingPolicy(Helper->getLangOpts())); 3180 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3181 OS << '\n'; 3182 } 3183 3184 if (print_edges) { 3185 // Print the predecessors of this block. 3186 OS << " Predecessors (" << B.pred_size() << "):"; 3187 unsigned i = 0; 3188 3189 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3190 I != E; ++I, ++i) { 3191 3192 if (i == 8 || (i-8) == 0) 3193 OS << "\n "; 3194 3195 OS << " B" << (*I)->getBlockID(); 3196 } 3197 3198 OS << '\n'; 3199 3200 // Print the successors of this block. 3201 OS << " Successors (" << B.succ_size() << "):"; 3202 i = 0; 3203 3204 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3205 I != E; ++I, ++i) { 3206 3207 if (i == 8 || (i-8) % 10 == 0) 3208 OS << "\n "; 3209 3210 if (*I) 3211 OS << " B" << (*I)->getBlockID(); 3212 else 3213 OS << " NULL"; 3214 } 3215 3216 OS << '\n'; 3217 } 3218} 3219 3220 3221/// dump - A simple pretty printer of a CFG that outputs to stderr. 3222void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 3223 3224/// print - A simple pretty printer of a CFG that outputs to an ostream. 3225void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const { 3226 StmtPrinterHelper Helper(this, LO); 3227 3228 // Print the entry block. 3229 print_block(OS, this, getEntry(), &Helper, true); 3230 3231 // Iterate through the CFGBlocks and print them one by one. 3232 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3233 // Skip the entry block, because we already printed it. 3234 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3235 continue; 3236 3237 print_block(OS, this, **I, &Helper, true); 3238 } 3239 3240 // Print the exit block. 3241 print_block(OS, this, getExit(), &Helper, true); 3242 OS.flush(); 3243} 3244 3245/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3246void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 3247 print(llvm::errs(), cfg, LO); 3248} 3249 3250/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3251/// Generally this will only be called from CFG::print. 3252void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg, 3253 const LangOptions &LO) const { 3254 StmtPrinterHelper Helper(cfg, LO); 3255 print_block(OS, cfg, *this, &Helper, true); 3256} 3257 3258/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3259void CFGBlock::printTerminator(llvm::raw_ostream &OS, 3260 const LangOptions &LO) const { 3261 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3262 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3263} 3264 3265Stmt* CFGBlock::getTerminatorCondition() { 3266 Stmt *Terminator = this->Terminator; 3267 if (!Terminator) 3268 return NULL; 3269 3270 Expr* E = NULL; 3271 3272 switch (Terminator->getStmtClass()) { 3273 default: 3274 break; 3275 3276 case Stmt::ForStmtClass: 3277 E = cast<ForStmt>(Terminator)->getCond(); 3278 break; 3279 3280 case Stmt::WhileStmtClass: 3281 E = cast<WhileStmt>(Terminator)->getCond(); 3282 break; 3283 3284 case Stmt::DoStmtClass: 3285 E = cast<DoStmt>(Terminator)->getCond(); 3286 break; 3287 3288 case Stmt::IfStmtClass: 3289 E = cast<IfStmt>(Terminator)->getCond(); 3290 break; 3291 3292 case Stmt::ChooseExprClass: 3293 E = cast<ChooseExpr>(Terminator)->getCond(); 3294 break; 3295 3296 case Stmt::IndirectGotoStmtClass: 3297 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3298 break; 3299 3300 case Stmt::SwitchStmtClass: 3301 E = cast<SwitchStmt>(Terminator)->getCond(); 3302 break; 3303 3304 case Stmt::ConditionalOperatorClass: 3305 E = cast<ConditionalOperator>(Terminator)->getCond(); 3306 break; 3307 3308 case Stmt::BinaryOperatorClass: // '&&' and '||' 3309 E = cast<BinaryOperator>(Terminator)->getLHS(); 3310 break; 3311 3312 case Stmt::ObjCForCollectionStmtClass: 3313 return Terminator; 3314 } 3315 3316 return E ? E->IgnoreParens() : NULL; 3317} 3318 3319bool CFGBlock::hasBinaryBranchTerminator() const { 3320 const Stmt *Terminator = this->Terminator; 3321 if (!Terminator) 3322 return false; 3323 3324 Expr* E = NULL; 3325 3326 switch (Terminator->getStmtClass()) { 3327 default: 3328 return false; 3329 3330 case Stmt::ForStmtClass: 3331 case Stmt::WhileStmtClass: 3332 case Stmt::DoStmtClass: 3333 case Stmt::IfStmtClass: 3334 case Stmt::ChooseExprClass: 3335 case Stmt::ConditionalOperatorClass: 3336 case Stmt::BinaryOperatorClass: 3337 return true; 3338 } 3339 3340 return E ? E->IgnoreParens() : NULL; 3341} 3342 3343 3344//===----------------------------------------------------------------------===// 3345// CFG Graphviz Visualization 3346//===----------------------------------------------------------------------===// 3347 3348 3349#ifndef NDEBUG 3350static StmtPrinterHelper* GraphHelper; 3351#endif 3352 3353void CFG::viewCFG(const LangOptions &LO) const { 3354#ifndef NDEBUG 3355 StmtPrinterHelper H(this, LO); 3356 GraphHelper = &H; 3357 llvm::ViewGraph(this,"CFG"); 3358 GraphHelper = NULL; 3359#endif 3360} 3361 3362namespace llvm { 3363template<> 3364struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3365 3366 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3367 3368 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) { 3369 3370#ifndef NDEBUG 3371 std::string OutSStr; 3372 llvm::raw_string_ostream Out(OutSStr); 3373 print_block(Out,Graph, *Node, GraphHelper, false); 3374 std::string& OutStr = Out.str(); 3375 3376 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3377 3378 // Process string output to make it nicer... 3379 for (unsigned i = 0; i != OutStr.length(); ++i) 3380 if (OutStr[i] == '\n') { // Left justify 3381 OutStr[i] = '\\'; 3382 OutStr.insert(OutStr.begin()+i+1, 'l'); 3383 } 3384 3385 return OutStr; 3386#else 3387 return ""; 3388#endif 3389 } 3390}; 3391} // end namespace llvm 3392