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