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