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