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