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