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