CFG.cpp revision c56c004e0b8030e8ca8614e7febe581221938b75
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().areExceptionsEnabled()) { 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 1221 // Create the block for the RHS expression. 1222 Succ = ConfluenceBlock; 1223 CFGBlock* RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 1224 if (badCFG) 1225 return 0; 1226 1227 // Create the block that will contain the condition. 1228 Block = createBlock(false); 1229 1230 // See if this is a known constant. 1231 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 1232 if (LHSBlock) 1233 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 1234 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 1235 Block->setTerminator(C); 1236 Expr *condExpr = C->getCond(); 1237 1238 CFGBlock *result = 0; 1239 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) result = addStmt(condExpr); 1243 1244 // Before that, run the common subexpression if there was one. 1245 // At least one of this or the above will be run. 1246 if (opaqueValue) result = addStmt(BCO->getCommon()); 1247 1248 return result; 1249} 1250 1251CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 1252 if (DS->isSingleDecl()) 1253 return VisitDeclSubExpr(DS); 1254 1255 CFGBlock *B = 0; 1256 1257 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 1258 typedef llvm::SmallVector<Decl*,10> BufTy; 1259 BufTy Buf(DS->decl_begin(), DS->decl_end()); 1260 1261 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 1262 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 1263 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 1264 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 1265 1266 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 1267 // automatically freed with the CFG. 1268 DeclGroupRef DG(*I); 1269 Decl *D = *I; 1270 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 1271 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 1272 1273 // Append the fake DeclStmt to block. 1274 B = VisitDeclSubExpr(DSNew); 1275 } 1276 1277 return B; 1278} 1279 1280/// VisitDeclSubExpr - Utility method to add block-level expressions for 1281/// DeclStmts and initializers in them. 1282CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt* DS) { 1283 assert(DS->isSingleDecl() && "Can handle single declarations only."); 1284 1285 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 1286 1287 if (!VD) { 1288 autoCreateBlock(); 1289 appendStmt(Block, DS); 1290 return Block; 1291 } 1292 1293 bool IsReference = false; 1294 bool HasTemporaries = false; 1295 1296 // Destructors of temporaries in initialization expression should be called 1297 // after initialization finishes. 1298 Expr *Init = VD->getInit(); 1299 if (Init) { 1300 IsReference = VD->getType()->isReferenceType(); 1301 HasTemporaries = isa<ExprWithCleanups>(Init); 1302 1303 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 1304 // Generate destructors for temporaries in initialization expression. 1305 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 1306 IsReference); 1307 } 1308 } 1309 1310 autoCreateBlock(); 1311 appendStmt(Block, DS); 1312 1313 if (Init) { 1314 if (HasTemporaries) 1315 // For expression with temporaries go directly to subexpression to omit 1316 // generating destructors for the second time. 1317 Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 1318 else 1319 Visit(Init); 1320 } 1321 1322 // If the type of VD is a VLA, then we must process its size expressions. 1323 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 1324 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1325 Block = addStmt(VA->getSizeExpr()); 1326 1327 // Remove variable from local scope. 1328 if (ScopePos && VD == *ScopePos) 1329 ++ScopePos; 1330 1331 return Block; 1332} 1333 1334CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) { 1335 // We may see an if statement in the middle of a basic block, or it may be the 1336 // first statement we are processing. In either case, we create a new basic 1337 // block. First, we create the blocks for the then...else statements, and 1338 // then we create the block containing the if statement. If we were in the 1339 // middle of a block, we stop processing that block. That block is then the 1340 // implicit successor for the "then" and "else" clauses. 1341 1342 // Save local scope position because in case of condition variable ScopePos 1343 // won't be restored when traversing AST. 1344 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1345 1346 // Create local scope for possible condition variable. 1347 // Store scope position. Add implicit destructor. 1348 if (VarDecl* VD = I->getConditionVariable()) { 1349 LocalScope::const_iterator BeginScopePos = ScopePos; 1350 addLocalScopeForVarDecl(VD); 1351 addAutomaticObjDtors(ScopePos, BeginScopePos, I); 1352 } 1353 1354 // The block we were proccessing is now finished. Make it the successor 1355 // block. 1356 if (Block) { 1357 Succ = Block; 1358 if (badCFG) 1359 return 0; 1360 } 1361 1362 // Process the false branch. 1363 CFGBlock* ElseBlock = Succ; 1364 1365 if (Stmt* Else = I->getElse()) { 1366 SaveAndRestore<CFGBlock*> sv(Succ); 1367 1368 // NULL out Block so that the recursive call to Visit will 1369 // create a new basic block. 1370 Block = NULL; 1371 1372 // If branch is not a compound statement create implicit scope 1373 // and add destructors. 1374 if (!isa<CompoundStmt>(Else)) 1375 addLocalScopeAndDtors(Else); 1376 1377 ElseBlock = addStmt(Else); 1378 1379 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 1380 ElseBlock = sv.get(); 1381 else if (Block) { 1382 if (badCFG) 1383 return 0; 1384 } 1385 } 1386 1387 // Process the true branch. 1388 CFGBlock* ThenBlock; 1389 { 1390 Stmt* Then = I->getThen(); 1391 assert(Then); 1392 SaveAndRestore<CFGBlock*> sv(Succ); 1393 Block = NULL; 1394 1395 // If branch is not a compound statement create implicit scope 1396 // and add destructors. 1397 if (!isa<CompoundStmt>(Then)) 1398 addLocalScopeAndDtors(Then); 1399 1400 ThenBlock = addStmt(Then); 1401 1402 if (!ThenBlock) { 1403 // We can reach here if the "then" body has all NullStmts. 1404 // Create an empty block so we can distinguish between true and false 1405 // branches in path-sensitive analyses. 1406 ThenBlock = createBlock(false); 1407 addSuccessor(ThenBlock, sv.get()); 1408 } else if (Block) { 1409 if (badCFG) 1410 return 0; 1411 } 1412 } 1413 1414 // Now create a new block containing the if statement. 1415 Block = createBlock(false); 1416 1417 // Set the terminator of the new block to the If statement. 1418 Block->setTerminator(I); 1419 1420 // See if this is a known constant. 1421 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 1422 1423 // Now add the successors. 1424 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 1425 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 1426 1427 // Add the condition as the last statement in the new block. This may create 1428 // new blocks as the condition may contain control-flow. Any newly created 1429 // blocks will be pointed to be "Block". 1430 Block = addStmt(I->getCond()); 1431 1432 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 1433 // and the condition variable initialization to the CFG. 1434 if (VarDecl *VD = I->getConditionVariable()) { 1435 if (Expr *Init = VD->getInit()) { 1436 autoCreateBlock(); 1437 appendStmt(Block, I, AddStmtChoice::AlwaysAdd); 1438 addStmt(Init); 1439 } 1440 } 1441 1442 return Block; 1443} 1444 1445 1446CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) { 1447 // If we were in the middle of a block we stop processing that block. 1448 // 1449 // NOTE: If a "return" appears in the middle of a block, this means that the 1450 // code afterwards is DEAD (unreachable). We still keep a basic block 1451 // for that code; a simple "mark-and-sweep" from the entry block will be 1452 // able to report such dead blocks. 1453 1454 // Create the new block. 1455 Block = createBlock(false); 1456 1457 // The Exit block is the only successor. 1458 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); 1459 addSuccessor(Block, &cfg->getExit()); 1460 1461 // Add the return statement to the block. This may create new blocks if R 1462 // contains control-flow (short-circuit operations). 1463 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 1464} 1465 1466CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt *L) { 1467 // Get the block of the labeled statement. Add it to our map. 1468 addStmt(L->getSubStmt()); 1469 CFGBlock *LabelBlock = Block; 1470 1471 if (!LabelBlock) // This can happen when the body is empty, i.e. 1472 LabelBlock = createBlock(); // scopes that only contains NullStmts. 1473 1474 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 1475 "label already in map"); 1476 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 1477 1478 // Labels partition blocks, so this is the end of the basic block we were 1479 // processing (L is the block's label). Because this is label (and we have 1480 // already processed the substatement) there is no extra control-flow to worry 1481 // about. 1482 LabelBlock->setLabel(L); 1483 if (badCFG) 1484 return 0; 1485 1486 // We set Block to NULL to allow lazy creation of a new block (if necessary); 1487 Block = NULL; 1488 1489 // This block is now the implicit successor of other blocks. 1490 Succ = LabelBlock; 1491 1492 return LabelBlock; 1493} 1494 1495CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) { 1496 // Goto is a control-flow statement. Thus we stop processing the current 1497 // block and create a new one. 1498 1499 Block = createBlock(false); 1500 Block->setTerminator(G); 1501 1502 // If we already know the mapping to the label block add the successor now. 1503 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 1504 1505 if (I == LabelMap.end()) 1506 // We will need to backpatch this block later. 1507 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 1508 else { 1509 JumpTarget JT = I->second; 1510 addAutomaticObjDtors(ScopePos, JT.scopePosition, G); 1511 addSuccessor(Block, JT.block); 1512 } 1513 1514 return Block; 1515} 1516 1517CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) { 1518 CFGBlock* LoopSuccessor = NULL; 1519 1520 // Save local scope position because in case of condition variable ScopePos 1521 // won't be restored when traversing AST. 1522 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1523 1524 // Create local scope for init statement and possible condition variable. 1525 // Add destructor for init statement and condition variable. 1526 // Store scope position for continue statement. 1527 if (Stmt* Init = F->getInit()) 1528 addLocalScopeForStmt(Init); 1529 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1530 1531 if (VarDecl* VD = F->getConditionVariable()) 1532 addLocalScopeForVarDecl(VD); 1533 LocalScope::const_iterator ContinueScopePos = ScopePos; 1534 1535 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); 1536 1537 // "for" is a control-flow statement. Thus we stop processing the current 1538 // block. 1539 if (Block) { 1540 if (badCFG) 1541 return 0; 1542 LoopSuccessor = Block; 1543 } else 1544 LoopSuccessor = Succ; 1545 1546 // Save the current value for the break targets. 1547 // All breaks should go to the code following the loop. 1548 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1549 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1550 1551 // Because of short-circuit evaluation, the condition of the loop can span 1552 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1553 // evaluate the condition. 1554 CFGBlock* ExitConditionBlock = createBlock(false); 1555 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1556 1557 // Set the terminator for the "exit" condition block. 1558 ExitConditionBlock->setTerminator(F); 1559 1560 // Now add the actual condition to the condition block. Because the condition 1561 // itself may contain control-flow, new blocks may be created. 1562 if (Stmt* C = F->getCond()) { 1563 Block = ExitConditionBlock; 1564 EntryConditionBlock = addStmt(C); 1565 if (badCFG) 1566 return 0; 1567 assert(Block == EntryConditionBlock || 1568 (Block == 0 && EntryConditionBlock == Succ)); 1569 1570 // If this block contains a condition variable, add both the condition 1571 // variable and initializer to the CFG. 1572 if (VarDecl *VD = F->getConditionVariable()) { 1573 if (Expr *Init = VD->getInit()) { 1574 autoCreateBlock(); 1575 appendStmt(Block, F, AddStmtChoice::AlwaysAdd); 1576 EntryConditionBlock = addStmt(Init); 1577 assert(Block == EntryConditionBlock); 1578 } 1579 } 1580 1581 if (Block) { 1582 if (badCFG) 1583 return 0; 1584 } 1585 } 1586 1587 // The condition block is the implicit successor for the loop body as well as 1588 // any code above the loop. 1589 Succ = EntryConditionBlock; 1590 1591 // See if this is a known constant. 1592 TryResult KnownVal(true); 1593 1594 if (F->getCond()) 1595 KnownVal = tryEvaluateBool(F->getCond()); 1596 1597 // Now create the loop body. 1598 { 1599 assert(F->getBody()); 1600 1601 // Save the current values for Block, Succ, and continue targets. 1602 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1603 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 1604 1605 // Create a new block to contain the (bottom) of the loop body. 1606 Block = NULL; 1607 1608 // Loop body should end with destructor of Condition variable (if any). 1609 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); 1610 1611 if (Stmt* I = F->getInc()) { 1612 // Generate increment code in its own basic block. This is the target of 1613 // continue statements. 1614 Succ = addStmt(I); 1615 } else { 1616 // No increment code. Create a special, empty, block that is used as the 1617 // target block for "looping back" to the start of the loop. 1618 assert(Succ == EntryConditionBlock); 1619 Succ = Block ? Block : createBlock(); 1620 } 1621 1622 // Finish up the increment (or empty) block if it hasn't been already. 1623 if (Block) { 1624 assert(Block == Succ); 1625 if (badCFG) 1626 return 0; 1627 Block = 0; 1628 } 1629 1630 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 1631 1632 // The starting block for the loop increment is the block that should 1633 // represent the 'loop target' for looping back to the start of the loop. 1634 ContinueJumpTarget.block->setLoopTarget(F); 1635 1636 // If body is not a compound statement create implicit scope 1637 // and add destructors. 1638 if (!isa<CompoundStmt>(F->getBody())) 1639 addLocalScopeAndDtors(F->getBody()); 1640 1641 // Now populate the body block, and in the process create new blocks as we 1642 // walk the body of the loop. 1643 CFGBlock* BodyBlock = addStmt(F->getBody()); 1644 1645 if (!BodyBlock) 1646 BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);" 1647 else if (badCFG) 1648 return 0; 1649 1650 // This new body block is a successor to our "exit" condition block. 1651 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1652 } 1653 1654 // Link up the condition block with the code that follows the loop. (the 1655 // false branch). 1656 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1657 1658 // If the loop contains initialization, create a new block for those 1659 // statements. This block can also contain statements that precede the loop. 1660 if (Stmt* I = F->getInit()) { 1661 Block = createBlock(); 1662 return addStmt(I); 1663 } 1664 1665 // There is no loop initialization. We are thus basically a while loop. 1666 // NULL out Block to force lazy block construction. 1667 Block = NULL; 1668 Succ = EntryConditionBlock; 1669 return EntryConditionBlock; 1670} 1671 1672CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 1673 if (asc.alwaysAdd()) { 1674 autoCreateBlock(); 1675 appendStmt(Block, M, asc); 1676 } 1677 return Visit(M->getBase()); 1678} 1679 1680CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) { 1681 // Objective-C fast enumeration 'for' statements: 1682 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 1683 // 1684 // for ( Type newVariable in collection_expression ) { statements } 1685 // 1686 // becomes: 1687 // 1688 // prologue: 1689 // 1. collection_expression 1690 // T. jump to loop_entry 1691 // loop_entry: 1692 // 1. side-effects of element expression 1693 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1694 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1695 // TB: 1696 // statements 1697 // T. jump to loop_entry 1698 // FB: 1699 // what comes after 1700 // 1701 // and 1702 // 1703 // Type existingItem; 1704 // for ( existingItem in expression ) { statements } 1705 // 1706 // becomes: 1707 // 1708 // the same with newVariable replaced with existingItem; the binding works 1709 // the same except that for one ObjCForCollectionStmt::getElement() returns 1710 // a DeclStmt and the other returns a DeclRefExpr. 1711 // 1712 1713 CFGBlock* LoopSuccessor = 0; 1714 1715 if (Block) { 1716 if (badCFG) 1717 return 0; 1718 LoopSuccessor = Block; 1719 Block = 0; 1720 } else 1721 LoopSuccessor = Succ; 1722 1723 // Build the condition blocks. 1724 CFGBlock* ExitConditionBlock = createBlock(false); 1725 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1726 1727 // Set the terminator for the "exit" condition block. 1728 ExitConditionBlock->setTerminator(S); 1729 1730 // The last statement in the block should be the ObjCForCollectionStmt, which 1731 // performs the actual binding to 'element' and determines if there are any 1732 // more items in the collection. 1733 appendStmt(ExitConditionBlock, S); 1734 Block = ExitConditionBlock; 1735 1736 // Walk the 'element' expression to see if there are any side-effects. We 1737 // generate new blocks as necesary. We DON'T add the statement by default to 1738 // the CFG unless it contains control-flow. 1739 EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd); 1740 if (Block) { 1741 if (badCFG) 1742 return 0; 1743 Block = 0; 1744 } 1745 1746 // The condition block is the implicit successor for the loop body as well as 1747 // any code above the loop. 1748 Succ = EntryConditionBlock; 1749 1750 // Now create the true branch. 1751 { 1752 // Save the current values for Succ, continue and break targets. 1753 SaveAndRestore<CFGBlock*> save_Succ(Succ); 1754 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1755 save_break(BreakJumpTarget); 1756 1757 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1758 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1759 1760 CFGBlock* BodyBlock = addStmt(S->getBody()); 1761 1762 if (!BodyBlock) 1763 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1764 else if (Block) { 1765 if (badCFG) 1766 return 0; 1767 } 1768 1769 // This new body block is a successor to our "exit" condition block. 1770 addSuccessor(ExitConditionBlock, BodyBlock); 1771 } 1772 1773 // Link up the condition block with the code that follows the loop. 1774 // (the false branch). 1775 addSuccessor(ExitConditionBlock, LoopSuccessor); 1776 1777 // Now create a prologue block to contain the collection expression. 1778 Block = createBlock(); 1779 return addStmt(S->getCollection()); 1780} 1781 1782CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) { 1783 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1784 1785 // Inline the body. 1786 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1787 1788 // The sync body starts its own basic block. This makes it a little easier 1789 // for diagnostic clients. 1790 if (SyncBlock) { 1791 if (badCFG) 1792 return 0; 1793 1794 Block = 0; 1795 Succ = SyncBlock; 1796 } 1797 1798 // Add the @synchronized to the CFG. 1799 autoCreateBlock(); 1800 appendStmt(Block, S, AddStmtChoice::AlwaysAdd); 1801 1802 // Inline the sync expression. 1803 return addStmt(S->getSynchExpr()); 1804} 1805 1806CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) { 1807 // FIXME 1808 return NYS(); 1809} 1810 1811CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) { 1812 CFGBlock* LoopSuccessor = NULL; 1813 1814 // Save local scope position because in case of condition variable ScopePos 1815 // won't be restored when traversing AST. 1816 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1817 1818 // Create local scope for possible condition variable. 1819 // Store scope position for continue statement. 1820 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1821 if (VarDecl* VD = W->getConditionVariable()) { 1822 addLocalScopeForVarDecl(VD); 1823 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 1824 } 1825 1826 // "while" is a control-flow statement. Thus we stop processing the current 1827 // block. 1828 if (Block) { 1829 if (badCFG) 1830 return 0; 1831 LoopSuccessor = Block; 1832 Block = 0; 1833 } else 1834 LoopSuccessor = Succ; 1835 1836 // Because of short-circuit evaluation, the condition of the loop can span 1837 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1838 // evaluate the condition. 1839 CFGBlock* ExitConditionBlock = createBlock(false); 1840 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1841 1842 // Set the terminator for the "exit" condition block. 1843 ExitConditionBlock->setTerminator(W); 1844 1845 // Now add the actual condition to the condition block. Because the condition 1846 // itself may contain control-flow, new blocks may be created. Thus we update 1847 // "Succ" after adding the condition. 1848 if (Stmt* C = W->getCond()) { 1849 Block = ExitConditionBlock; 1850 EntryConditionBlock = addStmt(C); 1851 // The condition might finish the current 'Block'. 1852 Block = EntryConditionBlock; 1853 1854 // If this block contains a condition variable, add both the condition 1855 // variable and initializer to the CFG. 1856 if (VarDecl *VD = W->getConditionVariable()) { 1857 if (Expr *Init = VD->getInit()) { 1858 autoCreateBlock(); 1859 appendStmt(Block, W, AddStmtChoice::AlwaysAdd); 1860 EntryConditionBlock = addStmt(Init); 1861 assert(Block == EntryConditionBlock); 1862 } 1863 } 1864 1865 if (Block) { 1866 if (badCFG) 1867 return 0; 1868 } 1869 } 1870 1871 // The condition block is the implicit successor for the loop body as well as 1872 // any code above the loop. 1873 Succ = EntryConditionBlock; 1874 1875 // See if this is a known constant. 1876 const TryResult& KnownVal = tryEvaluateBool(W->getCond()); 1877 1878 // Process the loop body. 1879 { 1880 assert(W->getBody()); 1881 1882 // Save the current values for Block, Succ, and continue and break targets 1883 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1884 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1885 save_break(BreakJumpTarget); 1886 1887 // Create an empty block to represent the transition block for looping back 1888 // to the head of the loop. 1889 Block = 0; 1890 assert(Succ == EntryConditionBlock); 1891 Succ = createBlock(); 1892 Succ->setLoopTarget(W); 1893 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 1894 1895 // All breaks should go to the code following the loop. 1896 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1897 1898 // NULL out Block to force lazy instantiation of blocks for the body. 1899 Block = NULL; 1900 1901 // Loop body should end with destructor of Condition variable (if any). 1902 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 1903 1904 // If body is not a compound statement create implicit scope 1905 // and add destructors. 1906 if (!isa<CompoundStmt>(W->getBody())) 1907 addLocalScopeAndDtors(W->getBody()); 1908 1909 // Create the body. The returned block is the entry to the loop body. 1910 CFGBlock* BodyBlock = addStmt(W->getBody()); 1911 1912 if (!BodyBlock) 1913 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 1914 else if (Block) { 1915 if (badCFG) 1916 return 0; 1917 } 1918 1919 // Add the loop body entry as a successor to the condition. 1920 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1921 } 1922 1923 // Link up the condition block with the code that follows the loop. (the 1924 // false branch). 1925 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1926 1927 // There can be no more statements in the condition block since we loop back 1928 // to this block. NULL out Block to force lazy creation of another block. 1929 Block = NULL; 1930 1931 // Return the condition block, which is the dominating block for the loop. 1932 Succ = EntryConditionBlock; 1933 return EntryConditionBlock; 1934} 1935 1936 1937CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { 1938 // FIXME: For now we pretend that @catch and the code it contains does not 1939 // exit. 1940 return Block; 1941} 1942 1943CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { 1944 // FIXME: This isn't complete. We basically treat @throw like a return 1945 // statement. 1946 1947 // If we were in the middle of a block we stop processing that block. 1948 if (badCFG) 1949 return 0; 1950 1951 // Create the new block. 1952 Block = createBlock(false); 1953 1954 // The Exit block is the only successor. 1955 addSuccessor(Block, &cfg->getExit()); 1956 1957 // Add the statement to the block. This may create new blocks if S contains 1958 // control-flow (short-circuit operations). 1959 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 1960} 1961 1962CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) { 1963 // If we were in the middle of a block we stop processing that block. 1964 if (badCFG) 1965 return 0; 1966 1967 // Create the new block. 1968 Block = createBlock(false); 1969 1970 if (TryTerminatedBlock) 1971 // The current try statement is the only successor. 1972 addSuccessor(Block, TryTerminatedBlock); 1973 else 1974 // otherwise the Exit block is the only successor. 1975 addSuccessor(Block, &cfg->getExit()); 1976 1977 // Add the statement to the block. This may create new blocks if S contains 1978 // control-flow (short-circuit operations). 1979 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 1980} 1981 1982CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) { 1983 CFGBlock* LoopSuccessor = NULL; 1984 1985 // "do...while" is a control-flow statement. Thus we stop processing the 1986 // current block. 1987 if (Block) { 1988 if (badCFG) 1989 return 0; 1990 LoopSuccessor = Block; 1991 } else 1992 LoopSuccessor = Succ; 1993 1994 // Because of short-circuit evaluation, the condition of the loop can span 1995 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1996 // evaluate the condition. 1997 CFGBlock* ExitConditionBlock = createBlock(false); 1998 CFGBlock* EntryConditionBlock = ExitConditionBlock; 1999 2000 // Set the terminator for the "exit" condition block. 2001 ExitConditionBlock->setTerminator(D); 2002 2003 // Now add the actual condition to the condition block. Because the condition 2004 // itself may contain control-flow, new blocks may be created. 2005 if (Stmt* C = D->getCond()) { 2006 Block = ExitConditionBlock; 2007 EntryConditionBlock = addStmt(C); 2008 if (Block) { 2009 if (badCFG) 2010 return 0; 2011 } 2012 } 2013 2014 // The condition block is the implicit successor for the loop body. 2015 Succ = EntryConditionBlock; 2016 2017 // See if this is a known constant. 2018 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 2019 2020 // Process the loop body. 2021 CFGBlock* BodyBlock = NULL; 2022 { 2023 assert(D->getBody()); 2024 2025 // Save the current values for Block, Succ, and continue and break targets 2026 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2027 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2028 save_break(BreakJumpTarget); 2029 2030 // All continues within this loop should go to the condition block 2031 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 2032 2033 // All breaks should go to the code following the loop. 2034 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2035 2036 // NULL out Block to force lazy instantiation of blocks for the body. 2037 Block = NULL; 2038 2039 // If body is not a compound statement create implicit scope 2040 // and add destructors. 2041 if (!isa<CompoundStmt>(D->getBody())) 2042 addLocalScopeAndDtors(D->getBody()); 2043 2044 // Create the body. The returned block is the entry to the loop body. 2045 BodyBlock = addStmt(D->getBody()); 2046 2047 if (!BodyBlock) 2048 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 2049 else if (Block) { 2050 if (badCFG) 2051 return 0; 2052 } 2053 2054 if (!KnownVal.isFalse()) { 2055 // Add an intermediate block between the BodyBlock and the 2056 // ExitConditionBlock to represent the "loop back" transition. Create an 2057 // empty block to represent the transition block for looping back to the 2058 // head of the loop. 2059 // FIXME: Can we do this more efficiently without adding another block? 2060 Block = NULL; 2061 Succ = BodyBlock; 2062 CFGBlock *LoopBackBlock = createBlock(); 2063 LoopBackBlock->setLoopTarget(D); 2064 2065 // Add the loop body entry as a successor to the condition. 2066 addSuccessor(ExitConditionBlock, LoopBackBlock); 2067 } 2068 else 2069 addSuccessor(ExitConditionBlock, NULL); 2070 } 2071 2072 // Link up the condition block with the code that follows the loop. 2073 // (the false branch). 2074 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2075 2076 // There can be no more statements in the body block(s) since we loop back to 2077 // the body. NULL out Block to force lazy creation of another block. 2078 Block = NULL; 2079 2080 // Return the loop body, which is the dominating block for the loop. 2081 Succ = BodyBlock; 2082 return BodyBlock; 2083} 2084 2085CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) { 2086 // "continue" is a control-flow statement. Thus we stop processing the 2087 // current block. 2088 if (badCFG) 2089 return 0; 2090 2091 // Now create a new block that ends with the continue statement. 2092 Block = createBlock(false); 2093 Block->setTerminator(C); 2094 2095 // If there is no target for the continue, then we are looking at an 2096 // incomplete AST. This means the CFG cannot be constructed. 2097 if (ContinueJumpTarget.block) { 2098 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); 2099 addSuccessor(Block, ContinueJumpTarget.block); 2100 } else 2101 badCFG = true; 2102 2103 return Block; 2104} 2105 2106CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, 2107 AddStmtChoice asc) { 2108 2109 if (asc.alwaysAdd()) { 2110 autoCreateBlock(); 2111 appendStmt(Block, E); 2112 } 2113 2114 // VLA types have expressions that must be evaluated. 2115 if (E->isArgumentType()) { 2116 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 2117 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 2118 addStmt(VA->getSizeExpr()); 2119 } 2120 2121 return Block; 2122} 2123 2124/// VisitStmtExpr - Utility method to handle (nested) statement 2125/// expressions (a GCC extension). 2126CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 2127 if (asc.alwaysAdd()) { 2128 autoCreateBlock(); 2129 appendStmt(Block, SE); 2130 } 2131 return VisitCompoundStmt(SE->getSubStmt()); 2132} 2133 2134CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) { 2135 // "switch" is a control-flow statement. Thus we stop processing the current 2136 // block. 2137 CFGBlock* SwitchSuccessor = NULL; 2138 2139 // Save local scope position because in case of condition variable ScopePos 2140 // won't be restored when traversing AST. 2141 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2142 2143 // Create local scope for possible condition variable. 2144 // Store scope position. Add implicit destructor. 2145 if (VarDecl* VD = Terminator->getConditionVariable()) { 2146 LocalScope::const_iterator SwitchBeginScopePos = ScopePos; 2147 addLocalScopeForVarDecl(VD); 2148 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); 2149 } 2150 2151 if (Block) { 2152 if (badCFG) 2153 return 0; 2154 SwitchSuccessor = Block; 2155 } else SwitchSuccessor = Succ; 2156 2157 // Save the current "switch" context. 2158 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 2159 save_default(DefaultCaseBlock); 2160 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2161 2162 // Set the "default" case to be the block after the switch statement. If the 2163 // switch statement contains a "default:", this value will be overwritten with 2164 // the block for that code. 2165 DefaultCaseBlock = SwitchSuccessor; 2166 2167 // Create a new block that will contain the switch statement. 2168 SwitchTerminatedBlock = createBlock(false); 2169 2170 // Now process the switch body. The code after the switch is the implicit 2171 // successor. 2172 Succ = SwitchSuccessor; 2173 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 2174 2175 // When visiting the body, the case statements should automatically get linked 2176 // up to the switch. We also don't keep a pointer to the body, since all 2177 // control-flow from the switch goes to case/default statements. 2178 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 2179 Block = NULL; 2180 2181 // If body is not a compound statement create implicit scope 2182 // and add destructors. 2183 if (!isa<CompoundStmt>(Terminator->getBody())) 2184 addLocalScopeAndDtors(Terminator->getBody()); 2185 2186 addStmt(Terminator->getBody()); 2187 if (Block) { 2188 if (badCFG) 2189 return 0; 2190 } 2191 2192 // If we have no "default:" case, the default transition is to the code 2193 // following the switch body. 2194 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock); 2195 2196 // Add the terminator and condition in the switch block. 2197 SwitchTerminatedBlock->setTerminator(Terminator); 2198 assert(Terminator->getCond() && "switch condition must be non-NULL"); 2199 Block = SwitchTerminatedBlock; 2200 Block = addStmt(Terminator->getCond()); 2201 2202 // Finally, if the SwitchStmt contains a condition variable, add both the 2203 // SwitchStmt and the condition variable initialization to the CFG. 2204 if (VarDecl *VD = Terminator->getConditionVariable()) { 2205 if (Expr *Init = VD->getInit()) { 2206 autoCreateBlock(); 2207 appendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd); 2208 addStmt(Init); 2209 } 2210 } 2211 2212 return Block; 2213} 2214 2215CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) { 2216 // CaseStmts are essentially labels, so they are the first statement in a 2217 // block. 2218 CFGBlock *TopBlock = 0, *LastBlock = 0; 2219 2220 if (Stmt *Sub = CS->getSubStmt()) { 2221 // For deeply nested chains of CaseStmts, instead of doing a recursion 2222 // (which can blow out the stack), manually unroll and create blocks 2223 // along the way. 2224 while (isa<CaseStmt>(Sub)) { 2225 CFGBlock *currentBlock = createBlock(false); 2226 currentBlock->setLabel(CS); 2227 2228 if (TopBlock) 2229 addSuccessor(LastBlock, currentBlock); 2230 else 2231 TopBlock = currentBlock; 2232 2233 addSuccessor(SwitchTerminatedBlock, currentBlock); 2234 LastBlock = currentBlock; 2235 2236 CS = cast<CaseStmt>(Sub); 2237 Sub = CS->getSubStmt(); 2238 } 2239 2240 addStmt(Sub); 2241 } 2242 2243 CFGBlock* CaseBlock = Block; 2244 if (!CaseBlock) 2245 CaseBlock = createBlock(); 2246 2247 // Cases statements partition blocks, so this is the top of the basic block we 2248 // were processing (the "case XXX:" is the label). 2249 CaseBlock->setLabel(CS); 2250 2251 if (badCFG) 2252 return 0; 2253 2254 // Add this block to the list of successors for the block with the switch 2255 // statement. 2256 assert(SwitchTerminatedBlock); 2257 addSuccessor(SwitchTerminatedBlock, CaseBlock); 2258 2259 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2260 Block = NULL; 2261 2262 if (TopBlock) { 2263 addSuccessor(LastBlock, CaseBlock); 2264 Succ = TopBlock; 2265 } else { 2266 // This block is now the implicit successor of other blocks. 2267 Succ = CaseBlock; 2268 } 2269 2270 return Succ; 2271} 2272 2273CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) { 2274 if (Terminator->getSubStmt()) 2275 addStmt(Terminator->getSubStmt()); 2276 2277 DefaultCaseBlock = Block; 2278 2279 if (!DefaultCaseBlock) 2280 DefaultCaseBlock = createBlock(); 2281 2282 // Default statements partition blocks, so this is the top of the basic block 2283 // we were processing (the "default:" is the label). 2284 DefaultCaseBlock->setLabel(Terminator); 2285 2286 if (badCFG) 2287 return 0; 2288 2289 // Unlike case statements, we don't add the default block to the successors 2290 // for the switch statement immediately. This is done when we finish 2291 // processing the switch statement. This allows for the default case 2292 // (including a fall-through to the code after the switch statement) to always 2293 // be the last successor of a switch-terminated block. 2294 2295 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2296 Block = NULL; 2297 2298 // This block is now the implicit successor of other blocks. 2299 Succ = DefaultCaseBlock; 2300 2301 return DefaultCaseBlock; 2302} 2303 2304CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 2305 // "try"/"catch" is a control-flow statement. Thus we stop processing the 2306 // current block. 2307 CFGBlock* TrySuccessor = NULL; 2308 2309 if (Block) { 2310 if (badCFG) 2311 return 0; 2312 TrySuccessor = Block; 2313 } else TrySuccessor = Succ; 2314 2315 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 2316 2317 // Create a new block that will contain the try statement. 2318 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2319 // Add the terminator in the try block. 2320 NewTryTerminatedBlock->setTerminator(Terminator); 2321 2322 bool HasCatchAll = false; 2323 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 2324 // The code after the try is the implicit successor. 2325 Succ = TrySuccessor; 2326 CXXCatchStmt *CS = Terminator->getHandler(h); 2327 if (CS->getExceptionDecl() == 0) { 2328 HasCatchAll = true; 2329 } 2330 Block = NULL; 2331 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 2332 if (CatchBlock == 0) 2333 return 0; 2334 // Add this block to the list of successors for the block with the try 2335 // statement. 2336 addSuccessor(NewTryTerminatedBlock, CatchBlock); 2337 } 2338 if (!HasCatchAll) { 2339 if (PrevTryTerminatedBlock) 2340 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 2341 else 2342 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2343 } 2344 2345 // The code after the try is the implicit successor. 2346 Succ = TrySuccessor; 2347 2348 // Save the current "try" context. 2349 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock); 2350 TryTerminatedBlock = NewTryTerminatedBlock; 2351 2352 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 2353 Block = NULL; 2354 Block = addStmt(Terminator->getTryBlock()); 2355 return Block; 2356} 2357 2358CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) { 2359 // CXXCatchStmt are treated like labels, so they are the first statement in a 2360 // block. 2361 2362 // Save local scope position because in case of exception variable ScopePos 2363 // won't be restored when traversing AST. 2364 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2365 2366 // Create local scope for possible exception variable. 2367 // Store scope position. Add implicit destructor. 2368 if (VarDecl* VD = CS->getExceptionDecl()) { 2369 LocalScope::const_iterator BeginScopePos = ScopePos; 2370 addLocalScopeForVarDecl(VD); 2371 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 2372 } 2373 2374 if (CS->getHandlerBlock()) 2375 addStmt(CS->getHandlerBlock()); 2376 2377 CFGBlock* CatchBlock = Block; 2378 if (!CatchBlock) 2379 CatchBlock = createBlock(); 2380 2381 CatchBlock->setLabel(CS); 2382 2383 if (badCFG) 2384 return 0; 2385 2386 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2387 Block = NULL; 2388 2389 return CatchBlock; 2390} 2391 2392CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 2393 AddStmtChoice asc) { 2394 if (BuildOpts.AddImplicitDtors) { 2395 // If adding implicit destructors visit the full expression for adding 2396 // destructors of temporaries. 2397 VisitForTemporaryDtors(E->getSubExpr()); 2398 2399 // Full expression has to be added as CFGStmt so it will be sequenced 2400 // before destructors of it's temporaries. 2401 asc = asc.withAlwaysAdd(true); 2402 } 2403 return Visit(E->getSubExpr(), asc); 2404} 2405 2406CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 2407 AddStmtChoice asc) { 2408 if (asc.alwaysAdd()) { 2409 autoCreateBlock(); 2410 appendStmt(Block, E, asc); 2411 2412 // We do not want to propagate the AlwaysAdd property. 2413 asc = asc.withAlwaysAdd(false); 2414 } 2415 return Visit(E->getSubExpr(), asc); 2416} 2417 2418CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 2419 AddStmtChoice asc) { 2420 autoCreateBlock(); 2421 if (!C->isElidable()) 2422 appendStmt(Block, C, asc.withAlwaysAdd(true)); 2423 2424 return VisitChildren(C); 2425} 2426 2427CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2428 AddStmtChoice asc) { 2429 if (asc.alwaysAdd()) { 2430 autoCreateBlock(); 2431 appendStmt(Block, E, asc); 2432 // We do not want to propagate the AlwaysAdd property. 2433 asc = asc.withAlwaysAdd(false); 2434 } 2435 return Visit(E->getSubExpr(), asc); 2436} 2437 2438CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2439 AddStmtChoice asc) { 2440 autoCreateBlock(); 2441 appendStmt(Block, C, asc.withAlwaysAdd(true)); 2442 return VisitChildren(C); 2443} 2444 2445CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C, 2446 AddStmtChoice asc) { 2447 autoCreateBlock(); 2448 appendStmt(Block, C, asc.withAlwaysAdd(true)); 2449 return VisitChildren(C); 2450} 2451 2452CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2453 AddStmtChoice asc) { 2454 if (asc.alwaysAdd()) { 2455 autoCreateBlock(); 2456 appendStmt(Block, E, asc); 2457 } 2458 return Visit(E->getSubExpr(), AddStmtChoice()); 2459} 2460 2461CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) { 2462 // Lazily create the indirect-goto dispatch block if there isn't one already. 2463 CFGBlock* IBlock = cfg->getIndirectGotoBlock(); 2464 2465 if (!IBlock) { 2466 IBlock = createBlock(false); 2467 cfg->setIndirectGotoBlock(IBlock); 2468 } 2469 2470 // IndirectGoto is a control-flow statement. Thus we stop processing the 2471 // current block and create a new one. 2472 if (badCFG) 2473 return 0; 2474 2475 Block = createBlock(false); 2476 Block->setTerminator(I); 2477 addSuccessor(Block, IBlock); 2478 return addStmt(I->getTarget()); 2479} 2480 2481CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2482tryAgain: 2483 if (!E) { 2484 badCFG = true; 2485 return NULL; 2486 } 2487 switch (E->getStmtClass()) { 2488 default: 2489 return VisitChildrenForTemporaryDtors(E); 2490 2491 case Stmt::BinaryOperatorClass: 2492 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2493 2494 case Stmt::CXXBindTemporaryExprClass: 2495 return VisitCXXBindTemporaryExprForTemporaryDtors( 2496 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2497 2498 case Stmt::BinaryConditionalOperatorClass: 2499 case Stmt::ConditionalOperatorClass: 2500 return VisitConditionalOperatorForTemporaryDtors( 2501 cast<AbstractConditionalOperator>(E), BindToTemporary); 2502 2503 case Stmt::ImplicitCastExprClass: 2504 // For implicit cast we want BindToTemporary to be passed further. 2505 E = cast<CastExpr>(E)->getSubExpr(); 2506 goto tryAgain; 2507 2508 case Stmt::ParenExprClass: 2509 E = cast<ParenExpr>(E)->getSubExpr(); 2510 goto tryAgain; 2511 } 2512} 2513 2514CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2515 // When visiting children for destructors we want to visit them in reverse 2516 // order. Because there's no reverse iterator for children must to reverse 2517 // them in helper vector. 2518 typedef llvm::SmallVector<Stmt *, 4> ChildrenVect; 2519 ChildrenVect ChildrenRev; 2520 for (Stmt::child_range I = E->children(); I; ++I) { 2521 if (*I) ChildrenRev.push_back(*I); 2522 } 2523 2524 CFGBlock *B = Block; 2525 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2526 L = ChildrenRev.rend(); I != L; ++I) { 2527 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2528 B = R; 2529 } 2530 return B; 2531} 2532 2533CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2534 if (E->isLogicalOp()) { 2535 // Destructors for temporaries in LHS expression should be called after 2536 // those for RHS expression. Even if this will unnecessarily create a block, 2537 // this block will be used at least by the full expression. 2538 autoCreateBlock(); 2539 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2540 if (badCFG) 2541 return NULL; 2542 2543 Succ = ConfluenceBlock; 2544 Block = NULL; 2545 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2546 2547 if (RHSBlock) { 2548 if (badCFG) 2549 return NULL; 2550 2551 // If RHS expression did produce destructors we need to connect created 2552 // blocks to CFG in same manner as for binary operator itself. 2553 CFGBlock *LHSBlock = createBlock(false); 2554 LHSBlock->setTerminator(CFGTerminator(E, true)); 2555 2556 // For binary operator LHS block is before RHS in list of predecessors 2557 // of ConfluenceBlock. 2558 std::reverse(ConfluenceBlock->pred_begin(), 2559 ConfluenceBlock->pred_end()); 2560 2561 // See if this is a known constant. 2562 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 2563 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2564 KnownVal.negate(); 2565 2566 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2567 // itself. 2568 if (E->getOpcode() == BO_LOr) { 2569 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2570 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2571 } else { 2572 assert (E->getOpcode() == BO_LAnd); 2573 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2574 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2575 } 2576 2577 Block = LHSBlock; 2578 return LHSBlock; 2579 } 2580 2581 Block = ConfluenceBlock; 2582 return ConfluenceBlock; 2583 } 2584 2585 if (E->isAssignmentOp()) { 2586 // For assignment operator (=) LHS expression is visited 2587 // before RHS expression. For destructors visit them in reverse order. 2588 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2589 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2590 return LHSBlock ? LHSBlock : RHSBlock; 2591 } 2592 2593 // For any other binary operator RHS expression is visited before 2594 // LHS expression (order of children). For destructors visit them in reverse 2595 // order. 2596 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2597 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2598 return RHSBlock ? RHSBlock : LHSBlock; 2599} 2600 2601CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2602 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2603 // First add destructors for temporaries in subexpression. 2604 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2605 if (!BindToTemporary) { 2606 // If lifetime of temporary is not prolonged (by assigning to constant 2607 // reference) add destructor for it. 2608 autoCreateBlock(); 2609 appendTemporaryDtor(Block, E); 2610 B = Block; 2611 } 2612 return B; 2613} 2614 2615CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2616 AbstractConditionalOperator *E, bool BindToTemporary) { 2617 // First add destructors for condition expression. Even if this will 2618 // unnecessarily create a block, this block will be used at least by the full 2619 // expression. 2620 autoCreateBlock(); 2621 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 2622 if (badCFG) 2623 return NULL; 2624 if (BinaryConditionalOperator *BCO 2625 = dyn_cast<BinaryConditionalOperator>(E)) { 2626 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 2627 if (badCFG) 2628 return NULL; 2629 } 2630 2631 // Try to add block with destructors for LHS expression. 2632 CFGBlock *LHSBlock = NULL; 2633 Succ = ConfluenceBlock; 2634 Block = NULL; 2635 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 2636 if (badCFG) 2637 return NULL; 2638 2639 // Try to add block with destructors for RHS expression; 2640 Succ = ConfluenceBlock; 2641 Block = NULL; 2642 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 2643 BindToTemporary); 2644 if (badCFG) 2645 return NULL; 2646 2647 if (!RHSBlock && !LHSBlock) { 2648 // If neither LHS nor RHS expression had temporaries to destroy don't create 2649 // more blocks. 2650 Block = ConfluenceBlock; 2651 return Block; 2652 } 2653 2654 Block = createBlock(false); 2655 Block->setTerminator(CFGTerminator(E, true)); 2656 2657 // See if this is a known constant. 2658 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 2659 2660 if (LHSBlock) { 2661 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 2662 } else if (KnownVal.isFalse()) { 2663 addSuccessor(Block, NULL); 2664 } else { 2665 addSuccessor(Block, ConfluenceBlock); 2666 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 2667 } 2668 2669 if (!RHSBlock) 2670 RHSBlock = ConfluenceBlock; 2671 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 2672 2673 return Block; 2674} 2675 2676} // end anonymous namespace 2677 2678/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 2679/// no successors or predecessors. If this is the first block created in the 2680/// CFG, it is automatically set to be the Entry and Exit of the CFG. 2681CFGBlock* CFG::createBlock() { 2682 bool first_block = begin() == end(); 2683 2684 // Create the block. 2685 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 2686 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 2687 Blocks.push_back(Mem, BlkBVC); 2688 2689 // If this is the first block, set it as the Entry and Exit. 2690 if (first_block) 2691 Entry = Exit = &back(); 2692 2693 // Return the block. 2694 return &back(); 2695} 2696 2697/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 2698/// CFG is returned to the caller. 2699CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C, 2700 BuildOptions BO) { 2701 CFGBuilder Builder; 2702 return Builder.buildCFG(D, Statement, C, BO); 2703} 2704 2705//===----------------------------------------------------------------------===// 2706// CFG: Queries for BlkExprs. 2707//===----------------------------------------------------------------------===// 2708 2709namespace { 2710 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 2711} 2712 2713static void FindSubExprAssignments(Stmt *S, 2714 llvm::SmallPtrSet<Expr*,50>& Set) { 2715 if (!S) 2716 return; 2717 2718 for (Stmt::child_range I = S->children(); I; ++I) { 2719 Stmt *child = *I; 2720 if (!child) 2721 continue; 2722 2723 if (BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 2724 if (B->isAssignmentOp()) Set.insert(B); 2725 2726 FindSubExprAssignments(child, Set); 2727 } 2728} 2729 2730static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 2731 BlkExprMapTy* M = new BlkExprMapTy(); 2732 2733 // Look for assignments that are used as subexpressions. These are the only 2734 // assignments that we want to *possibly* register as a block-level 2735 // expression. Basically, if an assignment occurs both in a subexpression and 2736 // at the block-level, it is a block-level expression. 2737 llvm::SmallPtrSet<Expr*,50> SubExprAssignments; 2738 2739 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 2740 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 2741 if (CFGStmt S = BI->getAs<CFGStmt>()) 2742 FindSubExprAssignments(S, SubExprAssignments); 2743 2744 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 2745 2746 // Iterate over the statements again on identify the Expr* and Stmt* at the 2747 // block-level that are block-level expressions. 2748 2749 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 2750 CFGStmt CS = BI->getAs<CFGStmt>(); 2751 if (!CS.isValid()) 2752 continue; 2753 if (Expr* Exp = dyn_cast<Expr>(CS.getStmt())) { 2754 2755 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 2756 // Assignment expressions that are not nested within another 2757 // expression are really "statements" whose value is never used by 2758 // another expression. 2759 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 2760 continue; 2761 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) { 2762 // Special handling for statement expressions. The last statement in 2763 // the statement expression is also a block-level expr. 2764 const CompoundStmt* C = Terminator->getSubStmt(); 2765 if (!C->body_empty()) { 2766 unsigned x = M->size(); 2767 (*M)[C->body_back()] = x; 2768 } 2769 } 2770 2771 unsigned x = M->size(); 2772 (*M)[Exp] = x; 2773 } 2774 } 2775 2776 // Look at terminators. The condition is a block-level expression. 2777 2778 Stmt* S = (*I)->getTerminatorCondition(); 2779 2780 if (S && M->find(S) == M->end()) { 2781 unsigned x = M->size(); 2782 (*M)[S] = x; 2783 } 2784 } 2785 2786 return M; 2787} 2788 2789CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) { 2790 assert(S != NULL); 2791 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 2792 2793 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 2794 BlkExprMapTy::iterator I = M->find(S); 2795 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 2796} 2797 2798unsigned CFG::getNumBlkExprs() { 2799 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 2800 return M->size(); 2801 2802 // We assume callers interested in the number of BlkExprs will want 2803 // the map constructed if it doesn't already exist. 2804 BlkExprMap = (void*) PopulateBlkExprMap(*this); 2805 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 2806} 2807 2808//===----------------------------------------------------------------------===// 2809// Filtered walking of the CFG. 2810//===----------------------------------------------------------------------===// 2811 2812bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 2813 const CFGBlock *From, const CFGBlock *To) { 2814 2815 if (F.IgnoreDefaultsWithCoveredEnums) { 2816 // If the 'To' has no label or is labeled but the label isn't a 2817 // CaseStmt then filter this edge. 2818 if (const SwitchStmt *S = 2819 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 2820 if (S->isAllEnumCasesCovered()) { 2821 const Stmt *L = To->getLabel(); 2822 if (!L || !isa<CaseStmt>(L)) 2823 return true; 2824 } 2825 } 2826 } 2827 2828 return false; 2829} 2830 2831//===----------------------------------------------------------------------===// 2832// Cleanup: CFG dstor. 2833//===----------------------------------------------------------------------===// 2834 2835CFG::~CFG() { 2836 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 2837} 2838 2839//===----------------------------------------------------------------------===// 2840// CFG pretty printing 2841//===----------------------------------------------------------------------===// 2842 2843namespace { 2844 2845class StmtPrinterHelper : public PrinterHelper { 2846 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 2847 typedef llvm::DenseMap<Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 2848 StmtMapTy StmtMap; 2849 DeclMapTy DeclMap; 2850 signed currentBlock; 2851 unsigned currentStmt; 2852 const LangOptions &LangOpts; 2853public: 2854 2855 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 2856 : currentBlock(0), currentStmt(0), LangOpts(LO) { 2857 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 2858 unsigned j = 1; 2859 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 2860 BI != BEnd; ++BI, ++j ) { 2861 if (CFGStmt SE = BI->getAs<CFGStmt>()) { 2862 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 2863 StmtMap[SE] = P; 2864 2865 if (DeclStmt* DS = dyn_cast<DeclStmt>(SE.getStmt())) { 2866 DeclMap[DS->getSingleDecl()] = P; 2867 2868 } else if (IfStmt* IS = dyn_cast<IfStmt>(SE.getStmt())) { 2869 if (VarDecl* VD = IS->getConditionVariable()) 2870 DeclMap[VD] = P; 2871 2872 } else if (ForStmt* FS = dyn_cast<ForStmt>(SE.getStmt())) { 2873 if (VarDecl* VD = FS->getConditionVariable()) 2874 DeclMap[VD] = P; 2875 2876 } else if (WhileStmt* WS = dyn_cast<WhileStmt>(SE.getStmt())) { 2877 if (VarDecl* VD = WS->getConditionVariable()) 2878 DeclMap[VD] = P; 2879 2880 } else if (SwitchStmt* SS = dyn_cast<SwitchStmt>(SE.getStmt())) { 2881 if (VarDecl* VD = SS->getConditionVariable()) 2882 DeclMap[VD] = P; 2883 2884 } else if (CXXCatchStmt* CS = dyn_cast<CXXCatchStmt>(SE.getStmt())) { 2885 if (VarDecl* VD = CS->getExceptionDecl()) 2886 DeclMap[VD] = P; 2887 } 2888 } 2889 } 2890 } 2891 } 2892 2893 virtual ~StmtPrinterHelper() {} 2894 2895 const LangOptions &getLangOpts() const { return LangOpts; } 2896 void setBlockID(signed i) { currentBlock = i; } 2897 void setStmtID(unsigned i) { currentStmt = i; } 2898 2899 virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) { 2900 StmtMapTy::iterator I = StmtMap.find(S); 2901 2902 if (I == StmtMap.end()) 2903 return false; 2904 2905 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 2906 && I->second.second == currentStmt) { 2907 return false; 2908 } 2909 2910 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2911 return true; 2912 } 2913 2914 bool handleDecl(Decl* D, llvm::raw_ostream& OS) { 2915 DeclMapTy::iterator I = DeclMap.find(D); 2916 2917 if (I == DeclMap.end()) 2918 return false; 2919 2920 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 2921 && I->second.second == currentStmt) { 2922 return false; 2923 } 2924 2925 OS << "[B" << I->second.first << "." << I->second.second << "]"; 2926 return true; 2927 } 2928}; 2929} // end anonymous namespace 2930 2931 2932namespace { 2933class CFGBlockTerminatorPrint 2934 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 2935 2936 llvm::raw_ostream& OS; 2937 StmtPrinterHelper* Helper; 2938 PrintingPolicy Policy; 2939public: 2940 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper, 2941 const PrintingPolicy &Policy) 2942 : OS(os), Helper(helper), Policy(Policy) {} 2943 2944 void VisitIfStmt(IfStmt* I) { 2945 OS << "if "; 2946 I->getCond()->printPretty(OS,Helper,Policy); 2947 } 2948 2949 // Default case. 2950 void VisitStmt(Stmt* Terminator) { 2951 Terminator->printPretty(OS, Helper, Policy); 2952 } 2953 2954 void VisitForStmt(ForStmt* F) { 2955 OS << "for (" ; 2956 if (F->getInit()) 2957 OS << "..."; 2958 OS << "; "; 2959 if (Stmt* C = F->getCond()) 2960 C->printPretty(OS, Helper, Policy); 2961 OS << "; "; 2962 if (F->getInc()) 2963 OS << "..."; 2964 OS << ")"; 2965 } 2966 2967 void VisitWhileStmt(WhileStmt* W) { 2968 OS << "while " ; 2969 if (Stmt* C = W->getCond()) 2970 C->printPretty(OS, Helper, Policy); 2971 } 2972 2973 void VisitDoStmt(DoStmt* D) { 2974 OS << "do ... while "; 2975 if (Stmt* C = D->getCond()) 2976 C->printPretty(OS, Helper, Policy); 2977 } 2978 2979 void VisitSwitchStmt(SwitchStmt* Terminator) { 2980 OS << "switch "; 2981 Terminator->getCond()->printPretty(OS, Helper, Policy); 2982 } 2983 2984 void VisitCXXTryStmt(CXXTryStmt* CS) { 2985 OS << "try ..."; 2986 } 2987 2988 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 2989 C->getCond()->printPretty(OS, Helper, Policy); 2990 OS << " ? ... : ..."; 2991 } 2992 2993 void VisitChooseExpr(ChooseExpr* C) { 2994 OS << "__builtin_choose_expr( "; 2995 C->getCond()->printPretty(OS, Helper, Policy); 2996 OS << " )"; 2997 } 2998 2999 void VisitIndirectGotoStmt(IndirectGotoStmt* I) { 3000 OS << "goto *"; 3001 I->getTarget()->printPretty(OS, Helper, Policy); 3002 } 3003 3004 void VisitBinaryOperator(BinaryOperator* B) { 3005 if (!B->isLogicalOp()) { 3006 VisitExpr(B); 3007 return; 3008 } 3009 3010 B->getLHS()->printPretty(OS, Helper, Policy); 3011 3012 switch (B->getOpcode()) { 3013 case BO_LOr: 3014 OS << " || ..."; 3015 return; 3016 case BO_LAnd: 3017 OS << " && ..."; 3018 return; 3019 default: 3020 assert(false && "Invalid logical operator."); 3021 } 3022 } 3023 3024 void VisitExpr(Expr* E) { 3025 E->printPretty(OS, Helper, Policy); 3026 } 3027}; 3028} // end anonymous namespace 3029 3030static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper, 3031 const CFGElement &E) { 3032 if (CFGStmt CS = E.getAs<CFGStmt>()) { 3033 Stmt *S = CS; 3034 3035 if (Helper) { 3036 3037 // special printing for statement-expressions. 3038 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) { 3039 CompoundStmt* Sub = SE->getSubStmt(); 3040 3041 if (Sub->children()) { 3042 OS << "({ ... ; "; 3043 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3044 OS << " })\n"; 3045 return; 3046 } 3047 } 3048 // special printing for comma expressions. 3049 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3050 if (B->getOpcode() == BO_Comma) { 3051 OS << "... , "; 3052 Helper->handledStmt(B->getRHS(),OS); 3053 OS << '\n'; 3054 return; 3055 } 3056 } 3057 } 3058 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3059 3060 if (isa<CXXOperatorCallExpr>(S)) { 3061 OS << " (OperatorCall)"; 3062 } else if (isa<CXXBindTemporaryExpr>(S)) { 3063 OS << " (BindTemporary)"; 3064 } 3065 3066 // Expressions need a newline. 3067 if (isa<Expr>(S)) 3068 OS << '\n'; 3069 3070 } else if (CFGInitializer IE = E.getAs<CFGInitializer>()) { 3071 CXXCtorInitializer* I = IE; 3072 if (I->isBaseInitializer()) 3073 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3074 else OS << I->getAnyMember()->getName(); 3075 3076 OS << "("; 3077 if (Expr* IE = I->getInit()) 3078 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3079 OS << ")"; 3080 3081 if (I->isBaseInitializer()) 3082 OS << " (Base initializer)\n"; 3083 else OS << " (Member initializer)\n"; 3084 3085 } else if (CFGAutomaticObjDtor DE = E.getAs<CFGAutomaticObjDtor>()){ 3086 VarDecl* VD = DE.getVarDecl(); 3087 Helper->handleDecl(VD, OS); 3088 3089 const Type* T = VD->getType().getTypePtr(); 3090 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3091 T = RT->getPointeeType().getTypePtr(); 3092 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3093 T = ET; 3094 3095 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3096 OS << " (Implicit destructor)\n"; 3097 3098 } else if (CFGBaseDtor BE = E.getAs<CFGBaseDtor>()) { 3099 const CXXBaseSpecifier *BS = BE.getBaseSpecifier(); 3100 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3101 OS << " (Base object destructor)\n"; 3102 3103 } else if (CFGMemberDtor ME = E.getAs<CFGMemberDtor>()) { 3104 FieldDecl *FD = ME.getFieldDecl(); 3105 3106 const Type *T = FD->getType().getTypePtr(); 3107 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3108 T = ET; 3109 3110 OS << "this->" << FD->getName(); 3111 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3112 OS << " (Member object destructor)\n"; 3113 3114 } else if (CFGTemporaryDtor TE = E.getAs<CFGTemporaryDtor>()) { 3115 CXXBindTemporaryExpr *BT = TE.getBindTemporaryExpr(); 3116 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3117 OS << " (Temporary object destructor)\n"; 3118 } 3119} 3120 3121static void print_block(llvm::raw_ostream& OS, const CFG* cfg, 3122 const CFGBlock& B, 3123 StmtPrinterHelper* Helper, bool print_edges) { 3124 3125 if (Helper) Helper->setBlockID(B.getBlockID()); 3126 3127 // Print the header. 3128 OS << "\n [ B" << B.getBlockID(); 3129 3130 if (&B == &cfg->getEntry()) 3131 OS << " (ENTRY) ]\n"; 3132 else if (&B == &cfg->getExit()) 3133 OS << " (EXIT) ]\n"; 3134 else if (&B == cfg->getIndirectGotoBlock()) 3135 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 3136 else 3137 OS << " ]\n"; 3138 3139 // Print the label of this block. 3140 if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) { 3141 3142 if (print_edges) 3143 OS << " "; 3144 3145 if (LabelStmt* L = dyn_cast<LabelStmt>(Label)) 3146 OS << L->getName(); 3147 else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) { 3148 OS << "case "; 3149 C->getLHS()->printPretty(OS, Helper, 3150 PrintingPolicy(Helper->getLangOpts())); 3151 if (C->getRHS()) { 3152 OS << " ... "; 3153 C->getRHS()->printPretty(OS, Helper, 3154 PrintingPolicy(Helper->getLangOpts())); 3155 } 3156 } else if (isa<DefaultStmt>(Label)) 3157 OS << "default"; 3158 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3159 OS << "catch ("; 3160 if (CS->getExceptionDecl()) 3161 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3162 0); 3163 else 3164 OS << "..."; 3165 OS << ")"; 3166 3167 } else 3168 assert(false && "Invalid label statement in CFGBlock."); 3169 3170 OS << ":\n"; 3171 } 3172 3173 // Iterate through the statements in the block and print them. 3174 unsigned j = 1; 3175 3176 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3177 I != E ; ++I, ++j ) { 3178 3179 // Print the statement # in the basic block and the statement itself. 3180 if (print_edges) 3181 OS << " "; 3182 3183 OS << llvm::format("%3d", j) << ": "; 3184 3185 if (Helper) 3186 Helper->setStmtID(j); 3187 3188 print_elem(OS,Helper,*I); 3189 } 3190 3191 // Print the terminator of this block. 3192 if (B.getTerminator()) { 3193 if (print_edges) 3194 OS << " "; 3195 3196 OS << " T: "; 3197 3198 if (Helper) Helper->setBlockID(-1); 3199 3200 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3201 PrintingPolicy(Helper->getLangOpts())); 3202 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3203 OS << '\n'; 3204 } 3205 3206 if (print_edges) { 3207 // Print the predecessors of this block. 3208 OS << " Predecessors (" << B.pred_size() << "):"; 3209 unsigned i = 0; 3210 3211 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3212 I != E; ++I, ++i) { 3213 3214 if (i == 8 || (i-8) == 0) 3215 OS << "\n "; 3216 3217 OS << " B" << (*I)->getBlockID(); 3218 } 3219 3220 OS << '\n'; 3221 3222 // Print the successors of this block. 3223 OS << " Successors (" << B.succ_size() << "):"; 3224 i = 0; 3225 3226 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3227 I != E; ++I, ++i) { 3228 3229 if (i == 8 || (i-8) % 10 == 0) 3230 OS << "\n "; 3231 3232 if (*I) 3233 OS << " B" << (*I)->getBlockID(); 3234 else 3235 OS << " NULL"; 3236 } 3237 3238 OS << '\n'; 3239 } 3240} 3241 3242 3243/// dump - A simple pretty printer of a CFG that outputs to stderr. 3244void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 3245 3246/// print - A simple pretty printer of a CFG that outputs to an ostream. 3247void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const { 3248 StmtPrinterHelper Helper(this, LO); 3249 3250 // Print the entry block. 3251 print_block(OS, this, getEntry(), &Helper, true); 3252 3253 // Iterate through the CFGBlocks and print them one by one. 3254 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3255 // Skip the entry block, because we already printed it. 3256 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3257 continue; 3258 3259 print_block(OS, this, **I, &Helper, true); 3260 } 3261 3262 // Print the exit block. 3263 print_block(OS, this, getExit(), &Helper, true); 3264 OS.flush(); 3265} 3266 3267/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3268void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 3269 print(llvm::errs(), cfg, LO); 3270} 3271 3272/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3273/// Generally this will only be called from CFG::print. 3274void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg, 3275 const LangOptions &LO) const { 3276 StmtPrinterHelper Helper(cfg, LO); 3277 print_block(OS, cfg, *this, &Helper, true); 3278} 3279 3280/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3281void CFGBlock::printTerminator(llvm::raw_ostream &OS, 3282 const LangOptions &LO) const { 3283 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3284 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3285} 3286 3287Stmt* CFGBlock::getTerminatorCondition() { 3288 Stmt *Terminator = this->Terminator; 3289 if (!Terminator) 3290 return NULL; 3291 3292 Expr* E = NULL; 3293 3294 switch (Terminator->getStmtClass()) { 3295 default: 3296 break; 3297 3298 case Stmt::ForStmtClass: 3299 E = cast<ForStmt>(Terminator)->getCond(); 3300 break; 3301 3302 case Stmt::WhileStmtClass: 3303 E = cast<WhileStmt>(Terminator)->getCond(); 3304 break; 3305 3306 case Stmt::DoStmtClass: 3307 E = cast<DoStmt>(Terminator)->getCond(); 3308 break; 3309 3310 case Stmt::IfStmtClass: 3311 E = cast<IfStmt>(Terminator)->getCond(); 3312 break; 3313 3314 case Stmt::ChooseExprClass: 3315 E = cast<ChooseExpr>(Terminator)->getCond(); 3316 break; 3317 3318 case Stmt::IndirectGotoStmtClass: 3319 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3320 break; 3321 3322 case Stmt::SwitchStmtClass: 3323 E = cast<SwitchStmt>(Terminator)->getCond(); 3324 break; 3325 3326 case Stmt::BinaryConditionalOperatorClass: 3327 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 3328 break; 3329 3330 case Stmt::ConditionalOperatorClass: 3331 E = cast<ConditionalOperator>(Terminator)->getCond(); 3332 break; 3333 3334 case Stmt::BinaryOperatorClass: // '&&' and '||' 3335 E = cast<BinaryOperator>(Terminator)->getLHS(); 3336 break; 3337 3338 case Stmt::ObjCForCollectionStmtClass: 3339 return Terminator; 3340 } 3341 3342 return E ? E->IgnoreParens() : NULL; 3343} 3344 3345bool CFGBlock::hasBinaryBranchTerminator() const { 3346 const Stmt *Terminator = this->Terminator; 3347 if (!Terminator) 3348 return false; 3349 3350 Expr* E = NULL; 3351 3352 switch (Terminator->getStmtClass()) { 3353 default: 3354 return false; 3355 3356 case Stmt::ForStmtClass: 3357 case Stmt::WhileStmtClass: 3358 case Stmt::DoStmtClass: 3359 case Stmt::IfStmtClass: 3360 case Stmt::ChooseExprClass: 3361 case Stmt::BinaryConditionalOperatorClass: 3362 case Stmt::ConditionalOperatorClass: 3363 case Stmt::BinaryOperatorClass: 3364 return true; 3365 } 3366 3367 return E ? E->IgnoreParens() : NULL; 3368} 3369 3370 3371//===----------------------------------------------------------------------===// 3372// CFG Graphviz Visualization 3373//===----------------------------------------------------------------------===// 3374 3375 3376#ifndef NDEBUG 3377static StmtPrinterHelper* GraphHelper; 3378#endif 3379 3380void CFG::viewCFG(const LangOptions &LO) const { 3381#ifndef NDEBUG 3382 StmtPrinterHelper H(this, LO); 3383 GraphHelper = &H; 3384 llvm::ViewGraph(this,"CFG"); 3385 GraphHelper = NULL; 3386#endif 3387} 3388 3389namespace llvm { 3390template<> 3391struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3392 3393 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3394 3395 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) { 3396 3397#ifndef NDEBUG 3398 std::string OutSStr; 3399 llvm::raw_string_ostream Out(OutSStr); 3400 print_block(Out,Graph, *Node, GraphHelper, false); 3401 std::string& OutStr = Out.str(); 3402 3403 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3404 3405 // Process string output to make it nicer... 3406 for (unsigned i = 0; i != OutStr.length(); ++i) 3407 if (OutStr[i] == '\n') { // Left justify 3408 OutStr[i] = '\\'; 3409 OutStr.insert(OutStr.begin()+i+1, 'l'); 3410 } 3411 3412 return OutStr; 3413#else 3414 return ""; 3415#endif 3416 } 3417}; 3418} // end namespace llvm 3419