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