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