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