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