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