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