CFG.cpp revision 550f2234fc9218914c325041067052342dfce553
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 // Keep track of the last non-null block, as 'Block' can be nulled out 1469 // if the initializer expression is something like a 'while' in a 1470 // statement-expression. 1471 CFGBlock *LastBlock = Block; 1472 1473 if (Init) { 1474 if (HasTemporaries) { 1475 // For expression with temporaries go directly to subexpression to omit 1476 // generating destructors for the second time. 1477 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init); 1478 if (CFGBlock *newBlock = Visit(EC->getSubExpr())) 1479 LastBlock = newBlock; 1480 } 1481 else { 1482 if (CFGBlock *newBlock = Visit(Init)) 1483 LastBlock = newBlock; 1484 } 1485 } 1486 1487 // If the type of VD is a VLA, then we must process its size expressions. 1488 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 1489 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1490 Block = addStmt(VA->getSizeExpr()); 1491 1492 // Remove variable from local scope. 1493 if (ScopePos && VD == *ScopePos) 1494 ++ScopePos; 1495 1496 return Block ? Block : LastBlock; 1497} 1498 1499CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 1500 // We may see an if statement in the middle of a basic block, or it may be the 1501 // first statement we are processing. In either case, we create a new basic 1502 // block. First, we create the blocks for the then...else statements, and 1503 // then we create the block containing the if statement. If we were in the 1504 // middle of a block, we stop processing that block. That block is then the 1505 // implicit successor for the "then" and "else" clauses. 1506 1507 // Save local scope position because in case of condition variable ScopePos 1508 // won't be restored when traversing AST. 1509 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1510 1511 // Create local scope for possible condition variable. 1512 // Store scope position. Add implicit destructor. 1513 if (VarDecl *VD = I->getConditionVariable()) { 1514 LocalScope::const_iterator BeginScopePos = ScopePos; 1515 addLocalScopeForVarDecl(VD); 1516 addAutomaticObjDtors(ScopePos, BeginScopePos, I); 1517 } 1518 1519 // The block we were processing is now finished. Make it the successor 1520 // block. 1521 if (Block) { 1522 Succ = Block; 1523 if (badCFG) 1524 return 0; 1525 } 1526 1527 // Process the false branch. 1528 CFGBlock *ElseBlock = Succ; 1529 1530 if (Stmt *Else = I->getElse()) { 1531 SaveAndRestore<CFGBlock*> sv(Succ); 1532 1533 // NULL out Block so that the recursive call to Visit will 1534 // create a new basic block. 1535 Block = NULL; 1536 1537 // If branch is not a compound statement create implicit scope 1538 // and add destructors. 1539 if (!isa<CompoundStmt>(Else)) 1540 addLocalScopeAndDtors(Else); 1541 1542 ElseBlock = addStmt(Else); 1543 1544 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 1545 ElseBlock = sv.get(); 1546 else if (Block) { 1547 if (badCFG) 1548 return 0; 1549 } 1550 } 1551 1552 // Process the true branch. 1553 CFGBlock *ThenBlock; 1554 { 1555 Stmt *Then = I->getThen(); 1556 assert(Then); 1557 SaveAndRestore<CFGBlock*> sv(Succ); 1558 Block = NULL; 1559 1560 // If branch is not a compound statement create implicit scope 1561 // and add destructors. 1562 if (!isa<CompoundStmt>(Then)) 1563 addLocalScopeAndDtors(Then); 1564 1565 ThenBlock = addStmt(Then); 1566 1567 if (!ThenBlock) { 1568 // We can reach here if the "then" body has all NullStmts. 1569 // Create an empty block so we can distinguish between true and false 1570 // branches in path-sensitive analyses. 1571 ThenBlock = createBlock(false); 1572 addSuccessor(ThenBlock, sv.get()); 1573 } else if (Block) { 1574 if (badCFG) 1575 return 0; 1576 } 1577 } 1578 1579 // Now create a new block containing the if statement. 1580 Block = createBlock(false); 1581 1582 // Set the terminator of the new block to the If statement. 1583 Block->setTerminator(I); 1584 1585 // See if this is a known constant. 1586 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 1587 1588 // Now add the successors. 1589 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 1590 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 1591 1592 // Add the condition as the last statement in the new block. This may create 1593 // new blocks as the condition may contain control-flow. Any newly created 1594 // blocks will be pointed to be "Block". 1595 Block = addStmt(I->getCond()); 1596 1597 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 1598 // and the condition variable initialization to the CFG. 1599 if (VarDecl *VD = I->getConditionVariable()) { 1600 if (Expr *Init = VD->getInit()) { 1601 autoCreateBlock(); 1602 appendStmt(Block, I->getConditionVariableDeclStmt()); 1603 addStmt(Init); 1604 } 1605 } 1606 1607 return Block; 1608} 1609 1610 1611CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { 1612 // If we were in the middle of a block we stop processing that block. 1613 // 1614 // NOTE: If a "return" appears in the middle of a block, this means that the 1615 // code afterwards is DEAD (unreachable). We still keep a basic block 1616 // for that code; a simple "mark-and-sweep" from the entry block will be 1617 // able to report such dead blocks. 1618 1619 // Create the new block. 1620 Block = createBlock(false); 1621 1622 // The Exit block is the only successor. 1623 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); 1624 addSuccessor(Block, &cfg->getExit()); 1625 1626 // Add the return statement to the block. This may create new blocks if R 1627 // contains control-flow (short-circuit operations). 1628 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 1629} 1630 1631CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 1632 // Get the block of the labeled statement. Add it to our map. 1633 addStmt(L->getSubStmt()); 1634 CFGBlock *LabelBlock = Block; 1635 1636 if (!LabelBlock) // This can happen when the body is empty, i.e. 1637 LabelBlock = createBlock(); // scopes that only contains NullStmts. 1638 1639 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 1640 "label already in map"); 1641 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 1642 1643 // Labels partition blocks, so this is the end of the basic block we were 1644 // processing (L is the block's label). Because this is label (and we have 1645 // already processed the substatement) there is no extra control-flow to worry 1646 // about. 1647 LabelBlock->setLabel(L); 1648 if (badCFG) 1649 return 0; 1650 1651 // We set Block to NULL to allow lazy creation of a new block (if necessary); 1652 Block = NULL; 1653 1654 // This block is now the implicit successor of other blocks. 1655 Succ = LabelBlock; 1656 1657 return LabelBlock; 1658} 1659 1660CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 1661 // Goto is a control-flow statement. Thus we stop processing the current 1662 // block and create a new one. 1663 1664 Block = createBlock(false); 1665 Block->setTerminator(G); 1666 1667 // If we already know the mapping to the label block add the successor now. 1668 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 1669 1670 if (I == LabelMap.end()) 1671 // We will need to backpatch this block later. 1672 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 1673 else { 1674 JumpTarget JT = I->second; 1675 addAutomaticObjDtors(ScopePos, JT.scopePosition, G); 1676 addSuccessor(Block, JT.block); 1677 } 1678 1679 return Block; 1680} 1681 1682CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 1683 CFGBlock *LoopSuccessor = NULL; 1684 1685 // Save local scope position because in case of condition variable ScopePos 1686 // won't be restored when traversing AST. 1687 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1688 1689 // Create local scope for init statement and possible condition variable. 1690 // Add destructor for init statement and condition variable. 1691 // Store scope position for continue statement. 1692 if (Stmt *Init = F->getInit()) 1693 addLocalScopeForStmt(Init); 1694 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1695 1696 if (VarDecl *VD = F->getConditionVariable()) 1697 addLocalScopeForVarDecl(VD); 1698 LocalScope::const_iterator ContinueScopePos = ScopePos; 1699 1700 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); 1701 1702 // "for" is a control-flow statement. Thus we stop processing the current 1703 // block. 1704 if (Block) { 1705 if (badCFG) 1706 return 0; 1707 LoopSuccessor = Block; 1708 } else 1709 LoopSuccessor = Succ; 1710 1711 // Save the current value for the break targets. 1712 // All breaks should go to the code following the loop. 1713 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1714 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1715 1716 // Because of short-circuit evaluation, the condition of the loop can span 1717 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1718 // evaluate the condition. 1719 CFGBlock *ExitConditionBlock = createBlock(false); 1720 CFGBlock *EntryConditionBlock = ExitConditionBlock; 1721 1722 // Set the terminator for the "exit" condition block. 1723 ExitConditionBlock->setTerminator(F); 1724 1725 // Now add the actual condition to the condition block. Because the condition 1726 // itself may contain control-flow, new blocks may be created. 1727 if (Stmt *C = F->getCond()) { 1728 Block = ExitConditionBlock; 1729 EntryConditionBlock = addStmt(C); 1730 if (badCFG) 1731 return 0; 1732 assert(Block == EntryConditionBlock || 1733 (Block == 0 && EntryConditionBlock == Succ)); 1734 1735 // If this block contains a condition variable, add both the condition 1736 // variable and initializer to the CFG. 1737 if (VarDecl *VD = F->getConditionVariable()) { 1738 if (Expr *Init = VD->getInit()) { 1739 autoCreateBlock(); 1740 appendStmt(Block, F->getConditionVariableDeclStmt()); 1741 EntryConditionBlock = addStmt(Init); 1742 assert(Block == EntryConditionBlock); 1743 } 1744 } 1745 1746 if (Block) { 1747 if (badCFG) 1748 return 0; 1749 } 1750 } 1751 1752 // The condition block is the implicit successor for the loop body as well as 1753 // any code above the loop. 1754 Succ = EntryConditionBlock; 1755 1756 // See if this is a known constant. 1757 TryResult KnownVal(true); 1758 1759 if (F->getCond()) 1760 KnownVal = tryEvaluateBool(F->getCond()); 1761 1762 // Now create the loop body. 1763 { 1764 assert(F->getBody()); 1765 1766 // Save the current values for Block, Succ, and continue targets. 1767 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1768 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 1769 1770 // Create a new block to contain the (bottom) of the loop body. 1771 Block = NULL; 1772 1773 // Loop body should end with destructor of Condition variable (if any). 1774 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); 1775 1776 if (Stmt *I = F->getInc()) { 1777 // Generate increment code in its own basic block. This is the target of 1778 // continue statements. 1779 Succ = addStmt(I); 1780 } else { 1781 // No increment code. Create a special, empty, block that is used as the 1782 // target block for "looping back" to the start of the loop. 1783 assert(Succ == EntryConditionBlock); 1784 Succ = Block ? Block : createBlock(); 1785 } 1786 1787 // Finish up the increment (or empty) block if it hasn't been already. 1788 if (Block) { 1789 assert(Block == Succ); 1790 if (badCFG) 1791 return 0; 1792 Block = 0; 1793 } 1794 1795 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 1796 1797 // The starting block for the loop increment is the block that should 1798 // represent the 'loop target' for looping back to the start of the loop. 1799 ContinueJumpTarget.block->setLoopTarget(F); 1800 1801 // If body is not a compound statement create implicit scope 1802 // and add destructors. 1803 if (!isa<CompoundStmt>(F->getBody())) 1804 addLocalScopeAndDtors(F->getBody()); 1805 1806 // Now populate the body block, and in the process create new blocks as we 1807 // walk the body of the loop. 1808 CFGBlock *BodyBlock = addStmt(F->getBody()); 1809 1810 if (!BodyBlock) 1811 BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);" 1812 else if (badCFG) 1813 return 0; 1814 1815 // This new body block is a successor to our "exit" condition block. 1816 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1817 } 1818 1819 // Link up the condition block with the code that follows the loop. (the 1820 // false branch). 1821 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1822 1823 // If the loop contains initialization, create a new block for those 1824 // statements. This block can also contain statements that precede the loop. 1825 if (Stmt *I = F->getInit()) { 1826 Block = createBlock(); 1827 return addStmt(I); 1828 } 1829 1830 // There is no loop initialization. We are thus basically a while loop. 1831 // NULL out Block to force lazy block construction. 1832 Block = NULL; 1833 Succ = EntryConditionBlock; 1834 return EntryConditionBlock; 1835} 1836 1837CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 1838 if (asc.alwaysAdd(*this, M)) { 1839 autoCreateBlock(); 1840 appendStmt(Block, M); 1841 } 1842 return Visit(M->getBase()); 1843} 1844 1845CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 1846 // Objective-C fast enumeration 'for' statements: 1847 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 1848 // 1849 // for ( Type newVariable in collection_expression ) { statements } 1850 // 1851 // becomes: 1852 // 1853 // prologue: 1854 // 1. collection_expression 1855 // T. jump to loop_entry 1856 // loop_entry: 1857 // 1. side-effects of element expression 1858 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1859 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1860 // TB: 1861 // statements 1862 // T. jump to loop_entry 1863 // FB: 1864 // what comes after 1865 // 1866 // and 1867 // 1868 // Type existingItem; 1869 // for ( existingItem in expression ) { statements } 1870 // 1871 // becomes: 1872 // 1873 // the same with newVariable replaced with existingItem; the binding works 1874 // the same except that for one ObjCForCollectionStmt::getElement() returns 1875 // a DeclStmt and the other returns a DeclRefExpr. 1876 // 1877 1878 CFGBlock *LoopSuccessor = 0; 1879 1880 if (Block) { 1881 if (badCFG) 1882 return 0; 1883 LoopSuccessor = Block; 1884 Block = 0; 1885 } else 1886 LoopSuccessor = Succ; 1887 1888 // Build the condition blocks. 1889 CFGBlock *ExitConditionBlock = createBlock(false); 1890 1891 // Set the terminator for the "exit" condition block. 1892 ExitConditionBlock->setTerminator(S); 1893 1894 // The last statement in the block should be the ObjCForCollectionStmt, which 1895 // performs the actual binding to 'element' and determines if there are any 1896 // more items in the collection. 1897 appendStmt(ExitConditionBlock, S); 1898 Block = ExitConditionBlock; 1899 1900 // Walk the 'element' expression to see if there are any side-effects. We 1901 // generate new blocks as necessary. We DON'T add the statement by default to 1902 // the CFG unless it contains control-flow. 1903 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 1904 AddStmtChoice::NotAlwaysAdd); 1905 if (Block) { 1906 if (badCFG) 1907 return 0; 1908 Block = 0; 1909 } 1910 1911 // The condition block is the implicit successor for the loop body as well as 1912 // any code above the loop. 1913 Succ = EntryConditionBlock; 1914 1915 // Now create the true branch. 1916 { 1917 // Save the current values for Succ, continue and break targets. 1918 SaveAndRestore<CFGBlock*> save_Succ(Succ); 1919 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1920 save_break(BreakJumpTarget); 1921 1922 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1923 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1924 1925 CFGBlock *BodyBlock = addStmt(S->getBody()); 1926 1927 if (!BodyBlock) 1928 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1929 else if (Block) { 1930 if (badCFG) 1931 return 0; 1932 } 1933 1934 // This new body block is a successor to our "exit" condition block. 1935 addSuccessor(ExitConditionBlock, BodyBlock); 1936 } 1937 1938 // Link up the condition block with the code that follows the loop. 1939 // (the false branch). 1940 addSuccessor(ExitConditionBlock, LoopSuccessor); 1941 1942 // Now create a prologue block to contain the collection expression. 1943 Block = createBlock(); 1944 return addStmt(S->getCollection()); 1945} 1946 1947CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 1948 // Inline the body. 1949 return addStmt(S->getSubStmt()); 1950 // TODO: consider adding cleanups for the end of @autoreleasepool scope. 1951} 1952 1953CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 1954 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1955 1956 // Inline the body. 1957 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1958 1959 // The sync body starts its own basic block. This makes it a little easier 1960 // for diagnostic clients. 1961 if (SyncBlock) { 1962 if (badCFG) 1963 return 0; 1964 1965 Block = 0; 1966 Succ = SyncBlock; 1967 } 1968 1969 // Add the @synchronized to the CFG. 1970 autoCreateBlock(); 1971 appendStmt(Block, S); 1972 1973 // Inline the sync expression. 1974 return addStmt(S->getSynchExpr()); 1975} 1976 1977CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 1978 // FIXME 1979 return NYS(); 1980} 1981 1982CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 1983 autoCreateBlock(); 1984 1985 // Add the PseudoObject as the last thing. 1986 appendStmt(Block, E); 1987 1988 CFGBlock *lastBlock = Block; 1989 1990 // Before that, evaluate all of the semantics in order. In 1991 // CFG-land, that means appending them in reverse order. 1992 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { 1993 Expr *Semantic = E->getSemanticExpr(--i); 1994 1995 // If the semantic is an opaque value, we're being asked to bind 1996 // it to its source expression. 1997 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 1998 Semantic = OVE->getSourceExpr(); 1999 2000 if (CFGBlock *B = Visit(Semantic)) 2001 lastBlock = B; 2002 } 2003 2004 return lastBlock; 2005} 2006 2007CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 2008 CFGBlock *LoopSuccessor = NULL; 2009 2010 // Save local scope position because in case of condition variable ScopePos 2011 // won't be restored when traversing AST. 2012 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2013 2014 // Create local scope for possible condition variable. 2015 // Store scope position for continue statement. 2016 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 2017 if (VarDecl *VD = W->getConditionVariable()) { 2018 addLocalScopeForVarDecl(VD); 2019 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 2020 } 2021 2022 // "while" is a control-flow statement. Thus we stop processing the current 2023 // block. 2024 if (Block) { 2025 if (badCFG) 2026 return 0; 2027 LoopSuccessor = Block; 2028 Block = 0; 2029 } else 2030 LoopSuccessor = Succ; 2031 2032 // Because of short-circuit evaluation, the condition of the loop can span 2033 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 2034 // evaluate the condition. 2035 CFGBlock *ExitConditionBlock = createBlock(false); 2036 CFGBlock *EntryConditionBlock = ExitConditionBlock; 2037 2038 // Set the terminator for the "exit" condition block. 2039 ExitConditionBlock->setTerminator(W); 2040 2041 // Now add the actual condition to the condition block. Because the condition 2042 // itself may contain control-flow, new blocks may be created. Thus we update 2043 // "Succ" after adding the condition. 2044 if (Stmt *C = W->getCond()) { 2045 Block = ExitConditionBlock; 2046 EntryConditionBlock = addStmt(C); 2047 // The condition might finish the current 'Block'. 2048 Block = EntryConditionBlock; 2049 2050 // If this block contains a condition variable, add both the condition 2051 // variable and initializer to the CFG. 2052 if (VarDecl *VD = W->getConditionVariable()) { 2053 if (Expr *Init = VD->getInit()) { 2054 autoCreateBlock(); 2055 appendStmt(Block, W->getConditionVariableDeclStmt()); 2056 EntryConditionBlock = addStmt(Init); 2057 assert(Block == EntryConditionBlock); 2058 } 2059 } 2060 2061 if (Block) { 2062 if (badCFG) 2063 return 0; 2064 } 2065 } 2066 2067 // The condition block is the implicit successor for the loop body as well as 2068 // any code above the loop. 2069 Succ = EntryConditionBlock; 2070 2071 // See if this is a known constant. 2072 const TryResult& KnownVal = tryEvaluateBool(W->getCond()); 2073 2074 // Process the loop body. 2075 { 2076 assert(W->getBody()); 2077 2078 // Save the current values for Block, Succ, and continue and break targets 2079 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2080 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2081 save_break(BreakJumpTarget); 2082 2083 // Create an empty block to represent the transition block for looping back 2084 // to the head of the loop. 2085 Block = 0; 2086 assert(Succ == EntryConditionBlock); 2087 Succ = createBlock(); 2088 Succ->setLoopTarget(W); 2089 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 2090 2091 // All breaks should go to the code following the loop. 2092 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2093 2094 // NULL out Block to force lazy instantiation of blocks for the body. 2095 Block = NULL; 2096 2097 // Loop body should end with destructor of Condition variable (if any). 2098 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 2099 2100 // If body is not a compound statement create implicit scope 2101 // and add destructors. 2102 if (!isa<CompoundStmt>(W->getBody())) 2103 addLocalScopeAndDtors(W->getBody()); 2104 2105 // Create the body. The returned block is the entry to the loop body. 2106 CFGBlock *BodyBlock = addStmt(W->getBody()); 2107 2108 if (!BodyBlock) 2109 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 2110 else if (Block) { 2111 if (badCFG) 2112 return 0; 2113 } 2114 2115 // Add the loop body entry as a successor to the condition. 2116 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 2117 } 2118 2119 // Link up the condition block with the code that follows the loop. (the 2120 // false branch). 2121 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2122 2123 // There can be no more statements in the condition block since we loop back 2124 // to this block. NULL out Block to force lazy creation of another block. 2125 Block = NULL; 2126 2127 // Return the condition block, which is the dominating block for the loop. 2128 Succ = EntryConditionBlock; 2129 return EntryConditionBlock; 2130} 2131 2132 2133CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 2134 // FIXME: For now we pretend that @catch and the code it contains does not 2135 // exit. 2136 return Block; 2137} 2138 2139CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 2140 // FIXME: This isn't complete. We basically treat @throw like a return 2141 // statement. 2142 2143 // If we were in the middle of a block we stop processing that block. 2144 if (badCFG) 2145 return 0; 2146 2147 // Create the new block. 2148 Block = createBlock(false); 2149 2150 // The Exit block is the only successor. 2151 addSuccessor(Block, &cfg->getExit()); 2152 2153 // Add the statement to the block. This may create new blocks if S contains 2154 // control-flow (short-circuit operations). 2155 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 2156} 2157 2158CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 2159 // If we were in the middle of a block we stop processing that block. 2160 if (badCFG) 2161 return 0; 2162 2163 // Create the new block. 2164 Block = createBlock(false); 2165 2166 if (TryTerminatedBlock) 2167 // The current try statement is the only successor. 2168 addSuccessor(Block, TryTerminatedBlock); 2169 else 2170 // otherwise the Exit block is the only successor. 2171 addSuccessor(Block, &cfg->getExit()); 2172 2173 // Add the statement to the block. This may create new blocks if S contains 2174 // control-flow (short-circuit operations). 2175 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 2176} 2177 2178CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 2179 CFGBlock *LoopSuccessor = NULL; 2180 2181 // "do...while" is a control-flow statement. Thus we stop processing the 2182 // current block. 2183 if (Block) { 2184 if (badCFG) 2185 return 0; 2186 LoopSuccessor = Block; 2187 } else 2188 LoopSuccessor = Succ; 2189 2190 // Because of short-circuit evaluation, the condition of the loop can span 2191 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 2192 // evaluate the condition. 2193 CFGBlock *ExitConditionBlock = createBlock(false); 2194 CFGBlock *EntryConditionBlock = ExitConditionBlock; 2195 2196 // Set the terminator for the "exit" condition block. 2197 ExitConditionBlock->setTerminator(D); 2198 2199 // Now add the actual condition to the condition block. Because the condition 2200 // itself may contain control-flow, new blocks may be created. 2201 if (Stmt *C = D->getCond()) { 2202 Block = ExitConditionBlock; 2203 EntryConditionBlock = addStmt(C); 2204 if (Block) { 2205 if (badCFG) 2206 return 0; 2207 } 2208 } 2209 2210 // The condition block is the implicit successor for the loop body. 2211 Succ = EntryConditionBlock; 2212 2213 // See if this is a known constant. 2214 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 2215 2216 // Process the loop body. 2217 CFGBlock *BodyBlock = NULL; 2218 { 2219 assert(D->getBody()); 2220 2221 // Save the current values for Block, Succ, and continue and break targets 2222 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2223 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2224 save_break(BreakJumpTarget); 2225 2226 // All continues within this loop should go to the condition block 2227 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 2228 2229 // All breaks should go to the code following the loop. 2230 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2231 2232 // NULL out Block to force lazy instantiation of blocks for the body. 2233 Block = NULL; 2234 2235 // If body is not a compound statement create implicit scope 2236 // and add destructors. 2237 if (!isa<CompoundStmt>(D->getBody())) 2238 addLocalScopeAndDtors(D->getBody()); 2239 2240 // Create the body. The returned block is the entry to the loop body. 2241 BodyBlock = addStmt(D->getBody()); 2242 2243 if (!BodyBlock) 2244 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 2245 else if (Block) { 2246 if (badCFG) 2247 return 0; 2248 } 2249 2250 if (!KnownVal.isFalse()) { 2251 // Add an intermediate block between the BodyBlock and the 2252 // ExitConditionBlock to represent the "loop back" transition. Create an 2253 // empty block to represent the transition block for looping back to the 2254 // head of the loop. 2255 // FIXME: Can we do this more efficiently without adding another block? 2256 Block = NULL; 2257 Succ = BodyBlock; 2258 CFGBlock *LoopBackBlock = createBlock(); 2259 LoopBackBlock->setLoopTarget(D); 2260 2261 // Add the loop body entry as a successor to the condition. 2262 addSuccessor(ExitConditionBlock, LoopBackBlock); 2263 } 2264 else 2265 addSuccessor(ExitConditionBlock, NULL); 2266 } 2267 2268 // Link up the condition block with the code that follows the loop. 2269 // (the false branch). 2270 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2271 2272 // There can be no more statements in the body block(s) since we loop back to 2273 // the body. NULL out Block to force lazy creation of another block. 2274 Block = NULL; 2275 2276 // Return the loop body, which is the dominating block for the loop. 2277 Succ = BodyBlock; 2278 return BodyBlock; 2279} 2280 2281CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 2282 // "continue" is a control-flow statement. Thus we stop processing the 2283 // current block. 2284 if (badCFG) 2285 return 0; 2286 2287 // Now create a new block that ends with the continue statement. 2288 Block = createBlock(false); 2289 Block->setTerminator(C); 2290 2291 // If there is no target for the continue, then we are looking at an 2292 // incomplete AST. This means the CFG cannot be constructed. 2293 if (ContinueJumpTarget.block) { 2294 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); 2295 addSuccessor(Block, ContinueJumpTarget.block); 2296 } else 2297 badCFG = true; 2298 2299 return Block; 2300} 2301 2302CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 2303 AddStmtChoice asc) { 2304 2305 if (asc.alwaysAdd(*this, E)) { 2306 autoCreateBlock(); 2307 appendStmt(Block, E); 2308 } 2309 2310 // VLA types have expressions that must be evaluated. 2311 CFGBlock *lastBlock = Block; 2312 2313 if (E->isArgumentType()) { 2314 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 2315 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 2316 lastBlock = addStmt(VA->getSizeExpr()); 2317 } 2318 return lastBlock; 2319} 2320 2321/// VisitStmtExpr - Utility method to handle (nested) statement 2322/// expressions (a GCC extension). 2323CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 2324 if (asc.alwaysAdd(*this, SE)) { 2325 autoCreateBlock(); 2326 appendStmt(Block, SE); 2327 } 2328 return VisitCompoundStmt(SE->getSubStmt()); 2329} 2330 2331CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 2332 // "switch" is a control-flow statement. Thus we stop processing the current 2333 // block. 2334 CFGBlock *SwitchSuccessor = NULL; 2335 2336 // Save local scope position because in case of condition variable ScopePos 2337 // won't be restored when traversing AST. 2338 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2339 2340 // Create local scope for possible condition variable. 2341 // Store scope position. Add implicit destructor. 2342 if (VarDecl *VD = Terminator->getConditionVariable()) { 2343 LocalScope::const_iterator SwitchBeginScopePos = ScopePos; 2344 addLocalScopeForVarDecl(VD); 2345 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); 2346 } 2347 2348 if (Block) { 2349 if (badCFG) 2350 return 0; 2351 SwitchSuccessor = Block; 2352 } else SwitchSuccessor = Succ; 2353 2354 // Save the current "switch" context. 2355 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 2356 save_default(DefaultCaseBlock); 2357 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2358 2359 // Set the "default" case to be the block after the switch statement. If the 2360 // switch statement contains a "default:", this value will be overwritten with 2361 // the block for that code. 2362 DefaultCaseBlock = SwitchSuccessor; 2363 2364 // Create a new block that will contain the switch statement. 2365 SwitchTerminatedBlock = createBlock(false); 2366 2367 // Now process the switch body. The code after the switch is the implicit 2368 // successor. 2369 Succ = SwitchSuccessor; 2370 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 2371 2372 // When visiting the body, the case statements should automatically get linked 2373 // up to the switch. We also don't keep a pointer to the body, since all 2374 // control-flow from the switch goes to case/default statements. 2375 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 2376 Block = NULL; 2377 2378 // For pruning unreachable case statements, save the current state 2379 // for tracking the condition value. 2380 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 2381 false); 2382 2383 // Determine if the switch condition can be explicitly evaluated. 2384 assert(Terminator->getCond() && "switch condition must be non-NULL"); 2385 Expr::EvalResult result; 2386 bool b = tryEvaluate(Terminator->getCond(), result); 2387 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 2388 b ? &result : 0); 2389 2390 // If body is not a compound statement create implicit scope 2391 // and add destructors. 2392 if (!isa<CompoundStmt>(Terminator->getBody())) 2393 addLocalScopeAndDtors(Terminator->getBody()); 2394 2395 addStmt(Terminator->getBody()); 2396 if (Block) { 2397 if (badCFG) 2398 return 0; 2399 } 2400 2401 // If we have no "default:" case, the default transition is to the code 2402 // following the switch body. Moreover, take into account if all the 2403 // cases of a switch are covered (e.g., switching on an enum value). 2404 addSuccessor(SwitchTerminatedBlock, 2405 switchExclusivelyCovered || Terminator->isAllEnumCasesCovered() 2406 ? 0 : DefaultCaseBlock); 2407 2408 // Add the terminator and condition in the switch block. 2409 SwitchTerminatedBlock->setTerminator(Terminator); 2410 Block = SwitchTerminatedBlock; 2411 Block = addStmt(Terminator->getCond()); 2412 2413 // Finally, if the SwitchStmt contains a condition variable, add both the 2414 // SwitchStmt and the condition variable initialization to the CFG. 2415 if (VarDecl *VD = Terminator->getConditionVariable()) { 2416 if (Expr *Init = VD->getInit()) { 2417 autoCreateBlock(); 2418 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 2419 addStmt(Init); 2420 } 2421 } 2422 2423 return Block; 2424} 2425 2426static bool shouldAddCase(bool &switchExclusivelyCovered, 2427 const Expr::EvalResult *switchCond, 2428 const CaseStmt *CS, 2429 ASTContext &Ctx) { 2430 if (!switchCond) 2431 return true; 2432 2433 bool addCase = false; 2434 2435 if (!switchExclusivelyCovered) { 2436 if (switchCond->Val.isInt()) { 2437 // Evaluate the LHS of the case value. 2438 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); 2439 const llvm::APSInt &condInt = switchCond->Val.getInt(); 2440 2441 if (condInt == lhsInt) { 2442 addCase = true; 2443 switchExclusivelyCovered = true; 2444 } 2445 else if (condInt < lhsInt) { 2446 if (const Expr *RHS = CS->getRHS()) { 2447 // Evaluate the RHS of the case value. 2448 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); 2449 if (V2 <= condInt) { 2450 addCase = true; 2451 switchExclusivelyCovered = true; 2452 } 2453 } 2454 } 2455 } 2456 else 2457 addCase = true; 2458 } 2459 return addCase; 2460} 2461 2462CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 2463 // CaseStmts are essentially labels, so they are the first statement in a 2464 // block. 2465 CFGBlock *TopBlock = 0, *LastBlock = 0; 2466 2467 if (Stmt *Sub = CS->getSubStmt()) { 2468 // For deeply nested chains of CaseStmts, instead of doing a recursion 2469 // (which can blow out the stack), manually unroll and create blocks 2470 // along the way. 2471 while (isa<CaseStmt>(Sub)) { 2472 CFGBlock *currentBlock = createBlock(false); 2473 currentBlock->setLabel(CS); 2474 2475 if (TopBlock) 2476 addSuccessor(LastBlock, currentBlock); 2477 else 2478 TopBlock = currentBlock; 2479 2480 addSuccessor(SwitchTerminatedBlock, 2481 shouldAddCase(switchExclusivelyCovered, switchCond, 2482 CS, *Context) 2483 ? currentBlock : 0); 2484 2485 LastBlock = currentBlock; 2486 CS = cast<CaseStmt>(Sub); 2487 Sub = CS->getSubStmt(); 2488 } 2489 2490 addStmt(Sub); 2491 } 2492 2493 CFGBlock *CaseBlock = Block; 2494 if (!CaseBlock) 2495 CaseBlock = createBlock(); 2496 2497 // Cases statements partition blocks, so this is the top of the basic block we 2498 // were processing (the "case XXX:" is the label). 2499 CaseBlock->setLabel(CS); 2500 2501 if (badCFG) 2502 return 0; 2503 2504 // Add this block to the list of successors for the block with the switch 2505 // statement. 2506 assert(SwitchTerminatedBlock); 2507 addSuccessor(SwitchTerminatedBlock, 2508 shouldAddCase(switchExclusivelyCovered, switchCond, 2509 CS, *Context) 2510 ? CaseBlock : 0); 2511 2512 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2513 Block = NULL; 2514 2515 if (TopBlock) { 2516 addSuccessor(LastBlock, CaseBlock); 2517 Succ = TopBlock; 2518 } else { 2519 // This block is now the implicit successor of other blocks. 2520 Succ = CaseBlock; 2521 } 2522 2523 return Succ; 2524} 2525 2526CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 2527 if (Terminator->getSubStmt()) 2528 addStmt(Terminator->getSubStmt()); 2529 2530 DefaultCaseBlock = Block; 2531 2532 if (!DefaultCaseBlock) 2533 DefaultCaseBlock = createBlock(); 2534 2535 // Default statements partition blocks, so this is the top of the basic block 2536 // we were processing (the "default:" is the label). 2537 DefaultCaseBlock->setLabel(Terminator); 2538 2539 if (badCFG) 2540 return 0; 2541 2542 // Unlike case statements, we don't add the default block to the successors 2543 // for the switch statement immediately. This is done when we finish 2544 // processing the switch statement. This allows for the default case 2545 // (including a fall-through to the code after the switch statement) to always 2546 // be the last successor of a switch-terminated block. 2547 2548 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2549 Block = NULL; 2550 2551 // This block is now the implicit successor of other blocks. 2552 Succ = DefaultCaseBlock; 2553 2554 return DefaultCaseBlock; 2555} 2556 2557CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 2558 // "try"/"catch" is a control-flow statement. Thus we stop processing the 2559 // current block. 2560 CFGBlock *TrySuccessor = NULL; 2561 2562 if (Block) { 2563 if (badCFG) 2564 return 0; 2565 TrySuccessor = Block; 2566 } else TrySuccessor = Succ; 2567 2568 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 2569 2570 // Create a new block that will contain the try statement. 2571 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2572 // Add the terminator in the try block. 2573 NewTryTerminatedBlock->setTerminator(Terminator); 2574 2575 bool HasCatchAll = false; 2576 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 2577 // The code after the try is the implicit successor. 2578 Succ = TrySuccessor; 2579 CXXCatchStmt *CS = Terminator->getHandler(h); 2580 if (CS->getExceptionDecl() == 0) { 2581 HasCatchAll = true; 2582 } 2583 Block = NULL; 2584 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 2585 if (CatchBlock == 0) 2586 return 0; 2587 // Add this block to the list of successors for the block with the try 2588 // statement. 2589 addSuccessor(NewTryTerminatedBlock, CatchBlock); 2590 } 2591 if (!HasCatchAll) { 2592 if (PrevTryTerminatedBlock) 2593 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 2594 else 2595 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2596 } 2597 2598 // The code after the try is the implicit successor. 2599 Succ = TrySuccessor; 2600 2601 // Save the current "try" context. 2602 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); 2603 cfg->addTryDispatchBlock(TryTerminatedBlock); 2604 2605 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 2606 Block = NULL; 2607 Block = addStmt(Terminator->getTryBlock()); 2608 return Block; 2609} 2610 2611CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 2612 // CXXCatchStmt are treated like labels, so they are the first statement in a 2613 // block. 2614 2615 // Save local scope position because in case of exception variable ScopePos 2616 // won't be restored when traversing AST. 2617 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2618 2619 // Create local scope for possible exception variable. 2620 // Store scope position. Add implicit destructor. 2621 if (VarDecl *VD = CS->getExceptionDecl()) { 2622 LocalScope::const_iterator BeginScopePos = ScopePos; 2623 addLocalScopeForVarDecl(VD); 2624 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 2625 } 2626 2627 if (CS->getHandlerBlock()) 2628 addStmt(CS->getHandlerBlock()); 2629 2630 CFGBlock *CatchBlock = Block; 2631 if (!CatchBlock) 2632 CatchBlock = createBlock(); 2633 2634 // CXXCatchStmt is more than just a label. They have semantic meaning 2635 // as well, as they implicitly "initialize" the catch variable. Add 2636 // it to the CFG as a CFGElement so that the control-flow of these 2637 // semantics gets captured. 2638 appendStmt(CatchBlock, CS); 2639 2640 // Also add the CXXCatchStmt as a label, to mirror handling of regular 2641 // labels. 2642 CatchBlock->setLabel(CS); 2643 2644 // Bail out if the CFG is bad. 2645 if (badCFG) 2646 return 0; 2647 2648 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2649 Block = NULL; 2650 2651 return CatchBlock; 2652} 2653 2654CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 2655 // C++0x for-range statements are specified as [stmt.ranged]: 2656 // 2657 // { 2658 // auto && __range = range-init; 2659 // for ( auto __begin = begin-expr, 2660 // __end = end-expr; 2661 // __begin != __end; 2662 // ++__begin ) { 2663 // for-range-declaration = *__begin; 2664 // statement 2665 // } 2666 // } 2667 2668 // Save local scope position before the addition of the implicit variables. 2669 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2670 2671 // Create local scopes and destructors for range, begin and end variables. 2672 if (Stmt *Range = S->getRangeStmt()) 2673 addLocalScopeForStmt(Range); 2674 if (Stmt *BeginEnd = S->getBeginEndStmt()) 2675 addLocalScopeForStmt(BeginEnd); 2676 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S); 2677 2678 LocalScope::const_iterator ContinueScopePos = ScopePos; 2679 2680 // "for" is a control-flow statement. Thus we stop processing the current 2681 // block. 2682 CFGBlock *LoopSuccessor = NULL; 2683 if (Block) { 2684 if (badCFG) 2685 return 0; 2686 LoopSuccessor = Block; 2687 } else 2688 LoopSuccessor = Succ; 2689 2690 // Save the current value for the break targets. 2691 // All breaks should go to the code following the loop. 2692 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2693 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2694 2695 // The block for the __begin != __end expression. 2696 CFGBlock *ConditionBlock = createBlock(false); 2697 ConditionBlock->setTerminator(S); 2698 2699 // Now add the actual condition to the condition block. 2700 if (Expr *C = S->getCond()) { 2701 Block = ConditionBlock; 2702 CFGBlock *BeginConditionBlock = addStmt(C); 2703 if (badCFG) 2704 return 0; 2705 assert(BeginConditionBlock == ConditionBlock && 2706 "condition block in for-range was unexpectedly complex"); 2707 (void)BeginConditionBlock; 2708 } 2709 2710 // The condition block is the implicit successor for the loop body as well as 2711 // any code above the loop. 2712 Succ = ConditionBlock; 2713 2714 // See if this is a known constant. 2715 TryResult KnownVal(true); 2716 2717 if (S->getCond()) 2718 KnownVal = tryEvaluateBool(S->getCond()); 2719 2720 // Now create the loop body. 2721 { 2722 assert(S->getBody()); 2723 2724 // Save the current values for Block, Succ, and continue targets. 2725 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2726 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 2727 2728 // Generate increment code in its own basic block. This is the target of 2729 // continue statements. 2730 Block = 0; 2731 Succ = addStmt(S->getInc()); 2732 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 2733 2734 // The starting block for the loop increment is the block that should 2735 // represent the 'loop target' for looping back to the start of the loop. 2736 ContinueJumpTarget.block->setLoopTarget(S); 2737 2738 // Finish up the increment block and prepare to start the loop body. 2739 assert(Block); 2740 if (badCFG) 2741 return 0; 2742 Block = 0; 2743 2744 2745 // Add implicit scope and dtors for loop variable. 2746 addLocalScopeAndDtors(S->getLoopVarStmt()); 2747 2748 // Populate a new block to contain the loop body and loop variable. 2749 Block = addStmt(S->getBody()); 2750 if (badCFG) 2751 return 0; 2752 Block = addStmt(S->getLoopVarStmt()); 2753 if (badCFG) 2754 return 0; 2755 2756 // This new body block is a successor to our condition block. 2757 addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : Block); 2758 } 2759 2760 // Link up the condition block with the code that follows the loop (the 2761 // false branch). 2762 addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor); 2763 2764 // Add the initialization statements. 2765 Block = createBlock(); 2766 addStmt(S->getBeginEndStmt()); 2767 return addStmt(S->getRangeStmt()); 2768} 2769 2770CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 2771 AddStmtChoice asc) { 2772 if (BuildOpts.AddImplicitDtors) { 2773 // If adding implicit destructors visit the full expression for adding 2774 // destructors of temporaries. 2775 VisitForTemporaryDtors(E->getSubExpr()); 2776 2777 // Full expression has to be added as CFGStmt so it will be sequenced 2778 // before destructors of it's temporaries. 2779 asc = asc.withAlwaysAdd(true); 2780 } 2781 return Visit(E->getSubExpr(), asc); 2782} 2783 2784CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 2785 AddStmtChoice asc) { 2786 if (asc.alwaysAdd(*this, E)) { 2787 autoCreateBlock(); 2788 appendStmt(Block, E); 2789 2790 // We do not want to propagate the AlwaysAdd property. 2791 asc = asc.withAlwaysAdd(false); 2792 } 2793 return Visit(E->getSubExpr(), asc); 2794} 2795 2796CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 2797 AddStmtChoice asc) { 2798 autoCreateBlock(); 2799 appendStmt(Block, C); 2800 2801 return VisitChildren(C); 2802} 2803 2804CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2805 AddStmtChoice asc) { 2806 if (asc.alwaysAdd(*this, E)) { 2807 autoCreateBlock(); 2808 appendStmt(Block, E); 2809 // We do not want to propagate the AlwaysAdd property. 2810 asc = asc.withAlwaysAdd(false); 2811 } 2812 return Visit(E->getSubExpr(), asc); 2813} 2814 2815CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2816 AddStmtChoice asc) { 2817 autoCreateBlock(); 2818 appendStmt(Block, C); 2819 return VisitChildren(C); 2820} 2821 2822CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2823 AddStmtChoice asc) { 2824 if (asc.alwaysAdd(*this, E)) { 2825 autoCreateBlock(); 2826 appendStmt(Block, E); 2827 } 2828 return Visit(E->getSubExpr(), AddStmtChoice()); 2829} 2830 2831CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 2832 // Lazily create the indirect-goto dispatch block if there isn't one already. 2833 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 2834 2835 if (!IBlock) { 2836 IBlock = createBlock(false); 2837 cfg->setIndirectGotoBlock(IBlock); 2838 } 2839 2840 // IndirectGoto is a control-flow statement. Thus we stop processing the 2841 // current block and create a new one. 2842 if (badCFG) 2843 return 0; 2844 2845 Block = createBlock(false); 2846 Block->setTerminator(I); 2847 addSuccessor(Block, IBlock); 2848 return addStmt(I->getTarget()); 2849} 2850 2851CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2852tryAgain: 2853 if (!E) { 2854 badCFG = true; 2855 return NULL; 2856 } 2857 switch (E->getStmtClass()) { 2858 default: 2859 return VisitChildrenForTemporaryDtors(E); 2860 2861 case Stmt::BinaryOperatorClass: 2862 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2863 2864 case Stmt::CXXBindTemporaryExprClass: 2865 return VisitCXXBindTemporaryExprForTemporaryDtors( 2866 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2867 2868 case Stmt::BinaryConditionalOperatorClass: 2869 case Stmt::ConditionalOperatorClass: 2870 return VisitConditionalOperatorForTemporaryDtors( 2871 cast<AbstractConditionalOperator>(E), BindToTemporary); 2872 2873 case Stmt::ImplicitCastExprClass: 2874 // For implicit cast we want BindToTemporary to be passed further. 2875 E = cast<CastExpr>(E)->getSubExpr(); 2876 goto tryAgain; 2877 2878 case Stmt::ParenExprClass: 2879 E = cast<ParenExpr>(E)->getSubExpr(); 2880 goto tryAgain; 2881 2882 case Stmt::MaterializeTemporaryExprClass: 2883 E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(); 2884 goto tryAgain; 2885 } 2886} 2887 2888CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2889 // When visiting children for destructors we want to visit them in reverse 2890 // order. Because there's no reverse iterator for children must to reverse 2891 // them in helper vector. 2892 typedef SmallVector<Stmt *, 4> ChildrenVect; 2893 ChildrenVect ChildrenRev; 2894 for (Stmt::child_range I = E->children(); I; ++I) { 2895 if (*I) ChildrenRev.push_back(*I); 2896 } 2897 2898 CFGBlock *B = Block; 2899 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2900 L = ChildrenRev.rend(); I != L; ++I) { 2901 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2902 B = R; 2903 } 2904 return B; 2905} 2906 2907CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2908 if (E->isLogicalOp()) { 2909 // Destructors for temporaries in LHS expression should be called after 2910 // those for RHS expression. Even if this will unnecessarily create a block, 2911 // this block will be used at least by the full expression. 2912 autoCreateBlock(); 2913 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2914 if (badCFG) 2915 return NULL; 2916 2917 Succ = ConfluenceBlock; 2918 Block = NULL; 2919 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2920 2921 if (RHSBlock) { 2922 if (badCFG) 2923 return NULL; 2924 2925 // If RHS expression did produce destructors we need to connect created 2926 // blocks to CFG in same manner as for binary operator itself. 2927 CFGBlock *LHSBlock = createBlock(false); 2928 LHSBlock->setTerminator(CFGTerminator(E, true)); 2929 2930 // For binary operator LHS block is before RHS in list of predecessors 2931 // of ConfluenceBlock. 2932 std::reverse(ConfluenceBlock->pred_begin(), 2933 ConfluenceBlock->pred_end()); 2934 2935 // See if this is a known constant. 2936 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 2937 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2938 KnownVal.negate(); 2939 2940 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2941 // itself. 2942 if (E->getOpcode() == BO_LOr) { 2943 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2944 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2945 } else { 2946 assert (E->getOpcode() == BO_LAnd); 2947 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2948 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2949 } 2950 2951 Block = LHSBlock; 2952 return LHSBlock; 2953 } 2954 2955 Block = ConfluenceBlock; 2956 return ConfluenceBlock; 2957 } 2958 2959 if (E->isAssignmentOp()) { 2960 // For assignment operator (=) LHS expression is visited 2961 // before RHS expression. For destructors visit them in reverse order. 2962 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2963 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2964 return LHSBlock ? LHSBlock : RHSBlock; 2965 } 2966 2967 // For any other binary operator RHS expression is visited before 2968 // LHS expression (order of children). For destructors visit them in reverse 2969 // order. 2970 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2971 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2972 return RHSBlock ? RHSBlock : LHSBlock; 2973} 2974 2975CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2976 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2977 // First add destructors for temporaries in subexpression. 2978 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2979 if (!BindToTemporary) { 2980 // If lifetime of temporary is not prolonged (by assigning to constant 2981 // reference) add destructor for it. 2982 2983 // If the destructor is marked as a no-return destructor, we need to create 2984 // a new block for the destructor which does not have as a successor 2985 // anything built thus far. Control won't flow out of this block. 2986 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 2987 if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) 2988 Block = createNoReturnBlock(); 2989 else 2990 autoCreateBlock(); 2991 2992 appendTemporaryDtor(Block, E); 2993 B = Block; 2994 } 2995 return B; 2996} 2997 2998CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2999 AbstractConditionalOperator *E, bool BindToTemporary) { 3000 // First add destructors for condition expression. Even if this will 3001 // unnecessarily create a block, this block will be used at least by the full 3002 // expression. 3003 autoCreateBlock(); 3004 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 3005 if (badCFG) 3006 return NULL; 3007 if (BinaryConditionalOperator *BCO 3008 = dyn_cast<BinaryConditionalOperator>(E)) { 3009 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 3010 if (badCFG) 3011 return NULL; 3012 } 3013 3014 // Try to add block with destructors for LHS expression. 3015 CFGBlock *LHSBlock = NULL; 3016 Succ = ConfluenceBlock; 3017 Block = NULL; 3018 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 3019 if (badCFG) 3020 return NULL; 3021 3022 // Try to add block with destructors for RHS expression; 3023 Succ = ConfluenceBlock; 3024 Block = NULL; 3025 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 3026 BindToTemporary); 3027 if (badCFG) 3028 return NULL; 3029 3030 if (!RHSBlock && !LHSBlock) { 3031 // If neither LHS nor RHS expression had temporaries to destroy don't create 3032 // more blocks. 3033 Block = ConfluenceBlock; 3034 return Block; 3035 } 3036 3037 Block = createBlock(false); 3038 Block->setTerminator(CFGTerminator(E, true)); 3039 3040 // See if this is a known constant. 3041 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 3042 3043 if (LHSBlock) { 3044 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 3045 } else if (KnownVal.isFalse()) { 3046 addSuccessor(Block, NULL); 3047 } else { 3048 addSuccessor(Block, ConfluenceBlock); 3049 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 3050 } 3051 3052 if (!RHSBlock) 3053 RHSBlock = ConfluenceBlock; 3054 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 3055 3056 return Block; 3057} 3058 3059} // end anonymous namespace 3060 3061/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 3062/// no successors or predecessors. If this is the first block created in the 3063/// CFG, it is automatically set to be the Entry and Exit of the CFG. 3064CFGBlock *CFG::createBlock() { 3065 bool first_block = begin() == end(); 3066 3067 // Create the block. 3068 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 3069 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); 3070 Blocks.push_back(Mem, BlkBVC); 3071 3072 // If this is the first block, set it as the Entry and Exit. 3073 if (first_block) 3074 Entry = Exit = &back(); 3075 3076 // Return the block. 3077 return &back(); 3078} 3079 3080/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 3081/// CFG is returned to the caller. 3082CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, 3083 const BuildOptions &BO) { 3084 CFGBuilder Builder(C, BO); 3085 return Builder.buildCFG(D, Statement); 3086} 3087 3088const CXXDestructorDecl * 3089CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 3090 switch (getKind()) { 3091 case CFGElement::Invalid: 3092 case CFGElement::Statement: 3093 case CFGElement::Initializer: 3094 llvm_unreachable("getDestructorDecl should only be used with " 3095 "ImplicitDtors"); 3096 case CFGElement::AutomaticObjectDtor: { 3097 const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl(); 3098 QualType ty = var->getType(); 3099 ty = ty.getNonReferenceType(); 3100 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 3101 ty = arrayType->getElementType(); 3102 } 3103 const RecordType *recordType = ty->getAs<RecordType>(); 3104 const CXXRecordDecl *classDecl = 3105 cast<CXXRecordDecl>(recordType->getDecl()); 3106 return classDecl->getDestructor(); 3107 } 3108 case CFGElement::TemporaryDtor: { 3109 const CXXBindTemporaryExpr *bindExpr = 3110 cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr(); 3111 const CXXTemporary *temp = bindExpr->getTemporary(); 3112 return temp->getDestructor(); 3113 } 3114 case CFGElement::BaseDtor: 3115 case CFGElement::MemberDtor: 3116 3117 // Not yet supported. 3118 return 0; 3119 } 3120 llvm_unreachable("getKind() returned bogus value"); 3121} 3122 3123bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 3124 if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) { 3125 QualType ty = cdecl->getType(); 3126 return cast<FunctionType>(ty)->getNoReturnAttr(); 3127 } 3128 return false; 3129} 3130 3131//===----------------------------------------------------------------------===// 3132// CFG: Queries for BlkExprs. 3133//===----------------------------------------------------------------------===// 3134 3135namespace { 3136 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 3137} 3138 3139static void FindSubExprAssignments(const Stmt *S, 3140 llvm::SmallPtrSet<const Expr*,50>& Set) { 3141 if (!S) 3142 return; 3143 3144 for (Stmt::const_child_range I = S->children(); I; ++I) { 3145 const Stmt *child = *I; 3146 if (!child) 3147 continue; 3148 3149 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 3150 if (B->isAssignmentOp()) Set.insert(B); 3151 3152 FindSubExprAssignments(child, Set); 3153 } 3154} 3155 3156static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 3157 BlkExprMapTy* M = new BlkExprMapTy(); 3158 3159 // Look for assignments that are used as subexpressions. These are the only 3160 // assignments that we want to *possibly* register as a block-level 3161 // expression. Basically, if an assignment occurs both in a subexpression and 3162 // at the block-level, it is a block-level expression. 3163 llvm::SmallPtrSet<const Expr*,50> SubExprAssignments; 3164 3165 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 3166 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 3167 if (const CFGStmt *S = BI->getAs<CFGStmt>()) 3168 FindSubExprAssignments(S->getStmt(), SubExprAssignments); 3169 3170 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 3171 3172 // Iterate over the statements again on identify the Expr* and Stmt* at the 3173 // block-level that are block-level expressions. 3174 3175 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 3176 const CFGStmt *CS = BI->getAs<CFGStmt>(); 3177 if (!CS) 3178 continue; 3179 if (const Expr *Exp = dyn_cast<Expr>(CS->getStmt())) { 3180 assert((Exp->IgnoreParens() == Exp) && "No parens on block-level exps"); 3181 3182 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 3183 // Assignment expressions that are not nested within another 3184 // expression are really "statements" whose value is never used by 3185 // another expression. 3186 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 3187 continue; 3188 } else if (const StmtExpr *SE = dyn_cast<StmtExpr>(Exp)) { 3189 // Special handling for statement expressions. The last statement in 3190 // the statement expression is also a block-level expr. 3191 const CompoundStmt *C = SE->getSubStmt(); 3192 if (!C->body_empty()) { 3193 const Stmt *Last = C->body_back(); 3194 if (const Expr *LastEx = dyn_cast<Expr>(Last)) 3195 Last = LastEx->IgnoreParens(); 3196 unsigned x = M->size(); 3197 (*M)[Last] = x; 3198 } 3199 } 3200 3201 unsigned x = M->size(); 3202 (*M)[Exp] = x; 3203 } 3204 } 3205 3206 // Look at terminators. The condition is a block-level expression. 3207 3208 Stmt *S = (*I)->getTerminatorCondition(); 3209 3210 if (S && M->find(S) == M->end()) { 3211 unsigned x = M->size(); 3212 (*M)[S] = x; 3213 } 3214 } 3215 3216 return M; 3217} 3218 3219CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt *S) { 3220 assert(S != NULL); 3221 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 3222 3223 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 3224 BlkExprMapTy::iterator I = M->find(S); 3225 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 3226} 3227 3228unsigned CFG::getNumBlkExprs() { 3229 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 3230 return M->size(); 3231 3232 // We assume callers interested in the number of BlkExprs will want 3233 // the map constructed if it doesn't already exist. 3234 BlkExprMap = (void*) PopulateBlkExprMap(*this); 3235 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 3236} 3237 3238//===----------------------------------------------------------------------===// 3239// Filtered walking of the CFG. 3240//===----------------------------------------------------------------------===// 3241 3242bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 3243 const CFGBlock *From, const CFGBlock *To) { 3244 3245 if (To && F.IgnoreDefaultsWithCoveredEnums) { 3246 // If the 'To' has no label or is labeled but the label isn't a 3247 // CaseStmt then filter this edge. 3248 if (const SwitchStmt *S = 3249 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 3250 if (S->isAllEnumCasesCovered()) { 3251 const Stmt *L = To->getLabel(); 3252 if (!L || !isa<CaseStmt>(L)) 3253 return true; 3254 } 3255 } 3256 } 3257 3258 return false; 3259} 3260 3261//===----------------------------------------------------------------------===// 3262// Cleanup: CFG dstor. 3263//===----------------------------------------------------------------------===// 3264 3265CFG::~CFG() { 3266 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 3267} 3268 3269//===----------------------------------------------------------------------===// 3270// CFG pretty printing 3271//===----------------------------------------------------------------------===// 3272 3273namespace { 3274 3275class StmtPrinterHelper : public PrinterHelper { 3276 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 3277 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 3278 StmtMapTy StmtMap; 3279 DeclMapTy DeclMap; 3280 signed currentBlock; 3281 unsigned currentStmt; 3282 const LangOptions &LangOpts; 3283public: 3284 3285 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 3286 : currentBlock(0), currentStmt(0), LangOpts(LO) 3287 { 3288 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 3289 unsigned j = 1; 3290 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 3291 BI != BEnd; ++BI, ++j ) { 3292 if (const CFGStmt *SE = BI->getAs<CFGStmt>()) { 3293 const Stmt *stmt= SE->getStmt(); 3294 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 3295 StmtMap[stmt] = P; 3296 3297 switch (stmt->getStmtClass()) { 3298 case Stmt::DeclStmtClass: 3299 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 3300 break; 3301 case Stmt::IfStmtClass: { 3302 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 3303 if (var) 3304 DeclMap[var] = P; 3305 break; 3306 } 3307 case Stmt::ForStmtClass: { 3308 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 3309 if (var) 3310 DeclMap[var] = P; 3311 break; 3312 } 3313 case Stmt::WhileStmtClass: { 3314 const VarDecl *var = 3315 cast<WhileStmt>(stmt)->getConditionVariable(); 3316 if (var) 3317 DeclMap[var] = P; 3318 break; 3319 } 3320 case Stmt::SwitchStmtClass: { 3321 const VarDecl *var = 3322 cast<SwitchStmt>(stmt)->getConditionVariable(); 3323 if (var) 3324 DeclMap[var] = P; 3325 break; 3326 } 3327 case Stmt::CXXCatchStmtClass: { 3328 const VarDecl *var = 3329 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 3330 if (var) 3331 DeclMap[var] = P; 3332 break; 3333 } 3334 default: 3335 break; 3336 } 3337 } 3338 } 3339 } 3340 } 3341 3342 3343 virtual ~StmtPrinterHelper() {} 3344 3345 const LangOptions &getLangOpts() const { return LangOpts; } 3346 void setBlockID(signed i) { currentBlock = i; } 3347 void setStmtID(unsigned i) { currentStmt = i; } 3348 3349 virtual bool handledStmt(Stmt *S, raw_ostream &OS) { 3350 StmtMapTy::iterator I = StmtMap.find(S); 3351 3352 if (I == StmtMap.end()) 3353 return false; 3354 3355 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3356 && I->second.second == currentStmt) { 3357 return false; 3358 } 3359 3360 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3361 return true; 3362 } 3363 3364 bool handleDecl(const Decl *D, raw_ostream &OS) { 3365 DeclMapTy::iterator I = DeclMap.find(D); 3366 3367 if (I == DeclMap.end()) 3368 return false; 3369 3370 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3371 && I->second.second == currentStmt) { 3372 return false; 3373 } 3374 3375 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3376 return true; 3377 } 3378}; 3379} // end anonymous namespace 3380 3381 3382namespace { 3383class CFGBlockTerminatorPrint 3384 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 3385 3386 raw_ostream &OS; 3387 StmtPrinterHelper* Helper; 3388 PrintingPolicy Policy; 3389public: 3390 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 3391 const PrintingPolicy &Policy) 3392 : OS(os), Helper(helper), Policy(Policy) {} 3393 3394 void VisitIfStmt(IfStmt *I) { 3395 OS << "if "; 3396 I->getCond()->printPretty(OS,Helper,Policy); 3397 } 3398 3399 // Default case. 3400 void VisitStmt(Stmt *Terminator) { 3401 Terminator->printPretty(OS, Helper, Policy); 3402 } 3403 3404 void VisitForStmt(ForStmt *F) { 3405 OS << "for (" ; 3406 if (F->getInit()) 3407 OS << "..."; 3408 OS << "; "; 3409 if (Stmt *C = F->getCond()) 3410 C->printPretty(OS, Helper, Policy); 3411 OS << "; "; 3412 if (F->getInc()) 3413 OS << "..."; 3414 OS << ")"; 3415 } 3416 3417 void VisitWhileStmt(WhileStmt *W) { 3418 OS << "while " ; 3419 if (Stmt *C = W->getCond()) 3420 C->printPretty(OS, Helper, Policy); 3421 } 3422 3423 void VisitDoStmt(DoStmt *D) { 3424 OS << "do ... while "; 3425 if (Stmt *C = D->getCond()) 3426 C->printPretty(OS, Helper, Policy); 3427 } 3428 3429 void VisitSwitchStmt(SwitchStmt *Terminator) { 3430 OS << "switch "; 3431 Terminator->getCond()->printPretty(OS, Helper, Policy); 3432 } 3433 3434 void VisitCXXTryStmt(CXXTryStmt *CS) { 3435 OS << "try ..."; 3436 } 3437 3438 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 3439 C->getCond()->printPretty(OS, Helper, Policy); 3440 OS << " ? ... : ..."; 3441 } 3442 3443 void VisitChooseExpr(ChooseExpr *C) { 3444 OS << "__builtin_choose_expr( "; 3445 C->getCond()->printPretty(OS, Helper, Policy); 3446 OS << " )"; 3447 } 3448 3449 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 3450 OS << "goto *"; 3451 I->getTarget()->printPretty(OS, Helper, Policy); 3452 } 3453 3454 void VisitBinaryOperator(BinaryOperator* B) { 3455 if (!B->isLogicalOp()) { 3456 VisitExpr(B); 3457 return; 3458 } 3459 3460 B->getLHS()->printPretty(OS, Helper, Policy); 3461 3462 switch (B->getOpcode()) { 3463 case BO_LOr: 3464 OS << " || ..."; 3465 return; 3466 case BO_LAnd: 3467 OS << " && ..."; 3468 return; 3469 default: 3470 llvm_unreachable("Invalid logical operator."); 3471 } 3472 } 3473 3474 void VisitExpr(Expr *E) { 3475 E->printPretty(OS, Helper, Policy); 3476 } 3477}; 3478} // end anonymous namespace 3479 3480static void print_elem(raw_ostream &OS, StmtPrinterHelper* Helper, 3481 const CFGElement &E) { 3482 if (const CFGStmt *CS = E.getAs<CFGStmt>()) { 3483 const Stmt *S = CS->getStmt(); 3484 3485 if (Helper) { 3486 3487 // special printing for statement-expressions. 3488 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 3489 const CompoundStmt *Sub = SE->getSubStmt(); 3490 3491 if (Sub->children()) { 3492 OS << "({ ... ; "; 3493 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3494 OS << " })\n"; 3495 return; 3496 } 3497 } 3498 // special printing for comma expressions. 3499 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3500 if (B->getOpcode() == BO_Comma) { 3501 OS << "... , "; 3502 Helper->handledStmt(B->getRHS(),OS); 3503 OS << '\n'; 3504 return; 3505 } 3506 } 3507 } 3508 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3509 3510 if (isa<CXXOperatorCallExpr>(S)) { 3511 OS << " (OperatorCall)"; 3512 } 3513 else if (isa<CXXBindTemporaryExpr>(S)) { 3514 OS << " (BindTemporary)"; 3515 } 3516 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { 3517 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")"; 3518 } 3519 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { 3520 OS << " (" << CE->getStmtClassName() << ", " 3521 << CE->getCastKindName() 3522 << ", " << CE->getType().getAsString() 3523 << ")"; 3524 } 3525 3526 // Expressions need a newline. 3527 if (isa<Expr>(S)) 3528 OS << '\n'; 3529 3530 } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) { 3531 const CXXCtorInitializer *I = IE->getInitializer(); 3532 if (I->isBaseInitializer()) 3533 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3534 else OS << I->getAnyMember()->getName(); 3535 3536 OS << "("; 3537 if (Expr *IE = I->getInit()) 3538 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3539 OS << ")"; 3540 3541 if (I->isBaseInitializer()) 3542 OS << " (Base initializer)\n"; 3543 else OS << " (Member initializer)\n"; 3544 3545 } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){ 3546 const VarDecl *VD = DE->getVarDecl(); 3547 Helper->handleDecl(VD, OS); 3548 3549 const Type* T = VD->getType().getTypePtr(); 3550 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3551 T = RT->getPointeeType().getTypePtr(); 3552 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3553 T = ET; 3554 3555 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3556 OS << " (Implicit destructor)\n"; 3557 3558 } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) { 3559 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 3560 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3561 OS << " (Base object destructor)\n"; 3562 3563 } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) { 3564 const FieldDecl *FD = ME->getFieldDecl(); 3565 3566 const Type *T = FD->getType().getTypePtr(); 3567 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3568 T = ET; 3569 3570 OS << "this->" << FD->getName(); 3571 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3572 OS << " (Member object destructor)\n"; 3573 3574 } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) { 3575 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 3576 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3577 OS << " (Temporary object destructor)\n"; 3578 } 3579} 3580 3581static void print_block(raw_ostream &OS, const CFG* cfg, 3582 const CFGBlock &B, 3583 StmtPrinterHelper* Helper, bool print_edges, 3584 bool ShowColors) { 3585 3586 if (Helper) 3587 Helper->setBlockID(B.getBlockID()); 3588 3589 // Print the header. 3590 if (ShowColors) 3591 OS.changeColor(raw_ostream::YELLOW, true); 3592 3593 OS << "\n [B" << B.getBlockID(); 3594 3595 if (&B == &cfg->getEntry()) 3596 OS << " (ENTRY)]\n"; 3597 else if (&B == &cfg->getExit()) 3598 OS << " (EXIT)]\n"; 3599 else if (&B == cfg->getIndirectGotoBlock()) 3600 OS << " (INDIRECT GOTO DISPATCH)]\n"; 3601 else 3602 OS << "]\n"; 3603 3604 if (ShowColors) 3605 OS.resetColor(); 3606 3607 // Print the label of this block. 3608 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 3609 3610 if (print_edges) 3611 OS << " "; 3612 3613 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 3614 OS << L->getName(); 3615 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 3616 OS << "case "; 3617 C->getLHS()->printPretty(OS, Helper, 3618 PrintingPolicy(Helper->getLangOpts())); 3619 if (C->getRHS()) { 3620 OS << " ... "; 3621 C->getRHS()->printPretty(OS, Helper, 3622 PrintingPolicy(Helper->getLangOpts())); 3623 } 3624 } else if (isa<DefaultStmt>(Label)) 3625 OS << "default"; 3626 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3627 OS << "catch ("; 3628 if (CS->getExceptionDecl()) 3629 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3630 0); 3631 else 3632 OS << "..."; 3633 OS << ")"; 3634 3635 } else 3636 llvm_unreachable("Invalid label statement in CFGBlock."); 3637 3638 OS << ":\n"; 3639 } 3640 3641 // Iterate through the statements in the block and print them. 3642 unsigned j = 1; 3643 3644 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3645 I != E ; ++I, ++j ) { 3646 3647 // Print the statement # in the basic block and the statement itself. 3648 if (print_edges) 3649 OS << " "; 3650 3651 OS << llvm::format("%3d", j) << ": "; 3652 3653 if (Helper) 3654 Helper->setStmtID(j); 3655 3656 print_elem(OS, Helper, *I); 3657 } 3658 3659 // Print the terminator of this block. 3660 if (B.getTerminator()) { 3661 if (ShowColors) 3662 OS.changeColor(raw_ostream::GREEN); 3663 3664 OS << " T: "; 3665 3666 if (Helper) Helper->setBlockID(-1); 3667 3668 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3669 PrintingPolicy(Helper->getLangOpts())); 3670 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3671 OS << '\n'; 3672 3673 if (ShowColors) 3674 OS.resetColor(); 3675 } 3676 3677 if (print_edges) { 3678 // Print the predecessors of this block. 3679 if (!B.pred_empty()) { 3680 const raw_ostream::Colors Color = raw_ostream::BLUE; 3681 if (ShowColors) 3682 OS.changeColor(Color); 3683 OS << " Preds " ; 3684 if (ShowColors) 3685 OS.resetColor(); 3686 OS << '(' << B.pred_size() << "):"; 3687 unsigned i = 0; 3688 3689 if (ShowColors) 3690 OS.changeColor(Color); 3691 3692 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3693 I != E; ++I, ++i) { 3694 3695 if (i == 8 || (i-8) == 0) 3696 OS << "\n "; 3697 3698 OS << " B" << (*I)->getBlockID(); 3699 } 3700 3701 if (ShowColors) 3702 OS.resetColor(); 3703 3704 OS << '\n'; 3705 } 3706 3707 // Print the successors of this block. 3708 if (!B.succ_empty()) { 3709 const raw_ostream::Colors Color = raw_ostream::MAGENTA; 3710 if (ShowColors) 3711 OS.changeColor(Color); 3712 OS << " Succs "; 3713 if (ShowColors) 3714 OS.resetColor(); 3715 OS << '(' << B.succ_size() << "):"; 3716 unsigned i = 0; 3717 3718 if (ShowColors) 3719 OS.changeColor(Color); 3720 3721 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3722 I != E; ++I, ++i) { 3723 3724 if (i == 8 || (i-8) % 10 == 0) 3725 OS << "\n "; 3726 3727 if (*I) 3728 OS << " B" << (*I)->getBlockID(); 3729 else 3730 OS << " NULL"; 3731 } 3732 3733 if (ShowColors) 3734 OS.resetColor(); 3735 OS << '\n'; 3736 } 3737 } 3738} 3739 3740 3741/// dump - A simple pretty printer of a CFG that outputs to stderr. 3742void CFG::dump(const LangOptions &LO, bool ShowColors) const { 3743 print(llvm::errs(), LO, ShowColors); 3744} 3745 3746/// print - A simple pretty printer of a CFG that outputs to an ostream. 3747void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { 3748 StmtPrinterHelper Helper(this, LO); 3749 3750 // Print the entry block. 3751 print_block(OS, this, getEntry(), &Helper, true, ShowColors); 3752 3753 // Iterate through the CFGBlocks and print them one by one. 3754 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3755 // Skip the entry block, because we already printed it. 3756 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3757 continue; 3758 3759 print_block(OS, this, **I, &Helper, true, ShowColors); 3760 } 3761 3762 // Print the exit block. 3763 print_block(OS, this, getExit(), &Helper, true, ShowColors); 3764 OS << '\n'; 3765 OS.flush(); 3766} 3767 3768/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3769void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, 3770 bool ShowColors) const { 3771 print(llvm::errs(), cfg, LO, ShowColors); 3772} 3773 3774/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3775/// Generally this will only be called from CFG::print. 3776void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 3777 const LangOptions &LO, bool ShowColors) const { 3778 StmtPrinterHelper Helper(cfg, LO); 3779 print_block(OS, cfg, *this, &Helper, true, ShowColors); 3780 OS << '\n'; 3781} 3782 3783/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3784void CFGBlock::printTerminator(raw_ostream &OS, 3785 const LangOptions &LO) const { 3786 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3787 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3788} 3789 3790Stmt *CFGBlock::getTerminatorCondition() { 3791 Stmt *Terminator = this->Terminator; 3792 if (!Terminator) 3793 return NULL; 3794 3795 Expr *E = NULL; 3796 3797 switch (Terminator->getStmtClass()) { 3798 default: 3799 break; 3800 3801 case Stmt::ForStmtClass: 3802 E = cast<ForStmt>(Terminator)->getCond(); 3803 break; 3804 3805 case Stmt::WhileStmtClass: 3806 E = cast<WhileStmt>(Terminator)->getCond(); 3807 break; 3808 3809 case Stmt::DoStmtClass: 3810 E = cast<DoStmt>(Terminator)->getCond(); 3811 break; 3812 3813 case Stmt::IfStmtClass: 3814 E = cast<IfStmt>(Terminator)->getCond(); 3815 break; 3816 3817 case Stmt::ChooseExprClass: 3818 E = cast<ChooseExpr>(Terminator)->getCond(); 3819 break; 3820 3821 case Stmt::IndirectGotoStmtClass: 3822 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3823 break; 3824 3825 case Stmt::SwitchStmtClass: 3826 E = cast<SwitchStmt>(Terminator)->getCond(); 3827 break; 3828 3829 case Stmt::BinaryConditionalOperatorClass: 3830 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 3831 break; 3832 3833 case Stmt::ConditionalOperatorClass: 3834 E = cast<ConditionalOperator>(Terminator)->getCond(); 3835 break; 3836 3837 case Stmt::BinaryOperatorClass: // '&&' and '||' 3838 E = cast<BinaryOperator>(Terminator)->getLHS(); 3839 break; 3840 3841 case Stmt::ObjCForCollectionStmtClass: 3842 return Terminator; 3843 } 3844 3845 return E ? E->IgnoreParens() : NULL; 3846} 3847 3848//===----------------------------------------------------------------------===// 3849// CFG Graphviz Visualization 3850//===----------------------------------------------------------------------===// 3851 3852 3853#ifndef NDEBUG 3854static StmtPrinterHelper* GraphHelper; 3855#endif 3856 3857void CFG::viewCFG(const LangOptions &LO) const { 3858#ifndef NDEBUG 3859 StmtPrinterHelper H(this, LO); 3860 GraphHelper = &H; 3861 llvm::ViewGraph(this,"CFG"); 3862 GraphHelper = NULL; 3863#endif 3864} 3865 3866namespace llvm { 3867template<> 3868struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3869 3870 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3871 3872 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 3873 3874#ifndef NDEBUG 3875 std::string OutSStr; 3876 llvm::raw_string_ostream Out(OutSStr); 3877 print_block(Out,Graph, *Node, GraphHelper, false, false); 3878 std::string& OutStr = Out.str(); 3879 3880 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3881 3882 // Process string output to make it nicer... 3883 for (unsigned i = 0; i != OutStr.length(); ++i) 3884 if (OutStr[i] == '\n') { // Left justify 3885 OutStr[i] = '\\'; 3886 OutStr.insert(OutStr.begin()+i+1, 'l'); 3887 } 3888 3889 return OutStr; 3890#else 3891 return ""; 3892#endif 3893 } 3894}; 3895} // end namespace llvm 3896