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