1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the CFG and CFGBuilder classes for representing and 10 // building Control-Flow Graphs (CFGs) from ASTs. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Analysis/CFG.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclGroup.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/OperationKinds.h" 24 #include "clang/AST/PrettyPrinter.h" 25 #include "clang/AST/Stmt.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/AST/StmtObjC.h" 28 #include "clang/AST/StmtVisitor.h" 29 #include "clang/AST/Type.h" 30 #include "clang/Analysis/ConstructionContext.h" 31 #include "clang/Analysis/Support/BumpVector.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/ExceptionSpecificationType.h" 34 #include "clang/Basic/JsonSupport.h" 35 #include "clang/Basic/LLVM.h" 36 #include "clang/Basic/LangOptions.h" 37 #include "clang/Basic/SourceLocation.h" 38 #include "clang/Basic/Specifiers.h" 39 #include "llvm/ADT/APInt.h" 40 #include "llvm/ADT/APSInt.h" 41 #include "llvm/ADT/ArrayRef.h" 42 #include "llvm/ADT/DenseMap.h" 43 #include "llvm/ADT/Optional.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/SetVector.h" 46 #include "llvm/ADT/SmallPtrSet.h" 47 #include "llvm/ADT/SmallVector.h" 48 #include "llvm/Support/Allocator.h" 49 #include "llvm/Support/Casting.h" 50 #include "llvm/Support/Compiler.h" 51 #include "llvm/Support/DOTGraphTraits.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/Format.h" 54 #include "llvm/Support/GraphWriter.h" 55 #include "llvm/Support/SaveAndRestore.h" 56 #include "llvm/Support/raw_ostream.h" 57 #include <cassert> 58 #include <memory> 59 #include <string> 60 #include <tuple> 61 #include <utility> 62 #include <vector> 63 64 using namespace clang; 65 66 static SourceLocation GetEndLoc(Decl *D) { 67 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 68 if (Expr *Ex = VD->getInit()) 69 return Ex->getSourceRange().getEnd(); 70 return D->getLocation(); 71 } 72 73 /// Returns true on constant values based around a single IntegerLiteral. 74 /// Allow for use of parentheses, integer casts, and negative signs. 75 static bool IsIntegerLiteralConstantExpr(const Expr *E) { 76 // Allow parentheses 77 E = E->IgnoreParens(); 78 79 // Allow conversions to different integer kind. 80 if (const auto *CE = dyn_cast<CastExpr>(E)) { 81 if (CE->getCastKind() != CK_IntegralCast) 82 return false; 83 E = CE->getSubExpr(); 84 } 85 86 // Allow negative numbers. 87 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 88 if (UO->getOpcode() != UO_Minus) 89 return false; 90 E = UO->getSubExpr(); 91 } 92 93 return isa<IntegerLiteral>(E); 94 } 95 96 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral 97 /// constant expression or EnumConstantDecl from the given Expr. If it fails, 98 /// returns nullptr. 99 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) { 100 E = E->IgnoreParens(); 101 if (IsIntegerLiteralConstantExpr(E)) 102 return E; 103 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 104 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr; 105 return nullptr; 106 } 107 108 /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if 109 /// NumExpr is an integer literal or an enum constant. 110 /// 111 /// If this fails, at least one of the returned DeclRefExpr or Expr will be 112 /// null. 113 static std::tuple<const Expr *, BinaryOperatorKind, const Expr *> 114 tryNormalizeBinaryOperator(const BinaryOperator *B) { 115 BinaryOperatorKind Op = B->getOpcode(); 116 117 const Expr *MaybeDecl = B->getLHS(); 118 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS()); 119 // Expr looked like `0 == Foo` instead of `Foo == 0` 120 if (Constant == nullptr) { 121 // Flip the operator 122 if (Op == BO_GT) 123 Op = BO_LT; 124 else if (Op == BO_GE) 125 Op = BO_LE; 126 else if (Op == BO_LT) 127 Op = BO_GT; 128 else if (Op == BO_LE) 129 Op = BO_GE; 130 131 MaybeDecl = B->getRHS(); 132 Constant = tryTransformToIntOrEnumConstant(B->getLHS()); 133 } 134 135 return std::make_tuple(MaybeDecl, Op, Constant); 136 } 137 138 /// For an expression `x == Foo && x == Bar`, this determines whether the 139 /// `Foo` and `Bar` are either of the same enumeration type, or both integer 140 /// literals. 141 /// 142 /// It's an error to pass this arguments that are not either IntegerLiterals 143 /// or DeclRefExprs (that have decls of type EnumConstantDecl) 144 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) { 145 // User intent isn't clear if they're mixing int literals with enum 146 // constants. 147 if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2)) 148 return false; 149 150 // Integer literal comparisons, regardless of literal type, are acceptable. 151 if (!isa<DeclRefExpr>(E1)) 152 return true; 153 154 // IntegerLiterals are handled above and only EnumConstantDecls are expected 155 // beyond this point 156 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2)); 157 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl(); 158 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl(); 159 160 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2)); 161 const DeclContext *DC1 = Decl1->getDeclContext(); 162 const DeclContext *DC2 = Decl2->getDeclContext(); 163 164 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2)); 165 return DC1 == DC2; 166 } 167 168 namespace { 169 170 class CFGBuilder; 171 172 /// The CFG builder uses a recursive algorithm to build the CFG. When 173 /// we process an expression, sometimes we know that we must add the 174 /// subexpressions as block-level expressions. For example: 175 /// 176 /// exp1 || exp2 177 /// 178 /// When processing the '||' expression, we know that exp1 and exp2 179 /// need to be added as block-level expressions, even though they 180 /// might not normally need to be. AddStmtChoice records this 181 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then 182 /// the builder has an option not to add a subexpression as a 183 /// block-level expression. 184 class AddStmtChoice { 185 public: 186 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; 187 188 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} 189 190 bool alwaysAdd(CFGBuilder &builder, 191 const Stmt *stmt) const; 192 193 /// Return a copy of this object, except with the 'always-add' bit 194 /// set as specified. 195 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { 196 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); 197 } 198 199 private: 200 Kind kind; 201 }; 202 203 /// LocalScope - Node in tree of local scopes created for C++ implicit 204 /// destructor calls generation. It contains list of automatic variables 205 /// declared in the scope and link to position in previous scope this scope 206 /// began in. 207 /// 208 /// The process of creating local scopes is as follows: 209 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 210 /// - Before processing statements in scope (e.g. CompoundStmt) create 211 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope 212 /// and set CFGBuilder::ScopePos to the end of new scope, 213 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 214 /// at this VarDecl, 215 /// - For every normal (without jump) end of scope add to CFGBlock destructors 216 /// for objects in the current scope, 217 /// - For every jump add to CFGBlock destructors for objects 218 /// between CFGBuilder::ScopePos and local scope position saved for jump 219 /// target. Thanks to C++ restrictions on goto jumps we can be sure that 220 /// jump target position will be on the path to root from CFGBuilder::ScopePos 221 /// (adding any variable that doesn't need constructor to be called to 222 /// LocalScope can break this assumption), 223 /// 224 class LocalScope { 225 public: 226 using AutomaticVarsTy = BumpVector<VarDecl *>; 227 228 /// const_iterator - Iterates local scope backwards and jumps to previous 229 /// scope on reaching the beginning of currently iterated scope. 230 class const_iterator { 231 const LocalScope* Scope = nullptr; 232 233 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 234 /// Invalid iterator (with null Scope) has VarIter equal to 0. 235 unsigned VarIter = 0; 236 237 public: 238 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 239 /// Incrementing invalid iterator is allowed and will result in invalid 240 /// iterator. 241 const_iterator() = default; 242 243 /// Create valid iterator. In case when S.Prev is an invalid iterator and 244 /// I is equal to 0, this will create invalid iterator. 245 const_iterator(const LocalScope& S, unsigned I) 246 : Scope(&S), VarIter(I) { 247 // Iterator to "end" of scope is not allowed. Handle it by going up 248 // in scopes tree possibly up to invalid iterator in the root. 249 if (VarIter == 0 && Scope) 250 *this = Scope->Prev; 251 } 252 253 VarDecl *const* operator->() const { 254 assert(Scope && "Dereferencing invalid iterator is not allowed"); 255 assert(VarIter != 0 && "Iterator has invalid value of VarIter member"); 256 return &Scope->Vars[VarIter - 1]; 257 } 258 259 const VarDecl *getFirstVarInScope() const { 260 assert(Scope && "Dereferencing invalid iterator is not allowed"); 261 assert(VarIter != 0 && "Iterator has invalid value of VarIter member"); 262 return Scope->Vars[0]; 263 } 264 265 VarDecl *operator*() const { 266 return *this->operator->(); 267 } 268 269 const_iterator &operator++() { 270 if (!Scope) 271 return *this; 272 273 assert(VarIter != 0 && "Iterator has invalid value of VarIter member"); 274 --VarIter; 275 if (VarIter == 0) 276 *this = Scope->Prev; 277 return *this; 278 } 279 const_iterator operator++(int) { 280 const_iterator P = *this; 281 ++*this; 282 return P; 283 } 284 285 bool operator==(const const_iterator &rhs) const { 286 return Scope == rhs.Scope && VarIter == rhs.VarIter; 287 } 288 bool operator!=(const const_iterator &rhs) const { 289 return !(*this == rhs); 290 } 291 292 explicit operator bool() const { 293 return *this != const_iterator(); 294 } 295 296 int distance(const_iterator L); 297 const_iterator shared_parent(const_iterator L); 298 bool pointsToFirstDeclaredVar() { return VarIter == 1; } 299 }; 300 301 private: 302 BumpVectorContext ctx; 303 304 /// Automatic variables in order of declaration. 305 AutomaticVarsTy Vars; 306 307 /// Iterator to variable in previous scope that was declared just before 308 /// begin of this scope. 309 const_iterator Prev; 310 311 public: 312 /// Constructs empty scope linked to previous scope in specified place. 313 LocalScope(BumpVectorContext ctx, const_iterator P) 314 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {} 315 316 /// Begin of scope in direction of CFG building (backwards). 317 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 318 319 void addVar(VarDecl *VD) { 320 Vars.push_back(VD, ctx); 321 } 322 }; 323 324 } // namespace 325 326 /// distance - Calculates distance from this to L. L must be reachable from this 327 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 328 /// number of scopes between this and L. 329 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 330 int D = 0; 331 const_iterator F = *this; 332 while (F.Scope != L.Scope) { 333 assert(F != const_iterator() && 334 "L iterator is not reachable from F iterator."); 335 D += F.VarIter; 336 F = F.Scope->Prev; 337 } 338 D += F.VarIter - L.VarIter; 339 return D; 340 } 341 342 /// Calculates the closest parent of this iterator 343 /// that is in a scope reachable through the parents of L. 344 /// I.e. when using 'goto' from this to L, the lifetime of all variables 345 /// between this and shared_parent(L) end. 346 LocalScope::const_iterator 347 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) { 348 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL; 349 while (true) { 350 ScopesOfL.insert(L.Scope); 351 if (L == const_iterator()) 352 break; 353 L = L.Scope->Prev; 354 } 355 356 const_iterator F = *this; 357 while (true) { 358 if (ScopesOfL.count(F.Scope)) 359 return F; 360 assert(F != const_iterator() && 361 "L iterator is not reachable from F iterator."); 362 F = F.Scope->Prev; 363 } 364 } 365 366 namespace { 367 368 /// Structure for specifying position in CFG during its build process. It 369 /// consists of CFGBlock that specifies position in CFG and 370 /// LocalScope::const_iterator that specifies position in LocalScope graph. 371 struct BlockScopePosPair { 372 CFGBlock *block = nullptr; 373 LocalScope::const_iterator scopePosition; 374 375 BlockScopePosPair() = default; 376 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) 377 : block(b), scopePosition(scopePos) {} 378 }; 379 380 /// TryResult - a class representing a variant over the values 381 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, 382 /// and is used by the CFGBuilder to decide if a branch condition 383 /// can be decided up front during CFG construction. 384 class TryResult { 385 int X = -1; 386 387 public: 388 TryResult() = default; 389 TryResult(bool b) : X(b ? 1 : 0) {} 390 391 bool isTrue() const { return X == 1; } 392 bool isFalse() const { return X == 0; } 393 bool isKnown() const { return X >= 0; } 394 395 void negate() { 396 assert(isKnown()); 397 X ^= 0x1; 398 } 399 }; 400 401 } // namespace 402 403 static TryResult bothKnownTrue(TryResult R1, TryResult R2) { 404 if (!R1.isKnown() || !R2.isKnown()) 405 return TryResult(); 406 return TryResult(R1.isTrue() && R2.isTrue()); 407 } 408 409 namespace { 410 411 class reverse_children { 412 llvm::SmallVector<Stmt *, 12> childrenBuf; 413 ArrayRef<Stmt *> children; 414 415 public: 416 reverse_children(Stmt *S); 417 418 using iterator = ArrayRef<Stmt *>::reverse_iterator; 419 420 iterator begin() const { return children.rbegin(); } 421 iterator end() const { return children.rend(); } 422 }; 423 424 } // namespace 425 426 reverse_children::reverse_children(Stmt *S) { 427 if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 428 children = CE->getRawSubExprs(); 429 return; 430 } 431 switch (S->getStmtClass()) { 432 // Note: Fill in this switch with more cases we want to optimize. 433 case Stmt::InitListExprClass: { 434 InitListExpr *IE = cast<InitListExpr>(S); 435 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()), 436 IE->getNumInits()); 437 return; 438 } 439 default: 440 break; 441 } 442 443 // Default case for all other statements. 444 for (Stmt *SubStmt : S->children()) 445 childrenBuf.push_back(SubStmt); 446 447 // This needs to be done *after* childrenBuf has been populated. 448 children = childrenBuf; 449 } 450 451 namespace { 452 453 /// CFGBuilder - This class implements CFG construction from an AST. 454 /// The builder is stateful: an instance of the builder should be used to only 455 /// construct a single CFG. 456 /// 457 /// Example usage: 458 /// 459 /// CFGBuilder builder; 460 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1); 461 /// 462 /// CFG construction is done via a recursive walk of an AST. We actually parse 463 /// the AST in reverse order so that the successor of a basic block is 464 /// constructed prior to its predecessor. This allows us to nicely capture 465 /// implicit fall-throughs without extra basic blocks. 466 class CFGBuilder { 467 using JumpTarget = BlockScopePosPair; 468 using JumpSource = BlockScopePosPair; 469 470 ASTContext *Context; 471 std::unique_ptr<CFG> cfg; 472 473 // Current block. 474 CFGBlock *Block = nullptr; 475 476 // Block after the current block. 477 CFGBlock *Succ = nullptr; 478 479 JumpTarget ContinueJumpTarget; 480 JumpTarget BreakJumpTarget; 481 JumpTarget SEHLeaveJumpTarget; 482 CFGBlock *SwitchTerminatedBlock = nullptr; 483 CFGBlock *DefaultCaseBlock = nullptr; 484 485 // This can point to either a C++ try, an Objective-C @try, or an SEH __try. 486 // try and @try can be mixed and generally work the same. 487 // The frontend forbids mixing SEH __try with either try or @try. 488 // So having one for all three is enough. 489 CFGBlock *TryTerminatedBlock = nullptr; 490 491 // Current position in local scope. 492 LocalScope::const_iterator ScopePos; 493 494 // LabelMap records the mapping from Label expressions to their jump targets. 495 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>; 496 LabelMapTy LabelMap; 497 498 // A list of blocks that end with a "goto" that must be backpatched to their 499 // resolved targets upon completion of CFG construction. 500 using BackpatchBlocksTy = std::vector<JumpSource>; 501 BackpatchBlocksTy BackpatchBlocks; 502 503 // A list of labels whose address has been taken (for indirect gotos). 504 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>; 505 LabelSetTy AddressTakenLabels; 506 507 // Information about the currently visited C++ object construction site. 508 // This is set in the construction trigger and read when the constructor 509 // or a function that returns an object by value is being visited. 510 llvm::DenseMap<Expr *, const ConstructionContextLayer *> 511 ConstructionContextMap; 512 513 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>; 514 DeclsWithEndedScopeSetTy DeclsWithEndedScope; 515 516 bool badCFG = false; 517 const CFG::BuildOptions &BuildOpts; 518 519 // State to track for building switch statements. 520 bool switchExclusivelyCovered = false; 521 Expr::EvalResult *switchCond = nullptr; 522 523 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr; 524 const Stmt *lastLookup = nullptr; 525 526 // Caches boolean evaluations of expressions to avoid multiple re-evaluations 527 // during construction of branches for chained logical operators. 528 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>; 529 CachedBoolEvalsTy CachedBoolEvals; 530 531 public: 532 explicit CFGBuilder(ASTContext *astContext, 533 const CFG::BuildOptions &buildOpts) 534 : Context(astContext), cfg(new CFG()), // crew a new CFG 535 ConstructionContextMap(), BuildOpts(buildOpts) {} 536 537 538 // buildCFG - Used by external clients to construct the CFG. 539 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement); 540 541 bool alwaysAdd(const Stmt *stmt); 542 543 private: 544 // Visitors to walk an AST and construct the CFG. 545 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc); 546 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 547 CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc); 548 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 549 CFGBlock *VisitBreakStmt(BreakStmt *B); 550 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 551 CFGBlock *VisitCaseStmt(CaseStmt *C); 552 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 553 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed); 554 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 555 AddStmtChoice asc); 556 CFGBlock *VisitContinueStmt(ContinueStmt *C); 557 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 558 AddStmtChoice asc); 559 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 560 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 561 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc); 562 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc); 563 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 564 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 565 AddStmtChoice asc); 566 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 567 AddStmtChoice asc); 568 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 569 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 570 CFGBlock *VisitDeclStmt(DeclStmt *DS); 571 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 572 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 573 CFGBlock *VisitDoStmt(DoStmt *D); 574 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, 575 AddStmtChoice asc, bool ExternallyDestructed); 576 CFGBlock *VisitForStmt(ForStmt *F); 577 CFGBlock *VisitGotoStmt(GotoStmt *G); 578 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc); 579 CFGBlock *VisitIfStmt(IfStmt *I); 580 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 581 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc); 582 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 583 CFGBlock *VisitLabelStmt(LabelStmt *L); 584 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc); 585 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc); 586 CFGBlock *VisitLogicalOperator(BinaryOperator *B); 587 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B, 588 Stmt *Term, 589 CFGBlock *TrueBlock, 590 CFGBlock *FalseBlock); 591 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE, 592 AddStmtChoice asc); 593 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 594 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 595 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 596 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 597 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 598 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 599 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 600 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc); 601 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); 602 CFGBlock *VisitReturnStmt(Stmt *S); 603 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S); 604 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S); 605 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S); 606 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S); 607 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 608 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 609 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 610 AddStmtChoice asc); 611 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 612 CFGBlock *VisitWhileStmt(WhileStmt *W); 613 614 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd, 615 bool ExternallyDestructed = false); 616 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 617 CFGBlock *VisitChildren(Stmt *S); 618 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc); 619 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D, 620 AddStmtChoice asc); 621 622 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD, 623 const Stmt *S) { 624 if (ScopePos && (VD == ScopePos.getFirstVarInScope())) 625 appendScopeBegin(B, VD, S); 626 } 627 628 /// When creating the CFG for temporary destructors, we want to mirror the 629 /// branch structure of the corresponding constructor calls. 630 /// Thus, while visiting a statement for temporary destructors, we keep a 631 /// context to keep track of the following information: 632 /// - whether a subexpression is executed unconditionally 633 /// - if a subexpression is executed conditionally, the first 634 /// CXXBindTemporaryExpr we encounter in that subexpression (which 635 /// corresponds to the last temporary destructor we have to call for this 636 /// subexpression) and the CFG block at that point (which will become the 637 /// successor block when inserting the decision point). 638 /// 639 /// That way, we can build the branch structure for temporary destructors as 640 /// follows: 641 /// 1. If a subexpression is executed unconditionally, we add the temporary 642 /// destructor calls to the current block. 643 /// 2. If a subexpression is executed conditionally, when we encounter a 644 /// CXXBindTemporaryExpr: 645 /// a) If it is the first temporary destructor call in the subexpression, 646 /// we remember the CXXBindTemporaryExpr and the current block in the 647 /// TempDtorContext; we start a new block, and insert the temporary 648 /// destructor call. 649 /// b) Otherwise, add the temporary destructor call to the current block. 650 /// 3. When we finished visiting a conditionally executed subexpression, 651 /// and we found at least one temporary constructor during the visitation 652 /// (2.a has executed), we insert a decision block that uses the 653 /// CXXBindTemporaryExpr as terminator, and branches to the current block 654 /// if the CXXBindTemporaryExpr was marked executed, and otherwise 655 /// branches to the stored successor. 656 struct TempDtorContext { 657 TempDtorContext() = default; 658 TempDtorContext(TryResult KnownExecuted) 659 : IsConditional(true), KnownExecuted(KnownExecuted) {} 660 661 /// Returns whether we need to start a new branch for a temporary destructor 662 /// call. This is the case when the temporary destructor is 663 /// conditionally executed, and it is the first one we encounter while 664 /// visiting a subexpression - other temporary destructors at the same level 665 /// will be added to the same block and are executed under the same 666 /// condition. 667 bool needsTempDtorBranch() const { 668 return IsConditional && !TerminatorExpr; 669 } 670 671 /// Remember the successor S of a temporary destructor decision branch for 672 /// the corresponding CXXBindTemporaryExpr E. 673 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) { 674 Succ = S; 675 TerminatorExpr = E; 676 } 677 678 const bool IsConditional = false; 679 const TryResult KnownExecuted = true; 680 CFGBlock *Succ = nullptr; 681 CXXBindTemporaryExpr *TerminatorExpr = nullptr; 682 }; 683 684 // Visitors to walk an AST and generate destructors of temporaries in 685 // full expression. 686 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed, 687 TempDtorContext &Context); 688 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed, 689 TempDtorContext &Context); 690 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E, 691 bool ExternallyDestructed, 692 TempDtorContext &Context); 693 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors( 694 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context); 695 CFGBlock *VisitConditionalOperatorForTemporaryDtors( 696 AbstractConditionalOperator *E, bool ExternallyDestructed, 697 TempDtorContext &Context); 698 void InsertTempDtorDecisionBlock(const TempDtorContext &Context, 699 CFGBlock *FalseSucc = nullptr); 700 701 // NYS == Not Yet Supported 702 CFGBlock *NYS() { 703 badCFG = true; 704 return Block; 705 } 706 707 // Remember to apply the construction context based on the current \p Layer 708 // when constructing the CFG element for \p CE. 709 void consumeConstructionContext(const ConstructionContextLayer *Layer, 710 Expr *E); 711 712 // Scan \p Child statement to find constructors in it, while keeping in mind 713 // that its parent statement is providing a partial construction context 714 // described by \p Layer. If a constructor is found, it would be assigned 715 // the context based on the layer. If an additional construction context layer 716 // is found, the function recurses into that. 717 void findConstructionContexts(const ConstructionContextLayer *Layer, 718 Stmt *Child); 719 720 // Scan all arguments of a call expression for a construction context. 721 // These sorts of call expressions don't have a common superclass, 722 // hence strict duck-typing. 723 template <typename CallLikeExpr, 724 typename = std::enable_if_t< 725 std::is_base_of<CallExpr, CallLikeExpr>::value || 726 std::is_base_of<CXXConstructExpr, CallLikeExpr>::value || 727 std::is_base_of<ObjCMessageExpr, CallLikeExpr>::value>> 728 void findConstructionContextsForArguments(CallLikeExpr *E) { 729 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 730 Expr *Arg = E->getArg(i); 731 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue()) 732 findConstructionContexts( 733 ConstructionContextLayer::create(cfg->getBumpVectorContext(), 734 ConstructionContextItem(E, i)), 735 Arg); 736 } 737 } 738 739 // Unset the construction context after consuming it. This is done immediately 740 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so 741 // there's no need to do this manually in every Visit... function. 742 void cleanupConstructionContext(Expr *E); 743 744 void autoCreateBlock() { if (!Block) Block = createBlock(); } 745 CFGBlock *createBlock(bool add_successor = true); 746 CFGBlock *createNoReturnBlock(); 747 748 CFGBlock *addStmt(Stmt *S) { 749 return Visit(S, AddStmtChoice::AlwaysAdd); 750 } 751 752 CFGBlock *addInitializer(CXXCtorInitializer *I); 753 void addLoopExit(const Stmt *LoopStmt); 754 void addAutomaticObjDtors(LocalScope::const_iterator B, 755 LocalScope::const_iterator E, Stmt *S); 756 void addLifetimeEnds(LocalScope::const_iterator B, 757 LocalScope::const_iterator E, Stmt *S); 758 void addAutomaticObjHandling(LocalScope::const_iterator B, 759 LocalScope::const_iterator E, Stmt *S); 760 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); 761 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E, 762 Stmt *S); 763 764 void getDeclsWithEndedScope(LocalScope::const_iterator B, 765 LocalScope::const_iterator E, Stmt *S); 766 767 // Local scopes creation. 768 LocalScope* createOrReuseLocalScope(LocalScope* Scope); 769 770 void addLocalScopeForStmt(Stmt *S); 771 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, 772 LocalScope* Scope = nullptr); 773 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr); 774 775 void addLocalScopeAndDtors(Stmt *S); 776 777 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) { 778 if (!BuildOpts.AddRichCXXConstructors) 779 return nullptr; 780 781 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E); 782 if (!Layer) 783 return nullptr; 784 785 cleanupConstructionContext(E); 786 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(), 787 Layer); 788 } 789 790 // Interface to CFGBlock - adding CFGElements. 791 792 void appendStmt(CFGBlock *B, const Stmt *S) { 793 if (alwaysAdd(S) && cachedEntry) 794 cachedEntry->second = B; 795 796 // All block-level expressions should have already been IgnoreParens()ed. 797 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); 798 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); 799 } 800 801 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) { 802 if (const ConstructionContext *CC = 803 retrieveAndCleanupConstructionContext(CE)) { 804 B->appendConstructor(CE, CC, cfg->getBumpVectorContext()); 805 return; 806 } 807 808 // No valid construction context found. Fall back to statement. 809 B->appendStmt(CE, cfg->getBumpVectorContext()); 810 } 811 812 void appendCall(CFGBlock *B, CallExpr *CE) { 813 if (alwaysAdd(CE) && cachedEntry) 814 cachedEntry->second = B; 815 816 if (const ConstructionContext *CC = 817 retrieveAndCleanupConstructionContext(CE)) { 818 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext()); 819 return; 820 } 821 822 // No valid construction context found. Fall back to statement. 823 B->appendStmt(CE, cfg->getBumpVectorContext()); 824 } 825 826 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { 827 B->appendInitializer(I, cfg->getBumpVectorContext()); 828 } 829 830 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) { 831 B->appendNewAllocator(NE, cfg->getBumpVectorContext()); 832 } 833 834 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { 835 B->appendBaseDtor(BS, cfg->getBumpVectorContext()); 836 } 837 838 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { 839 B->appendMemberDtor(FD, cfg->getBumpVectorContext()); 840 } 841 842 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) { 843 if (alwaysAdd(ME) && cachedEntry) 844 cachedEntry->second = B; 845 846 if (const ConstructionContext *CC = 847 retrieveAndCleanupConstructionContext(ME)) { 848 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext()); 849 return; 850 } 851 852 B->appendStmt(const_cast<ObjCMessageExpr *>(ME), 853 cfg->getBumpVectorContext()); 854 } 855 856 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { 857 B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); 858 } 859 860 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) { 861 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext()); 862 } 863 864 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) { 865 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext()); 866 } 867 868 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) { 869 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext()); 870 } 871 872 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) { 873 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext()); 874 } 875 876 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 877 LocalScope::const_iterator B, LocalScope::const_iterator E); 878 879 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk, 880 LocalScope::const_iterator B, 881 LocalScope::const_iterator E); 882 883 const VarDecl * 884 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk, 885 LocalScope::const_iterator B, 886 LocalScope::const_iterator E); 887 888 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) { 889 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable), 890 cfg->getBumpVectorContext()); 891 } 892 893 /// Add a reachable successor to a block, with the alternate variant that is 894 /// unreachable. 895 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) { 896 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock), 897 cfg->getBumpVectorContext()); 898 } 899 900 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) { 901 if (BuildOpts.AddScopes) 902 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext()); 903 } 904 905 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) { 906 if (BuildOpts.AddScopes) 907 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext()); 908 } 909 910 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) { 911 if (BuildOpts.AddScopes) 912 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext()); 913 } 914 915 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) { 916 if (BuildOpts.AddScopes) 917 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext()); 918 } 919 920 /// Find a relational comparison with an expression evaluating to a 921 /// boolean and a constant other than 0 and 1. 922 /// e.g. if ((x < y) == 10) 923 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) { 924 const Expr *LHSExpr = B->getLHS()->IgnoreParens(); 925 const Expr *RHSExpr = B->getRHS()->IgnoreParens(); 926 927 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); 928 const Expr *BoolExpr = RHSExpr; 929 bool IntFirst = true; 930 if (!IntLiteral) { 931 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); 932 BoolExpr = LHSExpr; 933 IntFirst = false; 934 } 935 936 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue()) 937 return TryResult(); 938 939 llvm::APInt IntValue = IntLiteral->getValue(); 940 if ((IntValue == 1) || (IntValue == 0)) 941 return TryResult(); 942 943 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() || 944 !IntValue.isNegative(); 945 946 BinaryOperatorKind Bok = B->getOpcode(); 947 if (Bok == BO_GT || Bok == BO_GE) { 948 // Always true for 10 > bool and bool > -1 949 // Always false for -1 > bool and bool > 10 950 return TryResult(IntFirst == IntLarger); 951 } else { 952 // Always true for -1 < bool and bool < 10 953 // Always false for 10 < bool and bool < -1 954 return TryResult(IntFirst != IntLarger); 955 } 956 } 957 958 /// Find an incorrect equality comparison. Either with an expression 959 /// evaluating to a boolean and a constant other than 0 and 1. 960 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to 961 /// true/false e.q. (x & 8) == 4. 962 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) { 963 const Expr *LHSExpr = B->getLHS()->IgnoreParens(); 964 const Expr *RHSExpr = B->getRHS()->IgnoreParens(); 965 966 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr); 967 const Expr *BoolExpr = RHSExpr; 968 969 if (!IntLiteral) { 970 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr); 971 BoolExpr = LHSExpr; 972 } 973 974 if (!IntLiteral) 975 return TryResult(); 976 977 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr); 978 if (BitOp && (BitOp->getOpcode() == BO_And || 979 BitOp->getOpcode() == BO_Or)) { 980 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens(); 981 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens(); 982 983 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2); 984 985 if (!IntLiteral2) 986 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2); 987 988 if (!IntLiteral2) 989 return TryResult(); 990 991 llvm::APInt L1 = IntLiteral->getValue(); 992 llvm::APInt L2 = IntLiteral2->getValue(); 993 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) || 994 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) { 995 if (BuildOpts.Observer) 996 BuildOpts.Observer->compareBitwiseEquality(B, 997 B->getOpcode() != BO_EQ); 998 TryResult(B->getOpcode() != BO_EQ); 999 } 1000 } else if (BoolExpr->isKnownToHaveBooleanValue()) { 1001 llvm::APInt IntValue = IntLiteral->getValue(); 1002 if ((IntValue == 1) || (IntValue == 0)) { 1003 return TryResult(); 1004 } 1005 return TryResult(B->getOpcode() != BO_EQ); 1006 } 1007 1008 return TryResult(); 1009 } 1010 1011 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation, 1012 const llvm::APSInt &Value1, 1013 const llvm::APSInt &Value2) { 1014 assert(Value1.isSigned() == Value2.isSigned()); 1015 switch (Relation) { 1016 default: 1017 return TryResult(); 1018 case BO_EQ: 1019 return TryResult(Value1 == Value2); 1020 case BO_NE: 1021 return TryResult(Value1 != Value2); 1022 case BO_LT: 1023 return TryResult(Value1 < Value2); 1024 case BO_LE: 1025 return TryResult(Value1 <= Value2); 1026 case BO_GT: 1027 return TryResult(Value1 > Value2); 1028 case BO_GE: 1029 return TryResult(Value1 >= Value2); 1030 } 1031 } 1032 1033 /// Find a pair of comparison expressions with or without parentheses 1034 /// with a shared variable and constants and a logical operator between them 1035 /// that always evaluates to either true or false. 1036 /// e.g. if (x != 3 || x != 4) 1037 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) { 1038 assert(B->isLogicalOp()); 1039 const BinaryOperator *LHS = 1040 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens()); 1041 const BinaryOperator *RHS = 1042 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens()); 1043 if (!LHS || !RHS) 1044 return {}; 1045 1046 if (!LHS->isComparisonOp() || !RHS->isComparisonOp()) 1047 return {}; 1048 1049 const Expr *DeclExpr1; 1050 const Expr *NumExpr1; 1051 BinaryOperatorKind BO1; 1052 std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS); 1053 1054 if (!DeclExpr1 || !NumExpr1) 1055 return {}; 1056 1057 const Expr *DeclExpr2; 1058 const Expr *NumExpr2; 1059 BinaryOperatorKind BO2; 1060 std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS); 1061 1062 if (!DeclExpr2 || !NumExpr2) 1063 return {}; 1064 1065 // Check that it is the same variable on both sides. 1066 if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2)) 1067 return {}; 1068 1069 // Make sure the user's intent is clear (e.g. they're comparing against two 1070 // int literals, or two things from the same enum) 1071 if (!areExprTypesCompatible(NumExpr1, NumExpr2)) 1072 return {}; 1073 1074 Expr::EvalResult L1Result, L2Result; 1075 if (!NumExpr1->EvaluateAsInt(L1Result, *Context) || 1076 !NumExpr2->EvaluateAsInt(L2Result, *Context)) 1077 return {}; 1078 1079 llvm::APSInt L1 = L1Result.Val.getInt(); 1080 llvm::APSInt L2 = L2Result.Val.getInt(); 1081 1082 // Can't compare signed with unsigned or with different bit width. 1083 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth()) 1084 return {}; 1085 1086 // Values that will be used to determine if result of logical 1087 // operator is always true/false 1088 const llvm::APSInt Values[] = { 1089 // Value less than both Value1 and Value2 1090 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()), 1091 // L1 1092 L1, 1093 // Value between Value1 and Value2 1094 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1), 1095 L1.isUnsigned()), 1096 // L2 1097 L2, 1098 // Value greater than both Value1 and Value2 1099 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()), 1100 }; 1101 1102 // Check whether expression is always true/false by evaluating the following 1103 // * variable x is less than the smallest literal. 1104 // * variable x is equal to the smallest literal. 1105 // * Variable x is between smallest and largest literal. 1106 // * Variable x is equal to the largest literal. 1107 // * Variable x is greater than largest literal. 1108 bool AlwaysTrue = true, AlwaysFalse = true; 1109 // Track value of both subexpressions. If either side is always 1110 // true/false, another warning should have already been emitted. 1111 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true; 1112 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true; 1113 for (const llvm::APSInt &Value : Values) { 1114 TryResult Res1, Res2; 1115 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1); 1116 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2); 1117 1118 if (!Res1.isKnown() || !Res2.isKnown()) 1119 return {}; 1120 1121 if (B->getOpcode() == BO_LAnd) { 1122 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue()); 1123 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue()); 1124 } else { 1125 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue()); 1126 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue()); 1127 } 1128 1129 LHSAlwaysTrue &= Res1.isTrue(); 1130 LHSAlwaysFalse &= Res1.isFalse(); 1131 RHSAlwaysTrue &= Res2.isTrue(); 1132 RHSAlwaysFalse &= Res2.isFalse(); 1133 } 1134 1135 if (AlwaysTrue || AlwaysFalse) { 1136 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue && 1137 !RHSAlwaysFalse && BuildOpts.Observer) 1138 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue); 1139 return TryResult(AlwaysTrue); 1140 } 1141 return {}; 1142 } 1143 1144 /// A bitwise-or with a non-zero constant always evaluates to true. 1145 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) { 1146 const Expr *LHSConstant = 1147 tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts()); 1148 const Expr *RHSConstant = 1149 tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts()); 1150 1151 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant)) 1152 return {}; 1153 1154 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant; 1155 1156 Expr::EvalResult Result; 1157 if (!Constant->EvaluateAsInt(Result, *Context)) 1158 return {}; 1159 1160 if (Result.Val.getInt() == 0) 1161 return {}; 1162 1163 if (BuildOpts.Observer) 1164 BuildOpts.Observer->compareBitwiseOr(B); 1165 1166 return TryResult(true); 1167 } 1168 1169 /// Try and evaluate an expression to an integer constant. 1170 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { 1171 if (!BuildOpts.PruneTriviallyFalseEdges) 1172 return false; 1173 return !S->isTypeDependent() && 1174 !S->isValueDependent() && 1175 S->EvaluateAsRValue(outResult, *Context); 1176 } 1177 1178 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 1179 /// if we can evaluate to a known value, otherwise return -1. 1180 TryResult tryEvaluateBool(Expr *S) { 1181 if (!BuildOpts.PruneTriviallyFalseEdges || 1182 S->isTypeDependent() || S->isValueDependent()) 1183 return {}; 1184 1185 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) { 1186 if (Bop->isLogicalOp() || Bop->isEqualityOp()) { 1187 // Check the cache first. 1188 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S); 1189 if (I != CachedBoolEvals.end()) 1190 return I->second; // already in map; 1191 1192 // Retrieve result at first, or the map might be updated. 1193 TryResult Result = evaluateAsBooleanConditionNoCache(S); 1194 CachedBoolEvals[S] = Result; // update or insert 1195 return Result; 1196 } 1197 else { 1198 switch (Bop->getOpcode()) { 1199 default: break; 1200 // For 'x & 0' and 'x * 0', we can determine that 1201 // the value is always false. 1202 case BO_Mul: 1203 case BO_And: { 1204 // If either operand is zero, we know the value 1205 // must be false. 1206 Expr::EvalResult LHSResult; 1207 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) { 1208 llvm::APSInt IntVal = LHSResult.Val.getInt(); 1209 if (!IntVal.getBoolValue()) { 1210 return TryResult(false); 1211 } 1212 } 1213 Expr::EvalResult RHSResult; 1214 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) { 1215 llvm::APSInt IntVal = RHSResult.Val.getInt(); 1216 if (!IntVal.getBoolValue()) { 1217 return TryResult(false); 1218 } 1219 } 1220 } 1221 break; 1222 } 1223 } 1224 } 1225 1226 return evaluateAsBooleanConditionNoCache(S); 1227 } 1228 1229 /// Evaluate as boolean \param E without using the cache. 1230 TryResult evaluateAsBooleanConditionNoCache(Expr *E) { 1231 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) { 1232 if (Bop->isLogicalOp()) { 1233 TryResult LHS = tryEvaluateBool(Bop->getLHS()); 1234 if (LHS.isKnown()) { 1235 // We were able to evaluate the LHS, see if we can get away with not 1236 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 1237 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 1238 return LHS.isTrue(); 1239 1240 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 1241 if (RHS.isKnown()) { 1242 if (Bop->getOpcode() == BO_LOr) 1243 return LHS.isTrue() || RHS.isTrue(); 1244 else 1245 return LHS.isTrue() && RHS.isTrue(); 1246 } 1247 } else { 1248 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 1249 if (RHS.isKnown()) { 1250 // We can't evaluate the LHS; however, sometimes the result 1251 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 1252 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 1253 return RHS.isTrue(); 1254 } else { 1255 TryResult BopRes = checkIncorrectLogicOperator(Bop); 1256 if (BopRes.isKnown()) 1257 return BopRes.isTrue(); 1258 } 1259 } 1260 1261 return {}; 1262 } else if (Bop->isEqualityOp()) { 1263 TryResult BopRes = checkIncorrectEqualityOperator(Bop); 1264 if (BopRes.isKnown()) 1265 return BopRes.isTrue(); 1266 } else if (Bop->isRelationalOp()) { 1267 TryResult BopRes = checkIncorrectRelationalOperator(Bop); 1268 if (BopRes.isKnown()) 1269 return BopRes.isTrue(); 1270 } else if (Bop->getOpcode() == BO_Or) { 1271 TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop); 1272 if (BopRes.isKnown()) 1273 return BopRes.isTrue(); 1274 } 1275 } 1276 1277 bool Result; 1278 if (E->EvaluateAsBooleanCondition(Result, *Context)) 1279 return Result; 1280 1281 return {}; 1282 } 1283 1284 bool hasTrivialDestructor(VarDecl *VD); 1285 }; 1286 1287 } // namespace 1288 1289 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, 1290 const Stmt *stmt) const { 1291 return builder.alwaysAdd(stmt) || kind == AlwaysAdd; 1292 } 1293 1294 bool CFGBuilder::alwaysAdd(const Stmt *stmt) { 1295 bool shouldAdd = BuildOpts.alwaysAdd(stmt); 1296 1297 if (!BuildOpts.forcedBlkExprs) 1298 return shouldAdd; 1299 1300 if (lastLookup == stmt) { 1301 if (cachedEntry) { 1302 assert(cachedEntry->first == stmt); 1303 return true; 1304 } 1305 return shouldAdd; 1306 } 1307 1308 lastLookup = stmt; 1309 1310 // Perform the lookup! 1311 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; 1312 1313 if (!fb) { 1314 // No need to update 'cachedEntry', since it will always be null. 1315 assert(!cachedEntry); 1316 return shouldAdd; 1317 } 1318 1319 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); 1320 if (itr == fb->end()) { 1321 cachedEntry = nullptr; 1322 return shouldAdd; 1323 } 1324 1325 cachedEntry = &*itr; 1326 return true; 1327 } 1328 1329 // FIXME: Add support for dependent-sized array types in C++? 1330 // Does it even make sense to build a CFG for an uninstantiated template? 1331 static const VariableArrayType *FindVA(const Type *t) { 1332 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { 1333 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) 1334 if (vat->getSizeExpr()) 1335 return vat; 1336 1337 t = vt->getElementType().getTypePtr(); 1338 } 1339 1340 return nullptr; 1341 } 1342 1343 void CFGBuilder::consumeConstructionContext( 1344 const ConstructionContextLayer *Layer, Expr *E) { 1345 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) || 1346 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!"); 1347 if (const ConstructionContextLayer *PreviouslyStoredLayer = 1348 ConstructionContextMap.lookup(E)) { 1349 (void)PreviouslyStoredLayer; 1350 // We might have visited this child when we were finding construction 1351 // contexts within its parents. 1352 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) && 1353 "Already within a different construction context!"); 1354 } else { 1355 ConstructionContextMap[E] = Layer; 1356 } 1357 } 1358 1359 void CFGBuilder::findConstructionContexts( 1360 const ConstructionContextLayer *Layer, Stmt *Child) { 1361 if (!BuildOpts.AddRichCXXConstructors) 1362 return; 1363 1364 if (!Child) 1365 return; 1366 1367 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) { 1368 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item, 1369 Layer); 1370 }; 1371 1372 switch(Child->getStmtClass()) { 1373 case Stmt::CXXConstructExprClass: 1374 case Stmt::CXXTemporaryObjectExprClass: { 1375 // Support pre-C++17 copy elision AST. 1376 auto *CE = cast<CXXConstructExpr>(Child); 1377 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) { 1378 findConstructionContexts(withExtraLayer(CE), CE->getArg(0)); 1379 } 1380 1381 consumeConstructionContext(Layer, CE); 1382 break; 1383 } 1384 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr. 1385 // FIXME: An isa<> would look much better but this whole switch is a 1386 // workaround for an internal compiler error in MSVC 2015 (see r326021). 1387 case Stmt::CallExprClass: 1388 case Stmt::CXXMemberCallExprClass: 1389 case Stmt::CXXOperatorCallExprClass: 1390 case Stmt::UserDefinedLiteralClass: 1391 case Stmt::ObjCMessageExprClass: { 1392 auto *E = cast<Expr>(Child); 1393 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E)) 1394 consumeConstructionContext(Layer, E); 1395 break; 1396 } 1397 case Stmt::ExprWithCleanupsClass: { 1398 auto *Cleanups = cast<ExprWithCleanups>(Child); 1399 findConstructionContexts(Layer, Cleanups->getSubExpr()); 1400 break; 1401 } 1402 case Stmt::CXXFunctionalCastExprClass: { 1403 auto *Cast = cast<CXXFunctionalCastExpr>(Child); 1404 findConstructionContexts(Layer, Cast->getSubExpr()); 1405 break; 1406 } 1407 case Stmt::ImplicitCastExprClass: { 1408 auto *Cast = cast<ImplicitCastExpr>(Child); 1409 // Should we support other implicit cast kinds? 1410 switch (Cast->getCastKind()) { 1411 case CK_NoOp: 1412 case CK_ConstructorConversion: 1413 findConstructionContexts(Layer, Cast->getSubExpr()); 1414 break; 1415 default: 1416 break; 1417 } 1418 break; 1419 } 1420 case Stmt::CXXBindTemporaryExprClass: { 1421 auto *BTE = cast<CXXBindTemporaryExpr>(Child); 1422 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr()); 1423 break; 1424 } 1425 case Stmt::MaterializeTemporaryExprClass: { 1426 // Normally we don't want to search in MaterializeTemporaryExpr because 1427 // it indicates the beginning of a temporary object construction context, 1428 // so it shouldn't be found in the middle. However, if it is the beginning 1429 // of an elidable copy or move construction context, we need to include it. 1430 if (Layer->getItem().getKind() == 1431 ConstructionContextItem::ElidableConstructorKind) { 1432 auto *MTE = cast<MaterializeTemporaryExpr>(Child); 1433 findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr()); 1434 } 1435 break; 1436 } 1437 case Stmt::ConditionalOperatorClass: { 1438 auto *CO = cast<ConditionalOperator>(Child); 1439 if (Layer->getItem().getKind() != 1440 ConstructionContextItem::MaterializationKind) { 1441 // If the object returned by the conditional operator is not going to be a 1442 // temporary object that needs to be immediately materialized, then 1443 // it must be C++17 with its mandatory copy elision. Do not yet promise 1444 // to support this case. 1445 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() || 1446 Context->getLangOpts().CPlusPlus17); 1447 break; 1448 } 1449 findConstructionContexts(Layer, CO->getLHS()); 1450 findConstructionContexts(Layer, CO->getRHS()); 1451 break; 1452 } 1453 case Stmt::InitListExprClass: { 1454 auto *ILE = cast<InitListExpr>(Child); 1455 if (ILE->isTransparent()) { 1456 findConstructionContexts(Layer, ILE->getInit(0)); 1457 break; 1458 } 1459 // TODO: Handle other cases. For now, fail to find construction contexts. 1460 break; 1461 } 1462 case Stmt::ParenExprClass: { 1463 // If expression is placed into parenthesis we should propagate the parent 1464 // construction context to subexpressions. 1465 auto *PE = cast<ParenExpr>(Child); 1466 findConstructionContexts(Layer, PE->getSubExpr()); 1467 break; 1468 } 1469 default: 1470 break; 1471 } 1472 } 1473 1474 void CFGBuilder::cleanupConstructionContext(Expr *E) { 1475 assert(BuildOpts.AddRichCXXConstructors && 1476 "We should not be managing construction contexts!"); 1477 assert(ConstructionContextMap.count(E) && 1478 "Cannot exit construction context without the context!"); 1479 ConstructionContextMap.erase(E); 1480 } 1481 1482 1483 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 1484 /// arbitrary statement. Examples include a single expression or a function 1485 /// body (compound statement). The ownership of the returned CFG is 1486 /// transferred to the caller. If CFG construction fails, this method returns 1487 /// NULL. 1488 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { 1489 assert(cfg.get()); 1490 if (!Statement) 1491 return nullptr; 1492 1493 // Create an empty block that will serve as the exit block for the CFG. Since 1494 // this is the first block added to the CFG, it will be implicitly registered 1495 // as the exit block. 1496 Succ = createBlock(); 1497 assert(Succ == &cfg->getExit()); 1498 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily. 1499 1500 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) && 1501 "AddImplicitDtors and AddLifetime cannot be used at the same time"); 1502 1503 if (BuildOpts.AddImplicitDtors) 1504 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) 1505 addImplicitDtorsForDestructor(DD); 1506 1507 // Visit the statements and create the CFG. 1508 CFGBlock *B = addStmt(Statement); 1509 1510 if (badCFG) 1511 return nullptr; 1512 1513 // For C++ constructor add initializers to CFG. Constructors of virtual bases 1514 // are ignored unless the object is of the most derived class. 1515 // class VBase { VBase() = default; VBase(int) {} }; 1516 // class A : virtual public VBase { A() : VBase(0) {} }; 1517 // class B : public A {}; 1518 // B b; // Constructor calls in order: VBase(), A(), B(). 1519 // // VBase(0) is ignored because A isn't the most derived class. 1520 // This may result in the virtual base(s) being already initialized at this 1521 // point, in which case we should jump right onto non-virtual bases and 1522 // fields. To handle this, make a CFG branch. We only need to add one such 1523 // branch per constructor, since the Standard states that all virtual bases 1524 // shall be initialized before non-virtual bases and direct data members. 1525 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 1526 CFGBlock *VBaseSucc = nullptr; 1527 for (auto *I : llvm::reverse(CD->inits())) { 1528 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc && 1529 I->isBaseInitializer() && I->isBaseVirtual()) { 1530 // We've reached the first virtual base init while iterating in reverse 1531 // order. Make a new block for virtual base initializers so that we 1532 // could skip them. 1533 VBaseSucc = Succ = B ? B : &cfg->getExit(); 1534 Block = createBlock(); 1535 } 1536 B = addInitializer(I); 1537 if (badCFG) 1538 return nullptr; 1539 } 1540 if (VBaseSucc) { 1541 // Make a branch block for potentially skipping virtual base initializers. 1542 Succ = VBaseSucc; 1543 B = createBlock(); 1544 B->setTerminator( 1545 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch)); 1546 addSuccessor(B, Block, true); 1547 } 1548 } 1549 1550 if (B) 1551 Succ = B; 1552 1553 // Backpatch the gotos whose label -> block mappings we didn't know when we 1554 // encountered them. 1555 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 1556 E = BackpatchBlocks.end(); I != E; ++I ) { 1557 1558 CFGBlock *B = I->block; 1559 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) { 1560 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 1561 // If there is no target for the goto, then we are looking at an 1562 // incomplete AST. Handle this by not registering a successor. 1563 if (LI == LabelMap.end()) 1564 continue; 1565 JumpTarget JT = LI->second; 1566 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition, 1567 JT.scopePosition); 1568 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, 1569 JT.scopePosition); 1570 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator( 1571 B, I->scopePosition, JT.scopePosition); 1572 appendScopeBegin(JT.block, VD, G); 1573 addSuccessor(B, JT.block); 1574 }; 1575 if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) { 1576 CFGBlock *Successor = (I+1)->block; 1577 for (auto *L : G->labels()) { 1578 LabelMapTy::iterator LI = LabelMap.find(L->getLabel()); 1579 // If there is no target for the goto, then we are looking at an 1580 // incomplete AST. Handle this by not registering a successor. 1581 if (LI == LabelMap.end()) 1582 continue; 1583 JumpTarget JT = LI->second; 1584 // Successor has been added, so skip it. 1585 if (JT.block == Successor) 1586 continue; 1587 addSuccessor(B, JT.block); 1588 } 1589 I++; 1590 } 1591 } 1592 1593 // Add successors to the Indirect Goto Dispatch block (if we have one). 1594 if (CFGBlock *B = cfg->getIndirectGotoBlock()) 1595 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 1596 E = AddressTakenLabels.end(); I != E; ++I ) { 1597 // Lookup the target block. 1598 LabelMapTy::iterator LI = LabelMap.find(*I); 1599 1600 // If there is no target block that contains label, then we are looking 1601 // at an incomplete AST. Handle this by not registering a successor. 1602 if (LI == LabelMap.end()) continue; 1603 1604 addSuccessor(B, LI->second.block); 1605 } 1606 1607 // Create an empty entry block that has no predecessors. 1608 cfg->setEntry(createBlock()); 1609 1610 if (BuildOpts.AddRichCXXConstructors) 1611 assert(ConstructionContextMap.empty() && 1612 "Not all construction contexts were cleaned up!"); 1613 1614 return std::move(cfg); 1615 } 1616 1617 /// createBlock - Used to lazily create blocks that are connected 1618 /// to the current (global) succcessor. 1619 CFGBlock *CFGBuilder::createBlock(bool add_successor) { 1620 CFGBlock *B = cfg->createBlock(); 1621 if (add_successor && Succ) 1622 addSuccessor(B, Succ); 1623 return B; 1624 } 1625 1626 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the 1627 /// CFG. It is *not* connected to the current (global) successor, and instead 1628 /// directly tied to the exit block in order to be reachable. 1629 CFGBlock *CFGBuilder::createNoReturnBlock() { 1630 CFGBlock *B = createBlock(false); 1631 B->setHasNoReturnElement(); 1632 addSuccessor(B, &cfg->getExit(), Succ); 1633 return B; 1634 } 1635 1636 /// addInitializer - Add C++ base or member initializer element to CFG. 1637 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { 1638 if (!BuildOpts.AddInitializers) 1639 return Block; 1640 1641 bool HasTemporaries = false; 1642 1643 // Destructors of temporaries in initialization expression should be called 1644 // after initialization finishes. 1645 Expr *Init = I->getInit(); 1646 if (Init) { 1647 HasTemporaries = isa<ExprWithCleanups>(Init); 1648 1649 if (BuildOpts.AddTemporaryDtors && HasTemporaries) { 1650 // Generate destructors for temporaries in initialization expression. 1651 TempDtorContext Context; 1652 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 1653 /*ExternallyDestructed=*/false, Context); 1654 } 1655 } 1656 1657 autoCreateBlock(); 1658 appendInitializer(Block, I); 1659 1660 if (Init) { 1661 findConstructionContexts( 1662 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I), 1663 Init); 1664 1665 if (HasTemporaries) { 1666 // For expression with temporaries go directly to subexpression to omit 1667 // generating destructors for the second time. 1668 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 1669 } 1670 if (BuildOpts.AddCXXDefaultInitExprInCtors) { 1671 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) { 1672 // In general, appending the expression wrapped by a CXXDefaultInitExpr 1673 // may cause the same Expr to appear more than once in the CFG. Doing it 1674 // here is safe because there's only one initializer per field. 1675 autoCreateBlock(); 1676 appendStmt(Block, Default); 1677 if (Stmt *Child = Default->getExpr()) 1678 if (CFGBlock *R = Visit(Child)) 1679 Block = R; 1680 return Block; 1681 } 1682 } 1683 return Visit(Init); 1684 } 1685 1686 return Block; 1687 } 1688 1689 /// Retrieve the type of the temporary object whose lifetime was 1690 /// extended by a local reference with the given initializer. 1691 static QualType getReferenceInitTemporaryType(const Expr *Init, 1692 bool *FoundMTE = nullptr) { 1693 while (true) { 1694 // Skip parentheses. 1695 Init = Init->IgnoreParens(); 1696 1697 // Skip through cleanups. 1698 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) { 1699 Init = EWC->getSubExpr(); 1700 continue; 1701 } 1702 1703 // Skip through the temporary-materialization expression. 1704 if (const MaterializeTemporaryExpr *MTE 1705 = dyn_cast<MaterializeTemporaryExpr>(Init)) { 1706 Init = MTE->getSubExpr(); 1707 if (FoundMTE) 1708 *FoundMTE = true; 1709 continue; 1710 } 1711 1712 // Skip sub-object accesses into rvalues. 1713 SmallVector<const Expr *, 2> CommaLHSs; 1714 SmallVector<SubobjectAdjustment, 2> Adjustments; 1715 const Expr *SkippedInit = 1716 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 1717 if (SkippedInit != Init) { 1718 Init = SkippedInit; 1719 continue; 1720 } 1721 1722 break; 1723 } 1724 1725 return Init->getType(); 1726 } 1727 1728 // TODO: Support adding LoopExit element to the CFG in case where the loop is 1729 // ended by ReturnStmt, GotoStmt or ThrowExpr. 1730 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){ 1731 if(!BuildOpts.AddLoopExit) 1732 return; 1733 autoCreateBlock(); 1734 appendLoopExit(Block, LoopStmt); 1735 } 1736 1737 void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B, 1738 LocalScope::const_iterator E, Stmt *S) { 1739 if (!BuildOpts.AddScopes) 1740 return; 1741 1742 if (B == E) 1743 return; 1744 1745 // To go from B to E, one first goes up the scopes from B to P 1746 // then sideways in one scope from P to P' and then down 1747 // the scopes from P' to E. 1748 // The lifetime of all objects between B and P end. 1749 LocalScope::const_iterator P = B.shared_parent(E); 1750 int Dist = B.distance(P); 1751 if (Dist <= 0) 1752 return; 1753 1754 for (LocalScope::const_iterator I = B; I != P; ++I) 1755 if (I.pointsToFirstDeclaredVar()) 1756 DeclsWithEndedScope.insert(*I); 1757 } 1758 1759 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B, 1760 LocalScope::const_iterator E, 1761 Stmt *S) { 1762 getDeclsWithEndedScope(B, E, S); 1763 if (BuildOpts.AddScopes) 1764 addScopesEnd(B, E, S); 1765 if (BuildOpts.AddImplicitDtors) 1766 addAutomaticObjDtors(B, E, S); 1767 if (BuildOpts.AddLifetime) 1768 addLifetimeEnds(B, E, S); 1769 } 1770 1771 /// Add to current block automatic objects that leave the scope. 1772 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B, 1773 LocalScope::const_iterator E, Stmt *S) { 1774 if (!BuildOpts.AddLifetime) 1775 return; 1776 1777 if (B == E) 1778 return; 1779 1780 // To go from B to E, one first goes up the scopes from B to P 1781 // then sideways in one scope from P to P' and then down 1782 // the scopes from P' to E. 1783 // The lifetime of all objects between B and P end. 1784 LocalScope::const_iterator P = B.shared_parent(E); 1785 int dist = B.distance(P); 1786 if (dist <= 0) 1787 return; 1788 1789 // We need to perform the scope leaving in reverse order 1790 SmallVector<VarDecl *, 10> DeclsTrivial; 1791 SmallVector<VarDecl *, 10> DeclsNonTrivial; 1792 DeclsTrivial.reserve(dist); 1793 DeclsNonTrivial.reserve(dist); 1794 1795 for (LocalScope::const_iterator I = B; I != P; ++I) 1796 if (hasTrivialDestructor(*I)) 1797 DeclsTrivial.push_back(*I); 1798 else 1799 DeclsNonTrivial.push_back(*I); 1800 1801 autoCreateBlock(); 1802 // object with trivial destructor end their lifetime last (when storage 1803 // duration ends) 1804 for (VarDecl *VD : llvm::reverse(DeclsTrivial)) 1805 appendLifetimeEnds(Block, VD, S); 1806 1807 for (VarDecl *VD : llvm::reverse(DeclsNonTrivial)) 1808 appendLifetimeEnds(Block, VD, S); 1809 } 1810 1811 /// Add to current block markers for ending scopes. 1812 void CFGBuilder::addScopesEnd(LocalScope::const_iterator B, 1813 LocalScope::const_iterator E, Stmt *S) { 1814 // If implicit destructors are enabled, we'll add scope ends in 1815 // addAutomaticObjDtors. 1816 if (BuildOpts.AddImplicitDtors) 1817 return; 1818 1819 autoCreateBlock(); 1820 1821 for (VarDecl *VD : llvm::reverse(DeclsWithEndedScope)) 1822 appendScopeEnd(Block, VD, S); 1823 } 1824 1825 /// addAutomaticObjDtors - Add to current block automatic objects destructors 1826 /// for objects in range of local scope positions. Use S as trigger statement 1827 /// for destructors. 1828 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 1829 LocalScope::const_iterator E, Stmt *S) { 1830 if (!BuildOpts.AddImplicitDtors) 1831 return; 1832 1833 if (B == E) 1834 return; 1835 1836 // We need to append the destructors in reverse order, but any one of them 1837 // may be a no-return destructor which changes the CFG. As a result, buffer 1838 // this sequence up and replay them in reverse order when appending onto the 1839 // CFGBlock(s). 1840 SmallVector<VarDecl*, 10> Decls; 1841 Decls.reserve(B.distance(E)); 1842 for (LocalScope::const_iterator I = B; I != E; ++I) 1843 Decls.push_back(*I); 1844 1845 for (VarDecl *VD : llvm::reverse(Decls)) { 1846 if (hasTrivialDestructor(VD)) { 1847 // If AddScopes is enabled and *I is a first variable in a scope, add a 1848 // ScopeEnd marker in a Block. 1849 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) { 1850 autoCreateBlock(); 1851 appendScopeEnd(Block, VD, S); 1852 } 1853 continue; 1854 } 1855 // If this destructor is marked as a no-return destructor, we need to 1856 // create a new block for the destructor which does not have as a successor 1857 // anything built thus far: control won't flow out of this block. 1858 QualType Ty = VD->getType(); 1859 if (Ty->isReferenceType()) { 1860 Ty = getReferenceInitTemporaryType(VD->getInit()); 1861 } 1862 Ty = Context->getBaseElementType(Ty); 1863 1864 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn()) 1865 Block = createNoReturnBlock(); 1866 else 1867 autoCreateBlock(); 1868 1869 // Add ScopeEnd just after automatic obj destructor. 1870 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(VD)) 1871 appendScopeEnd(Block, VD, S); 1872 appendAutomaticObjDtor(Block, VD, S); 1873 } 1874 } 1875 1876 /// addImplicitDtorsForDestructor - Add implicit destructors generated for 1877 /// base and member objects in destructor. 1878 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 1879 assert(BuildOpts.AddImplicitDtors && 1880 "Can be called only when dtors should be added"); 1881 const CXXRecordDecl *RD = DD->getParent(); 1882 1883 // At the end destroy virtual base objects. 1884 for (const auto &VI : RD->vbases()) { 1885 // TODO: Add a VirtualBaseBranch to see if the most derived class 1886 // (which is different from the current class) is responsible for 1887 // destroying them. 1888 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl(); 1889 if (!CD->hasTrivialDestructor()) { 1890 autoCreateBlock(); 1891 appendBaseDtor(Block, &VI); 1892 } 1893 } 1894 1895 // Before virtual bases destroy direct base objects. 1896 for (const auto &BI : RD->bases()) { 1897 if (!BI.isVirtual()) { 1898 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl(); 1899 if (!CD->hasTrivialDestructor()) { 1900 autoCreateBlock(); 1901 appendBaseDtor(Block, &BI); 1902 } 1903 } 1904 } 1905 1906 // First destroy member objects. 1907 for (auto *FI : RD->fields()) { 1908 // Check for constant size array. Set type to array element type. 1909 QualType QT = FI->getType(); 1910 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 1911 if (AT->getSize() == 0) 1912 continue; 1913 QT = AT->getElementType(); 1914 } 1915 1916 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 1917 if (!CD->hasTrivialDestructor()) { 1918 autoCreateBlock(); 1919 appendMemberDtor(Block, FI); 1920 } 1921 } 1922 } 1923 1924 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 1925 /// way return valid LocalScope object. 1926 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 1927 if (Scope) 1928 return Scope; 1929 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 1930 return new (alloc.Allocate<LocalScope>()) 1931 LocalScope(BumpVectorContext(alloc), ScopePos); 1932 } 1933 1934 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 1935 /// that should create implicit scope (e.g. if/else substatements). 1936 void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 1937 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 1938 !BuildOpts.AddScopes) 1939 return; 1940 1941 LocalScope *Scope = nullptr; 1942 1943 // For compound statement we will be creating explicit scope. 1944 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 1945 for (auto *BI : CS->body()) { 1946 Stmt *SI = BI->stripLabelLikeStatements(); 1947 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 1948 Scope = addLocalScopeForDeclStmt(DS, Scope); 1949 } 1950 return; 1951 } 1952 1953 // For any other statement scope will be implicit and as such will be 1954 // interesting only for DeclStmt. 1955 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 1956 addLocalScopeForDeclStmt(DS); 1957 } 1958 1959 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 1960 /// reuse Scope if not NULL. 1961 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 1962 LocalScope* Scope) { 1963 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 1964 !BuildOpts.AddScopes) 1965 return Scope; 1966 1967 for (auto *DI : DS->decls()) 1968 if (VarDecl *VD = dyn_cast<VarDecl>(DI)) 1969 Scope = addLocalScopeForVarDecl(VD, Scope); 1970 return Scope; 1971 } 1972 1973 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) { 1974 // Check for const references bound to temporary. Set type to pointee. 1975 QualType QT = VD->getType(); 1976 if (QT->isReferenceType()) { 1977 // Attempt to determine whether this declaration lifetime-extends a 1978 // temporary. 1979 // 1980 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend 1981 // temporaries, and a single declaration can extend multiple temporaries. 1982 // We should look at the storage duration on each nested 1983 // MaterializeTemporaryExpr instead. 1984 1985 const Expr *Init = VD->getInit(); 1986 if (!Init) { 1987 // Probably an exception catch-by-reference variable. 1988 // FIXME: It doesn't really mean that the object has a trivial destructor. 1989 // Also are there other cases? 1990 return true; 1991 } 1992 1993 // Lifetime-extending a temporary? 1994 bool FoundMTE = false; 1995 QT = getReferenceInitTemporaryType(Init, &FoundMTE); 1996 if (!FoundMTE) 1997 return true; 1998 } 1999 2000 // Check for constant size array. Set type to array element type. 2001 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 2002 if (AT->getSize() == 0) 2003 return true; 2004 QT = AT->getElementType(); 2005 } 2006 2007 // Check if type is a C++ class with non-trivial destructor. 2008 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 2009 return !CD->hasDefinition() || CD->hasTrivialDestructor(); 2010 return true; 2011 } 2012 2013 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 2014 /// create add scope for automatic objects and temporary objects bound to 2015 /// const reference. Will reuse Scope if not NULL. 2016 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 2017 LocalScope* Scope) { 2018 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) && 2019 "AddImplicitDtors and AddLifetime cannot be used at the same time"); 2020 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime && 2021 !BuildOpts.AddScopes) 2022 return Scope; 2023 2024 // Check if variable is local. 2025 switch (VD->getStorageClass()) { 2026 case SC_None: 2027 case SC_Auto: 2028 case SC_Register: 2029 break; 2030 default: return Scope; 2031 } 2032 2033 if (BuildOpts.AddImplicitDtors) { 2034 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) { 2035 // Add the variable to scope 2036 Scope = createOrReuseLocalScope(Scope); 2037 Scope->addVar(VD); 2038 ScopePos = Scope->begin(); 2039 } 2040 return Scope; 2041 } 2042 2043 assert(BuildOpts.AddLifetime); 2044 // Add the variable to scope 2045 Scope = createOrReuseLocalScope(Scope); 2046 Scope->addVar(VD); 2047 ScopePos = Scope->begin(); 2048 return Scope; 2049 } 2050 2051 /// addLocalScopeAndDtors - For given statement add local scope for it and 2052 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 2053 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 2054 LocalScope::const_iterator scopeBeginPos = ScopePos; 2055 addLocalScopeForStmt(S); 2056 addAutomaticObjHandling(ScopePos, scopeBeginPos, S); 2057 } 2058 2059 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 2060 /// variables with automatic storage duration to CFGBlock's elements vector. 2061 /// Elements will be prepended to physical beginning of the vector which 2062 /// happens to be logical end. Use blocks terminator as statement that specifies 2063 /// destructors call site. 2064 /// FIXME: This mechanism for adding automatic destructors doesn't handle 2065 /// no-return destructors properly. 2066 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 2067 LocalScope::const_iterator B, LocalScope::const_iterator E) { 2068 if (!BuildOpts.AddImplicitDtors) 2069 return; 2070 BumpVectorContext &C = cfg->getBumpVectorContext(); 2071 CFGBlock::iterator InsertPos 2072 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); 2073 for (LocalScope::const_iterator I = B; I != E; ++I) 2074 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, 2075 Blk->getTerminatorStmt()); 2076 } 2077 2078 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for 2079 /// variables with automatic storage duration to CFGBlock's elements vector. 2080 /// Elements will be prepended to physical beginning of the vector which 2081 /// happens to be logical end. Use blocks terminator as statement that specifies 2082 /// where lifetime ends. 2083 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator( 2084 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { 2085 if (!BuildOpts.AddLifetime) 2086 return; 2087 BumpVectorContext &C = cfg->getBumpVectorContext(); 2088 CFGBlock::iterator InsertPos = 2089 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C); 2090 for (LocalScope::const_iterator I = B; I != E; ++I) { 2091 InsertPos = 2092 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt()); 2093 } 2094 } 2095 2096 /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for 2097 /// variables with automatic storage duration to CFGBlock's elements vector. 2098 /// Elements will be prepended to physical beginning of the vector which 2099 /// happens to be logical end. Use blocks terminator as statement that specifies 2100 /// where scope ends. 2101 const VarDecl * 2102 CFGBuilder::prependAutomaticObjScopeEndWithTerminator( 2103 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) { 2104 if (!BuildOpts.AddScopes) 2105 return nullptr; 2106 BumpVectorContext &C = cfg->getBumpVectorContext(); 2107 CFGBlock::iterator InsertPos = 2108 Blk->beginScopeEndInsert(Blk->end(), 1, C); 2109 LocalScope::const_iterator PlaceToInsert = B; 2110 for (LocalScope::const_iterator I = B; I != E; ++I) 2111 PlaceToInsert = I; 2112 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt()); 2113 return *PlaceToInsert; 2114 } 2115 2116 /// Visit - Walk the subtree of a statement and add extra 2117 /// blocks for ternary operators, &&, and ||. We also process "," and 2118 /// DeclStmts (which may contain nested control-flow). 2119 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc, 2120 bool ExternallyDestructed) { 2121 if (!S) { 2122 badCFG = true; 2123 return nullptr; 2124 } 2125 2126 if (Expr *E = dyn_cast<Expr>(S)) 2127 S = E->IgnoreParens(); 2128 2129 if (Context->getLangOpts().OpenMP) 2130 if (auto *D = dyn_cast<OMPExecutableDirective>(S)) 2131 return VisitOMPExecutableDirective(D, asc); 2132 2133 switch (S->getStmtClass()) { 2134 default: 2135 return VisitStmt(S, asc); 2136 2137 case Stmt::ImplicitValueInitExprClass: 2138 if (BuildOpts.OmitImplicitValueInitializers) 2139 return Block; 2140 return VisitStmt(S, asc); 2141 2142 case Stmt::InitListExprClass: 2143 return VisitInitListExpr(cast<InitListExpr>(S), asc); 2144 2145 case Stmt::AttributedStmtClass: 2146 return VisitAttributedStmt(cast<AttributedStmt>(S), asc); 2147 2148 case Stmt::AddrLabelExprClass: 2149 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 2150 2151 case Stmt::BinaryConditionalOperatorClass: 2152 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 2153 2154 case Stmt::BinaryOperatorClass: 2155 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 2156 2157 case Stmt::BlockExprClass: 2158 return VisitBlockExpr(cast<BlockExpr>(S), asc); 2159 2160 case Stmt::BreakStmtClass: 2161 return VisitBreakStmt(cast<BreakStmt>(S)); 2162 2163 case Stmt::CallExprClass: 2164 case Stmt::CXXOperatorCallExprClass: 2165 case Stmt::CXXMemberCallExprClass: 2166 case Stmt::UserDefinedLiteralClass: 2167 return VisitCallExpr(cast<CallExpr>(S), asc); 2168 2169 case Stmt::CaseStmtClass: 2170 return VisitCaseStmt(cast<CaseStmt>(S)); 2171 2172 case Stmt::ChooseExprClass: 2173 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 2174 2175 case Stmt::CompoundStmtClass: 2176 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed); 2177 2178 case Stmt::ConditionalOperatorClass: 2179 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 2180 2181 case Stmt::ContinueStmtClass: 2182 return VisitContinueStmt(cast<ContinueStmt>(S)); 2183 2184 case Stmt::CXXCatchStmtClass: 2185 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 2186 2187 case Stmt::ExprWithCleanupsClass: 2188 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), 2189 asc, ExternallyDestructed); 2190 2191 case Stmt::CXXDefaultArgExprClass: 2192 case Stmt::CXXDefaultInitExprClass: 2193 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the 2194 // called function's declaration, not by the caller. If we simply add 2195 // this expression to the CFG, we could end up with the same Expr 2196 // appearing multiple times. 2197 // PR13385 / <rdar://problem/12156507> 2198 // 2199 // It's likewise possible for multiple CXXDefaultInitExprs for the same 2200 // expression to be used in the same function (through aggregate 2201 // initialization). 2202 return VisitStmt(S, asc); 2203 2204 case Stmt::CXXBindTemporaryExprClass: 2205 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 2206 2207 case Stmt::CXXConstructExprClass: 2208 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 2209 2210 case Stmt::CXXNewExprClass: 2211 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc); 2212 2213 case Stmt::CXXDeleteExprClass: 2214 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc); 2215 2216 case Stmt::CXXFunctionalCastExprClass: 2217 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 2218 2219 case Stmt::CXXTemporaryObjectExprClass: 2220 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 2221 2222 case Stmt::CXXThrowExprClass: 2223 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 2224 2225 case Stmt::CXXTryStmtClass: 2226 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 2227 2228 case Stmt::CXXForRangeStmtClass: 2229 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 2230 2231 case Stmt::DeclStmtClass: 2232 return VisitDeclStmt(cast<DeclStmt>(S)); 2233 2234 case Stmt::DefaultStmtClass: 2235 return VisitDefaultStmt(cast<DefaultStmt>(S)); 2236 2237 case Stmt::DoStmtClass: 2238 return VisitDoStmt(cast<DoStmt>(S)); 2239 2240 case Stmt::ForStmtClass: 2241 return VisitForStmt(cast<ForStmt>(S)); 2242 2243 case Stmt::GotoStmtClass: 2244 return VisitGotoStmt(cast<GotoStmt>(S)); 2245 2246 case Stmt::GCCAsmStmtClass: 2247 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc); 2248 2249 case Stmt::IfStmtClass: 2250 return VisitIfStmt(cast<IfStmt>(S)); 2251 2252 case Stmt::ImplicitCastExprClass: 2253 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 2254 2255 case Stmt::ConstantExprClass: 2256 return VisitConstantExpr(cast<ConstantExpr>(S), asc); 2257 2258 case Stmt::IndirectGotoStmtClass: 2259 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 2260 2261 case Stmt::LabelStmtClass: 2262 return VisitLabelStmt(cast<LabelStmt>(S)); 2263 2264 case Stmt::LambdaExprClass: 2265 return VisitLambdaExpr(cast<LambdaExpr>(S), asc); 2266 2267 case Stmt::MaterializeTemporaryExprClass: 2268 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S), 2269 asc); 2270 2271 case Stmt::MemberExprClass: 2272 return VisitMemberExpr(cast<MemberExpr>(S), asc); 2273 2274 case Stmt::NullStmtClass: 2275 return Block; 2276 2277 case Stmt::ObjCAtCatchStmtClass: 2278 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 2279 2280 case Stmt::ObjCAutoreleasePoolStmtClass: 2281 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S)); 2282 2283 case Stmt::ObjCAtSynchronizedStmtClass: 2284 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 2285 2286 case Stmt::ObjCAtThrowStmtClass: 2287 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 2288 2289 case Stmt::ObjCAtTryStmtClass: 2290 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 2291 2292 case Stmt::ObjCForCollectionStmtClass: 2293 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 2294 2295 case Stmt::ObjCMessageExprClass: 2296 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc); 2297 2298 case Stmt::OpaqueValueExprClass: 2299 return Block; 2300 2301 case Stmt::PseudoObjectExprClass: 2302 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S)); 2303 2304 case Stmt::ReturnStmtClass: 2305 case Stmt::CoreturnStmtClass: 2306 return VisitReturnStmt(S); 2307 2308 case Stmt::SEHExceptStmtClass: 2309 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S)); 2310 2311 case Stmt::SEHFinallyStmtClass: 2312 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S)); 2313 2314 case Stmt::SEHLeaveStmtClass: 2315 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S)); 2316 2317 case Stmt::SEHTryStmtClass: 2318 return VisitSEHTryStmt(cast<SEHTryStmt>(S)); 2319 2320 case Stmt::UnaryExprOrTypeTraitExprClass: 2321 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 2322 asc); 2323 2324 case Stmt::StmtExprClass: 2325 return VisitStmtExpr(cast<StmtExpr>(S), asc); 2326 2327 case Stmt::SwitchStmtClass: 2328 return VisitSwitchStmt(cast<SwitchStmt>(S)); 2329 2330 case Stmt::UnaryOperatorClass: 2331 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 2332 2333 case Stmt::WhileStmtClass: 2334 return VisitWhileStmt(cast<WhileStmt>(S)); 2335 } 2336 } 2337 2338 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 2339 if (asc.alwaysAdd(*this, S)) { 2340 autoCreateBlock(); 2341 appendStmt(Block, S); 2342 } 2343 2344 return VisitChildren(S); 2345 } 2346 2347 /// VisitChildren - Visit the children of a Stmt. 2348 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) { 2349 CFGBlock *B = Block; 2350 2351 // Visit the children in their reverse order so that they appear in 2352 // left-to-right (natural) order in the CFG. 2353 reverse_children RChildren(S); 2354 for (Stmt *Child : RChildren) { 2355 if (Child) 2356 if (CFGBlock *R = Visit(Child)) 2357 B = R; 2358 } 2359 return B; 2360 } 2361 2362 CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) { 2363 if (asc.alwaysAdd(*this, ILE)) { 2364 autoCreateBlock(); 2365 appendStmt(Block, ILE); 2366 } 2367 CFGBlock *B = Block; 2368 2369 reverse_children RChildren(ILE); 2370 for (Stmt *Child : RChildren) { 2371 if (!Child) 2372 continue; 2373 if (CFGBlock *R = Visit(Child)) 2374 B = R; 2375 if (BuildOpts.AddCXXDefaultInitExprInAggregates) { 2376 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child)) 2377 if (Stmt *Child = DIE->getExpr()) 2378 if (CFGBlock *R = Visit(Child)) 2379 B = R; 2380 } 2381 } 2382 return B; 2383 } 2384 2385 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 2386 AddStmtChoice asc) { 2387 AddressTakenLabels.insert(A->getLabel()); 2388 2389 if (asc.alwaysAdd(*this, A)) { 2390 autoCreateBlock(); 2391 appendStmt(Block, A); 2392 } 2393 2394 return Block; 2395 } 2396 2397 static bool isFallthroughStatement(const AttributedStmt *A) { 2398 bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs()); 2399 assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) && 2400 "expected fallthrough not to have children"); 2401 return isFallthrough; 2402 } 2403 2404 CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A, 2405 AddStmtChoice asc) { 2406 // AttributedStmts for [[likely]] can have arbitrary statements as children, 2407 // and the current visitation order here would add the AttributedStmts 2408 // for [[likely]] after the child nodes, which is undesirable: For example, 2409 // if the child contains an unconditional return, the [[likely]] would be 2410 // considered unreachable. 2411 // So only add the AttributedStmt for FallThrough, which has CFG effects and 2412 // also no children, and omit the others. None of the other current StmtAttrs 2413 // have semantic meaning for the CFG. 2414 if (isFallthroughStatement(A) && asc.alwaysAdd(*this, A)) { 2415 autoCreateBlock(); 2416 appendStmt(Block, A); 2417 } 2418 2419 return VisitChildren(A); 2420 } 2421 2422 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) { 2423 if (asc.alwaysAdd(*this, U)) { 2424 autoCreateBlock(); 2425 appendStmt(Block, U); 2426 } 2427 2428 if (U->getOpcode() == UO_LNot) 2429 tryEvaluateBool(U->getSubExpr()->IgnoreParens()); 2430 2431 return Visit(U->getSubExpr(), AddStmtChoice()); 2432 } 2433 2434 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) { 2435 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 2436 appendStmt(ConfluenceBlock, B); 2437 2438 if (badCFG) 2439 return nullptr; 2440 2441 return VisitLogicalOperator(B, nullptr, ConfluenceBlock, 2442 ConfluenceBlock).first; 2443 } 2444 2445 std::pair<CFGBlock*, CFGBlock*> 2446 CFGBuilder::VisitLogicalOperator(BinaryOperator *B, 2447 Stmt *Term, 2448 CFGBlock *TrueBlock, 2449 CFGBlock *FalseBlock) { 2450 // Introspect the RHS. If it is a nested logical operation, we recursively 2451 // build the CFG using this function. Otherwise, resort to default 2452 // CFG construction behavior. 2453 Expr *RHS = B->getRHS()->IgnoreParens(); 2454 CFGBlock *RHSBlock, *ExitBlock; 2455 2456 do { 2457 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS)) 2458 if (B_RHS->isLogicalOp()) { 2459 std::tie(RHSBlock, ExitBlock) = 2460 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock); 2461 break; 2462 } 2463 2464 // The RHS is not a nested logical operation. Don't push the terminator 2465 // down further, but instead visit RHS and construct the respective 2466 // pieces of the CFG, and link up the RHSBlock with the terminator 2467 // we have been provided. 2468 ExitBlock = RHSBlock = createBlock(false); 2469 2470 // Even though KnownVal is only used in the else branch of the next 2471 // conditional, tryEvaluateBool performs additional checking on the 2472 // Expr, so it should be called unconditionally. 2473 TryResult KnownVal = tryEvaluateBool(RHS); 2474 if (!KnownVal.isKnown()) 2475 KnownVal = tryEvaluateBool(B); 2476 2477 if (!Term) { 2478 assert(TrueBlock == FalseBlock); 2479 addSuccessor(RHSBlock, TrueBlock); 2480 } 2481 else { 2482 RHSBlock->setTerminator(Term); 2483 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse()); 2484 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue()); 2485 } 2486 2487 Block = RHSBlock; 2488 RHSBlock = addStmt(RHS); 2489 } 2490 while (false); 2491 2492 if (badCFG) 2493 return std::make_pair(nullptr, nullptr); 2494 2495 // Generate the blocks for evaluating the LHS. 2496 Expr *LHS = B->getLHS()->IgnoreParens(); 2497 2498 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS)) 2499 if (B_LHS->isLogicalOp()) { 2500 if (B->getOpcode() == BO_LOr) 2501 FalseBlock = RHSBlock; 2502 else 2503 TrueBlock = RHSBlock; 2504 2505 // For the LHS, treat 'B' as the terminator that we want to sink 2506 // into the nested branch. The RHS always gets the top-most 2507 // terminator. 2508 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock); 2509 } 2510 2511 // Create the block evaluating the LHS. 2512 // This contains the '&&' or '||' as the terminator. 2513 CFGBlock *LHSBlock = createBlock(false); 2514 LHSBlock->setTerminator(B); 2515 2516 Block = LHSBlock; 2517 CFGBlock *EntryLHSBlock = addStmt(LHS); 2518 2519 if (badCFG) 2520 return std::make_pair(nullptr, nullptr); 2521 2522 // See if this is a known constant. 2523 TryResult KnownVal = tryEvaluateBool(LHS); 2524 2525 // Now link the LHSBlock with RHSBlock. 2526 if (B->getOpcode() == BO_LOr) { 2527 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse()); 2528 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue()); 2529 } else { 2530 assert(B->getOpcode() == BO_LAnd); 2531 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse()); 2532 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue()); 2533 } 2534 2535 return std::make_pair(EntryLHSBlock, ExitBlock); 2536 } 2537 2538 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 2539 AddStmtChoice asc) { 2540 // && or || 2541 if (B->isLogicalOp()) 2542 return VisitLogicalOperator(B); 2543 2544 if (B->getOpcode() == BO_Comma) { // , 2545 autoCreateBlock(); 2546 appendStmt(Block, B); 2547 addStmt(B->getRHS()); 2548 return addStmt(B->getLHS()); 2549 } 2550 2551 if (B->isAssignmentOp()) { 2552 if (asc.alwaysAdd(*this, B)) { 2553 autoCreateBlock(); 2554 appendStmt(Block, B); 2555 } 2556 Visit(B->getLHS()); 2557 return Visit(B->getRHS()); 2558 } 2559 2560 if (asc.alwaysAdd(*this, B)) { 2561 autoCreateBlock(); 2562 appendStmt(Block, B); 2563 } 2564 2565 if (B->isEqualityOp() || B->isRelationalOp()) 2566 tryEvaluateBool(B); 2567 2568 CFGBlock *RBlock = Visit(B->getRHS()); 2569 CFGBlock *LBlock = Visit(B->getLHS()); 2570 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr 2571 // containing a DoStmt, and the LHS doesn't create a new block, then we should 2572 // return RBlock. Otherwise we'll incorrectly return NULL. 2573 return (LBlock ? LBlock : RBlock); 2574 } 2575 2576 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) { 2577 if (asc.alwaysAdd(*this, E)) { 2578 autoCreateBlock(); 2579 appendStmt(Block, E); 2580 } 2581 return Block; 2582 } 2583 2584 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 2585 // "break" is a control-flow statement. Thus we stop processing the current 2586 // block. 2587 if (badCFG) 2588 return nullptr; 2589 2590 // Now create a new block that ends with the break statement. 2591 Block = createBlock(false); 2592 Block->setTerminator(B); 2593 2594 // If there is no target for the break, then we are looking at an incomplete 2595 // AST. This means that the CFG cannot be constructed. 2596 if (BreakJumpTarget.block) { 2597 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B); 2598 addSuccessor(Block, BreakJumpTarget.block); 2599 } else 2600 badCFG = true; 2601 2602 return Block; 2603 } 2604 2605 static bool CanThrow(Expr *E, ASTContext &Ctx) { 2606 QualType Ty = E->getType(); 2607 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType()) 2608 Ty = Ty->getPointeeType(); 2609 2610 const FunctionType *FT = Ty->getAs<FunctionType>(); 2611 if (FT) { 2612 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 2613 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) && 2614 Proto->isNothrow()) 2615 return false; 2616 } 2617 return true; 2618 } 2619 2620 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 2621 // Compute the callee type. 2622 QualType calleeType = C->getCallee()->getType(); 2623 if (calleeType == Context->BoundMemberTy) { 2624 QualType boundType = Expr::findBoundMemberType(C->getCallee()); 2625 2626 // We should only get a null bound type if processing a dependent 2627 // CFG. Recover by assuming nothing. 2628 if (!boundType.isNull()) calleeType = boundType; 2629 } 2630 2631 // If this is a call to a no-return function, this stops the block here. 2632 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); 2633 2634 bool AddEHEdge = false; 2635 2636 // Languages without exceptions are assumed to not throw. 2637 if (Context->getLangOpts().Exceptions) { 2638 if (BuildOpts.AddEHEdges) 2639 AddEHEdge = true; 2640 } 2641 2642 // If this is a call to a builtin function, it might not actually evaluate 2643 // its arguments. Don't add them to the CFG if this is the case. 2644 bool OmitArguments = false; 2645 2646 if (FunctionDecl *FD = C->getDirectCallee()) { 2647 // TODO: Support construction contexts for variadic function arguments. 2648 // These are a bit problematic and not very useful because passing 2649 // C++ objects as C-style variadic arguments doesn't work in general 2650 // (see [expr.call]). 2651 if (!FD->isVariadic()) 2652 findConstructionContextsForArguments(C); 2653 2654 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context)) 2655 NoReturn = true; 2656 if (FD->hasAttr<NoThrowAttr>()) 2657 AddEHEdge = false; 2658 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size || 2659 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size) 2660 OmitArguments = true; 2661 } 2662 2663 if (!CanThrow(C->getCallee(), *Context)) 2664 AddEHEdge = false; 2665 2666 if (OmitArguments) { 2667 assert(!NoReturn && "noreturn calls with unevaluated args not implemented"); 2668 assert(!AddEHEdge && "EH calls with unevaluated args not implemented"); 2669 autoCreateBlock(); 2670 appendStmt(Block, C); 2671 return Visit(C->getCallee()); 2672 } 2673 2674 if (!NoReturn && !AddEHEdge) { 2675 autoCreateBlock(); 2676 appendCall(Block, C); 2677 2678 return VisitChildren(C); 2679 } 2680 2681 if (Block) { 2682 Succ = Block; 2683 if (badCFG) 2684 return nullptr; 2685 } 2686 2687 if (NoReturn) 2688 Block = createNoReturnBlock(); 2689 else 2690 Block = createBlock(); 2691 2692 appendCall(Block, C); 2693 2694 if (AddEHEdge) { 2695 // Add exceptional edges. 2696 if (TryTerminatedBlock) 2697 addSuccessor(Block, TryTerminatedBlock); 2698 else 2699 addSuccessor(Block, &cfg->getExit()); 2700 } 2701 2702 return VisitChildren(C); 2703 } 2704 2705 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 2706 AddStmtChoice asc) { 2707 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 2708 appendStmt(ConfluenceBlock, C); 2709 if (badCFG) 2710 return nullptr; 2711 2712 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 2713 Succ = ConfluenceBlock; 2714 Block = nullptr; 2715 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); 2716 if (badCFG) 2717 return nullptr; 2718 2719 Succ = ConfluenceBlock; 2720 Block = nullptr; 2721 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); 2722 if (badCFG) 2723 return nullptr; 2724 2725 Block = createBlock(false); 2726 // See if this is a known constant. 2727 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 2728 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock); 2729 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock); 2730 Block->setTerminator(C); 2731 return addStmt(C->getCond()); 2732 } 2733 2734 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C, 2735 bool ExternallyDestructed) { 2736 LocalScope::const_iterator scopeBeginPos = ScopePos; 2737 addLocalScopeForStmt(C); 2738 2739 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) { 2740 // If the body ends with a ReturnStmt, the dtors will be added in 2741 // VisitReturnStmt. 2742 addAutomaticObjHandling(ScopePos, scopeBeginPos, C); 2743 } 2744 2745 CFGBlock *LastBlock = Block; 2746 2747 for (Stmt *S : llvm::reverse(C->body())) { 2748 // If we hit a segment of code just containing ';' (NullStmts), we can 2749 // get a null block back. In such cases, just use the LastBlock 2750 CFGBlock *newBlock = Visit(S, AddStmtChoice::AlwaysAdd, 2751 ExternallyDestructed); 2752 2753 if (newBlock) 2754 LastBlock = newBlock; 2755 2756 if (badCFG) 2757 return nullptr; 2758 2759 ExternallyDestructed = false; 2760 } 2761 2762 return LastBlock; 2763 } 2764 2765 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, 2766 AddStmtChoice asc) { 2767 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); 2768 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr); 2769 2770 // Create the confluence block that will "merge" the results of the ternary 2771 // expression. 2772 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 2773 appendStmt(ConfluenceBlock, C); 2774 if (badCFG) 2775 return nullptr; 2776 2777 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 2778 2779 // Create a block for the LHS expression if there is an LHS expression. A 2780 // GCC extension allows LHS to be NULL, causing the condition to be the 2781 // value that is returned instead. 2782 // e.g: x ?: y is shorthand for: x ? x : y; 2783 Succ = ConfluenceBlock; 2784 Block = nullptr; 2785 CFGBlock *LHSBlock = nullptr; 2786 const Expr *trueExpr = C->getTrueExpr(); 2787 if (trueExpr != opaqueValue) { 2788 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); 2789 if (badCFG) 2790 return nullptr; 2791 Block = nullptr; 2792 } 2793 else 2794 LHSBlock = ConfluenceBlock; 2795 2796 // Create the block for the RHS expression. 2797 Succ = ConfluenceBlock; 2798 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 2799 if (badCFG) 2800 return nullptr; 2801 2802 // If the condition is a logical '&&' or '||', build a more accurate CFG. 2803 if (BinaryOperator *Cond = 2804 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens())) 2805 if (Cond->isLogicalOp()) 2806 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first; 2807 2808 // Create the block that will contain the condition. 2809 Block = createBlock(false); 2810 2811 // See if this is a known constant. 2812 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 2813 addSuccessor(Block, LHSBlock, !KnownVal.isFalse()); 2814 addSuccessor(Block, RHSBlock, !KnownVal.isTrue()); 2815 Block->setTerminator(C); 2816 Expr *condExpr = C->getCond(); 2817 2818 if (opaqueValue) { 2819 // Run the condition expression if it's not trivially expressed in 2820 // terms of the opaque value (or if there is no opaque value). 2821 if (condExpr != opaqueValue) 2822 addStmt(condExpr); 2823 2824 // Before that, run the common subexpression if there was one. 2825 // At least one of this or the above will be run. 2826 return addStmt(BCO->getCommon()); 2827 } 2828 2829 return addStmt(condExpr); 2830 } 2831 2832 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 2833 // Check if the Decl is for an __label__. If so, elide it from the 2834 // CFG entirely. 2835 if (isa<LabelDecl>(*DS->decl_begin())) 2836 return Block; 2837 2838 // This case also handles static_asserts. 2839 if (DS->isSingleDecl()) 2840 return VisitDeclSubExpr(DS); 2841 2842 CFGBlock *B = nullptr; 2843 2844 // Build an individual DeclStmt for each decl. 2845 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(), 2846 E = DS->decl_rend(); 2847 I != E; ++I) { 2848 2849 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 2850 // automatically freed with the CFG. 2851 DeclGroupRef DG(*I); 2852 Decl *D = *I; 2853 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 2854 cfg->addSyntheticDeclStmt(DSNew, DS); 2855 2856 // Append the fake DeclStmt to block. 2857 B = VisitDeclSubExpr(DSNew); 2858 } 2859 2860 return B; 2861 } 2862 2863 /// VisitDeclSubExpr - Utility method to add block-level expressions for 2864 /// DeclStmts and initializers in them. 2865 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { 2866 assert(DS->isSingleDecl() && "Can handle single declarations only."); 2867 2868 if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl())) { 2869 // If we encounter a VLA, process its size expressions. 2870 const Type *T = TND->getUnderlyingType().getTypePtr(); 2871 if (!T->isVariablyModifiedType()) 2872 return Block; 2873 2874 autoCreateBlock(); 2875 appendStmt(Block, DS); 2876 2877 CFGBlock *LastBlock = Block; 2878 for (const VariableArrayType *VA = FindVA(T); VA != nullptr; 2879 VA = FindVA(VA->getElementType().getTypePtr())) { 2880 if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr())) 2881 LastBlock = NewBlock; 2882 } 2883 return LastBlock; 2884 } 2885 2886 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 2887 2888 if (!VD) { 2889 // Of everything that can be declared in a DeclStmt, only VarDecls and the 2890 // exceptions above impact runtime semantics. 2891 return Block; 2892 } 2893 2894 bool HasTemporaries = false; 2895 2896 // Guard static initializers under a branch. 2897 CFGBlock *blockAfterStaticInit = nullptr; 2898 2899 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) { 2900 // For static variables, we need to create a branch to track 2901 // whether or not they are initialized. 2902 if (Block) { 2903 Succ = Block; 2904 Block = nullptr; 2905 if (badCFG) 2906 return nullptr; 2907 } 2908 blockAfterStaticInit = Succ; 2909 } 2910 2911 // Destructors of temporaries in initialization expression should be called 2912 // after initialization finishes. 2913 Expr *Init = VD->getInit(); 2914 if (Init) { 2915 HasTemporaries = isa<ExprWithCleanups>(Init); 2916 2917 if (BuildOpts.AddTemporaryDtors && HasTemporaries) { 2918 // Generate destructors for temporaries in initialization expression. 2919 TempDtorContext Context; 2920 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 2921 /*ExternallyDestructed=*/true, Context); 2922 } 2923 } 2924 2925 autoCreateBlock(); 2926 appendStmt(Block, DS); 2927 2928 findConstructionContexts( 2929 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS), 2930 Init); 2931 2932 // Keep track of the last non-null block, as 'Block' can be nulled out 2933 // if the initializer expression is something like a 'while' in a 2934 // statement-expression. 2935 CFGBlock *LastBlock = Block; 2936 2937 if (Init) { 2938 if (HasTemporaries) { 2939 // For expression with temporaries go directly to subexpression to omit 2940 // generating destructors for the second time. 2941 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init); 2942 if (CFGBlock *newBlock = Visit(EC->getSubExpr())) 2943 LastBlock = newBlock; 2944 } 2945 else { 2946 if (CFGBlock *newBlock = Visit(Init)) 2947 LastBlock = newBlock; 2948 } 2949 } 2950 2951 // If the type of VD is a VLA, then we must process its size expressions. 2952 // FIXME: This does not find the VLA if it is embedded in other types, 2953 // like here: `int (*p_vla)[x];` 2954 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 2955 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) { 2956 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr())) 2957 LastBlock = newBlock; 2958 } 2959 2960 maybeAddScopeBeginForVarDecl(Block, VD, DS); 2961 2962 // Remove variable from local scope. 2963 if (ScopePos && VD == *ScopePos) 2964 ++ScopePos; 2965 2966 CFGBlock *B = LastBlock; 2967 if (blockAfterStaticInit) { 2968 Succ = B; 2969 Block = createBlock(false); 2970 Block->setTerminator(DS); 2971 addSuccessor(Block, blockAfterStaticInit); 2972 addSuccessor(Block, B); 2973 B = Block; 2974 } 2975 2976 return B; 2977 } 2978 2979 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 2980 // We may see an if statement in the middle of a basic block, or it may be the 2981 // first statement we are processing. In either case, we create a new basic 2982 // block. First, we create the blocks for the then...else statements, and 2983 // then we create the block containing the if statement. If we were in the 2984 // middle of a block, we stop processing that block. That block is then the 2985 // implicit successor for the "then" and "else" clauses. 2986 2987 // Save local scope position because in case of condition variable ScopePos 2988 // won't be restored when traversing AST. 2989 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2990 2991 // Create local scope for C++17 if init-stmt if one exists. 2992 if (Stmt *Init = I->getInit()) 2993 addLocalScopeForStmt(Init); 2994 2995 // Create local scope for possible condition variable. 2996 // Store scope position. Add implicit destructor. 2997 if (VarDecl *VD = I->getConditionVariable()) 2998 addLocalScopeForVarDecl(VD); 2999 3000 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I); 3001 3002 // The block we were processing is now finished. Make it the successor 3003 // block. 3004 if (Block) { 3005 Succ = Block; 3006 if (badCFG) 3007 return nullptr; 3008 } 3009 3010 // Process the false branch. 3011 CFGBlock *ElseBlock = Succ; 3012 3013 if (Stmt *Else = I->getElse()) { 3014 SaveAndRestore<CFGBlock*> sv(Succ); 3015 3016 // NULL out Block so that the recursive call to Visit will 3017 // create a new basic block. 3018 Block = nullptr; 3019 3020 // If branch is not a compound statement create implicit scope 3021 // and add destructors. 3022 if (!isa<CompoundStmt>(Else)) 3023 addLocalScopeAndDtors(Else); 3024 3025 ElseBlock = addStmt(Else); 3026 3027 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 3028 ElseBlock = sv.get(); 3029 else if (Block) { 3030 if (badCFG) 3031 return nullptr; 3032 } 3033 } 3034 3035 // Process the true branch. 3036 CFGBlock *ThenBlock; 3037 { 3038 Stmt *Then = I->getThen(); 3039 assert(Then); 3040 SaveAndRestore<CFGBlock*> sv(Succ); 3041 Block = nullptr; 3042 3043 // If branch is not a compound statement create implicit scope 3044 // and add destructors. 3045 if (!isa<CompoundStmt>(Then)) 3046 addLocalScopeAndDtors(Then); 3047 3048 ThenBlock = addStmt(Then); 3049 3050 if (!ThenBlock) { 3051 // We can reach here if the "then" body has all NullStmts. 3052 // Create an empty block so we can distinguish between true and false 3053 // branches in path-sensitive analyses. 3054 ThenBlock = createBlock(false); 3055 addSuccessor(ThenBlock, sv.get()); 3056 } else if (Block) { 3057 if (badCFG) 3058 return nullptr; 3059 } 3060 } 3061 3062 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by 3063 // having these handle the actual control-flow jump. Note that 3064 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)" 3065 // we resort to the old control-flow behavior. This special handling 3066 // removes infeasible paths from the control-flow graph by having the 3067 // control-flow transfer of '&&' or '||' go directly into the then/else 3068 // blocks directly. 3069 BinaryOperator *Cond = 3070 (I->isConsteval() || I->getConditionVariable()) 3071 ? nullptr 3072 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()); 3073 CFGBlock *LastBlock; 3074 if (Cond && Cond->isLogicalOp()) 3075 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first; 3076 else { 3077 // Now create a new block containing the if statement. 3078 Block = createBlock(false); 3079 3080 // Set the terminator of the new block to the If statement. 3081 Block->setTerminator(I); 3082 3083 // See if this is a known constant. 3084 TryResult KnownVal; 3085 if (!I->isConsteval()) 3086 KnownVal = tryEvaluateBool(I->getCond()); 3087 3088 // Add the successors. If we know that specific branches are 3089 // unreachable, inform addSuccessor() of that knowledge. 3090 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse()); 3091 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue()); 3092 3093 // Add the condition as the last statement in the new block. This may 3094 // create new blocks as the condition may contain control-flow. Any newly 3095 // created blocks will be pointed to be "Block". 3096 LastBlock = addStmt(I->getCond()); 3097 3098 // If the IfStmt contains a condition variable, add it and its 3099 // initializer to the CFG. 3100 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) { 3101 autoCreateBlock(); 3102 LastBlock = addStmt(const_cast<DeclStmt *>(DS)); 3103 } 3104 } 3105 3106 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG. 3107 if (Stmt *Init = I->getInit()) { 3108 autoCreateBlock(); 3109 LastBlock = addStmt(Init); 3110 } 3111 3112 return LastBlock; 3113 } 3114 3115 CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) { 3116 // If we were in the middle of a block we stop processing that block. 3117 // 3118 // NOTE: If a "return" or "co_return" appears in the middle of a block, this 3119 // means that the code afterwards is DEAD (unreachable). We still keep 3120 // a basic block for that code; a simple "mark-and-sweep" from the entry 3121 // block will be able to report such dead blocks. 3122 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)); 3123 3124 // Create the new block. 3125 Block = createBlock(false); 3126 3127 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S); 3128 3129 if (auto *R = dyn_cast<ReturnStmt>(S)) 3130 findConstructionContexts( 3131 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R), 3132 R->getRetValue()); 3133 3134 // If the one of the destructors does not return, we already have the Exit 3135 // block as a successor. 3136 if (!Block->hasNoReturnElement()) 3137 addSuccessor(Block, &cfg->getExit()); 3138 3139 // Add the return statement to the block. 3140 appendStmt(Block, S); 3141 3142 // Visit children 3143 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) { 3144 if (Expr *O = RS->getRetValue()) 3145 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true); 3146 return Block; 3147 } 3148 // co_return 3149 return VisitChildren(S); 3150 } 3151 3152 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) { 3153 // SEHExceptStmt are treated like labels, so they are the first statement in a 3154 // block. 3155 3156 // Save local scope position because in case of exception variable ScopePos 3157 // won't be restored when traversing AST. 3158 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3159 3160 addStmt(ES->getBlock()); 3161 CFGBlock *SEHExceptBlock = Block; 3162 if (!SEHExceptBlock) 3163 SEHExceptBlock = createBlock(); 3164 3165 appendStmt(SEHExceptBlock, ES); 3166 3167 // Also add the SEHExceptBlock as a label, like with regular labels. 3168 SEHExceptBlock->setLabel(ES); 3169 3170 // Bail out if the CFG is bad. 3171 if (badCFG) 3172 return nullptr; 3173 3174 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3175 Block = nullptr; 3176 3177 return SEHExceptBlock; 3178 } 3179 3180 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) { 3181 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false); 3182 } 3183 3184 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) { 3185 // "__leave" is a control-flow statement. Thus we stop processing the current 3186 // block. 3187 if (badCFG) 3188 return nullptr; 3189 3190 // Now create a new block that ends with the __leave statement. 3191 Block = createBlock(false); 3192 Block->setTerminator(LS); 3193 3194 // If there is no target for the __leave, then we are looking at an incomplete 3195 // AST. This means that the CFG cannot be constructed. 3196 if (SEHLeaveJumpTarget.block) { 3197 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS); 3198 addSuccessor(Block, SEHLeaveJumpTarget.block); 3199 } else 3200 badCFG = true; 3201 3202 return Block; 3203 } 3204 3205 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) { 3206 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop 3207 // processing the current block. 3208 CFGBlock *SEHTrySuccessor = nullptr; 3209 3210 if (Block) { 3211 if (badCFG) 3212 return nullptr; 3213 SEHTrySuccessor = Block; 3214 } else SEHTrySuccessor = Succ; 3215 3216 // FIXME: Implement __finally support. 3217 if (Terminator->getFinallyHandler()) 3218 return NYS(); 3219 3220 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock; 3221 3222 // Create a new block that will contain the __try statement. 3223 CFGBlock *NewTryTerminatedBlock = createBlock(false); 3224 3225 // Add the terminator in the __try block. 3226 NewTryTerminatedBlock->setTerminator(Terminator); 3227 3228 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) { 3229 // The code after the try is the implicit successor if there's an __except. 3230 Succ = SEHTrySuccessor; 3231 Block = nullptr; 3232 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except); 3233 if (!ExceptBlock) 3234 return nullptr; 3235 // Add this block to the list of successors for the block with the try 3236 // statement. 3237 addSuccessor(NewTryTerminatedBlock, ExceptBlock); 3238 } 3239 if (PrevSEHTryTerminatedBlock) 3240 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock); 3241 else 3242 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 3243 3244 // The code after the try is the implicit successor. 3245 Succ = SEHTrySuccessor; 3246 3247 // Save the current "__try" context. 3248 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 3249 cfg->addTryDispatchBlock(TryTerminatedBlock); 3250 3251 // Save the current value for the __leave target. 3252 // All __leaves should go to the code following the __try 3253 // (FIXME: or if the __try has a __finally, to the __finally.) 3254 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget); 3255 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos); 3256 3257 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body"); 3258 Block = nullptr; 3259 return addStmt(Terminator->getTryBlock()); 3260 } 3261 3262 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 3263 // Get the block of the labeled statement. Add it to our map. 3264 addStmt(L->getSubStmt()); 3265 CFGBlock *LabelBlock = Block; 3266 3267 if (!LabelBlock) // This can happen when the body is empty, i.e. 3268 LabelBlock = createBlock(); // scopes that only contains NullStmts. 3269 3270 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 3271 "label already in map"); 3272 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 3273 3274 // Labels partition blocks, so this is the end of the basic block we were 3275 // processing (L is the block's label). Because this is label (and we have 3276 // already processed the substatement) there is no extra control-flow to worry 3277 // about. 3278 LabelBlock->setLabel(L); 3279 if (badCFG) 3280 return nullptr; 3281 3282 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3283 Block = nullptr; 3284 3285 // This block is now the implicit successor of other blocks. 3286 Succ = LabelBlock; 3287 3288 return LabelBlock; 3289 } 3290 3291 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 3292 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 3293 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) { 3294 if (Expr *CopyExpr = CI.getCopyExpr()) { 3295 CFGBlock *Tmp = Visit(CopyExpr); 3296 if (Tmp) 3297 LastBlock = Tmp; 3298 } 3299 } 3300 return LastBlock; 3301 } 3302 3303 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { 3304 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 3305 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(), 3306 et = E->capture_init_end(); it != et; ++it) { 3307 if (Expr *Init = *it) { 3308 CFGBlock *Tmp = Visit(Init); 3309 if (Tmp) 3310 LastBlock = Tmp; 3311 } 3312 } 3313 return LastBlock; 3314 } 3315 3316 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 3317 // Goto is a control-flow statement. Thus we stop processing the current 3318 // block and create a new one. 3319 3320 Block = createBlock(false); 3321 Block->setTerminator(G); 3322 3323 // If we already know the mapping to the label block add the successor now. 3324 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 3325 3326 if (I == LabelMap.end()) 3327 // We will need to backpatch this block later. 3328 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 3329 else { 3330 JumpTarget JT = I->second; 3331 addAutomaticObjHandling(ScopePos, JT.scopePosition, G); 3332 addSuccessor(Block, JT.block); 3333 } 3334 3335 return Block; 3336 } 3337 3338 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) { 3339 // Goto is a control-flow statement. Thus we stop processing the current 3340 // block and create a new one. 3341 3342 if (!G->isAsmGoto()) 3343 return VisitStmt(G, asc); 3344 3345 if (Block) { 3346 Succ = Block; 3347 if (badCFG) 3348 return nullptr; 3349 } 3350 Block = createBlock(); 3351 Block->setTerminator(G); 3352 // We will backpatch this block later for all the labels. 3353 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 3354 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is 3355 // used to avoid adding "Succ" again. 3356 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos)); 3357 return Block; 3358 } 3359 3360 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 3361 CFGBlock *LoopSuccessor = nullptr; 3362 3363 // Save local scope position because in case of condition variable ScopePos 3364 // won't be restored when traversing AST. 3365 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3366 3367 // Create local scope for init statement and possible condition variable. 3368 // Add destructor for init statement and condition variable. 3369 // Store scope position for continue statement. 3370 if (Stmt *Init = F->getInit()) 3371 addLocalScopeForStmt(Init); 3372 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 3373 3374 if (VarDecl *VD = F->getConditionVariable()) 3375 addLocalScopeForVarDecl(VD); 3376 LocalScope::const_iterator ContinueScopePos = ScopePos; 3377 3378 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F); 3379 3380 addLoopExit(F); 3381 3382 // "for" is a control-flow statement. Thus we stop processing the current 3383 // block. 3384 if (Block) { 3385 if (badCFG) 3386 return nullptr; 3387 LoopSuccessor = Block; 3388 } else 3389 LoopSuccessor = Succ; 3390 3391 // Save the current value for the break targets. 3392 // All breaks should go to the code following the loop. 3393 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 3394 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3395 3396 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 3397 3398 // Now create the loop body. 3399 { 3400 assert(F->getBody()); 3401 3402 // Save the current values for Block, Succ, continue and break targets. 3403 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3404 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 3405 3406 // Create an empty block to represent the transition block for looping back 3407 // to the head of the loop. If we have increment code, it will 3408 // go in this block as well. 3409 Block = Succ = TransitionBlock = createBlock(false); 3410 TransitionBlock->setLoopTarget(F); 3411 3412 if (Stmt *I = F->getInc()) { 3413 // Generate increment code in its own basic block. This is the target of 3414 // continue statements. 3415 Succ = addStmt(I); 3416 } 3417 3418 // Finish up the increment (or empty) block if it hasn't been already. 3419 if (Block) { 3420 assert(Block == Succ); 3421 if (badCFG) 3422 return nullptr; 3423 Block = nullptr; 3424 } 3425 3426 // The starting block for the loop increment is the block that should 3427 // represent the 'loop target' for looping back to the start of the loop. 3428 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 3429 ContinueJumpTarget.block->setLoopTarget(F); 3430 3431 // Loop body should end with destructor of Condition variable (if any). 3432 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F); 3433 3434 // If body is not a compound statement create implicit scope 3435 // and add destructors. 3436 if (!isa<CompoundStmt>(F->getBody())) 3437 addLocalScopeAndDtors(F->getBody()); 3438 3439 // Now populate the body block, and in the process create new blocks as we 3440 // walk the body of the loop. 3441 BodyBlock = addStmt(F->getBody()); 3442 3443 if (!BodyBlock) { 3444 // In the case of "for (...;...;...);" we can have a null BodyBlock. 3445 // Use the continue jump target as the proxy for the body. 3446 BodyBlock = ContinueJumpTarget.block; 3447 } 3448 else if (badCFG) 3449 return nullptr; 3450 } 3451 3452 // Because of short-circuit evaluation, the condition of the loop can span 3453 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3454 // evaluate the condition. 3455 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 3456 3457 do { 3458 Expr *C = F->getCond(); 3459 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3460 3461 // Specially handle logical operators, which have a slightly 3462 // more optimal CFG representation. 3463 if (BinaryOperator *Cond = 3464 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr)) 3465 if (Cond->isLogicalOp()) { 3466 std::tie(EntryConditionBlock, ExitConditionBlock) = 3467 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor); 3468 break; 3469 } 3470 3471 // The default case when not handling logical operators. 3472 EntryConditionBlock = ExitConditionBlock = createBlock(false); 3473 ExitConditionBlock->setTerminator(F); 3474 3475 // See if this is a known constant. 3476 TryResult KnownVal(true); 3477 3478 if (C) { 3479 // Now add the actual condition to the condition block. 3480 // Because the condition itself may contain control-flow, new blocks may 3481 // be created. Thus we update "Succ" after adding the condition. 3482 Block = ExitConditionBlock; 3483 EntryConditionBlock = addStmt(C); 3484 3485 // If this block contains a condition variable, add both the condition 3486 // variable and initializer to the CFG. 3487 if (VarDecl *VD = F->getConditionVariable()) { 3488 if (Expr *Init = VD->getInit()) { 3489 autoCreateBlock(); 3490 const DeclStmt *DS = F->getConditionVariableDeclStmt(); 3491 assert(DS->isSingleDecl()); 3492 findConstructionContexts( 3493 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS), 3494 Init); 3495 appendStmt(Block, DS); 3496 EntryConditionBlock = addStmt(Init); 3497 assert(Block == EntryConditionBlock); 3498 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C); 3499 } 3500 } 3501 3502 if (Block && badCFG) 3503 return nullptr; 3504 3505 KnownVal = tryEvaluateBool(C); 3506 } 3507 3508 // Add the loop body entry as a successor to the condition. 3509 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 3510 // Link up the condition block with the code that follows the loop. (the 3511 // false branch). 3512 addSuccessor(ExitConditionBlock, 3513 KnownVal.isTrue() ? nullptr : LoopSuccessor); 3514 } while (false); 3515 3516 // Link up the loop-back block to the entry condition block. 3517 addSuccessor(TransitionBlock, EntryConditionBlock); 3518 3519 // The condition block is the implicit successor for any code above the loop. 3520 Succ = EntryConditionBlock; 3521 3522 // If the loop contains initialization, create a new block for those 3523 // statements. This block can also contain statements that precede the loop. 3524 if (Stmt *I = F->getInit()) { 3525 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3526 ScopePos = LoopBeginScopePos; 3527 Block = createBlock(); 3528 return addStmt(I); 3529 } 3530 3531 // There is no loop initialization. We are thus basically a while loop. 3532 // NULL out Block to force lazy block construction. 3533 Block = nullptr; 3534 Succ = EntryConditionBlock; 3535 return EntryConditionBlock; 3536 } 3537 3538 CFGBlock * 3539 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE, 3540 AddStmtChoice asc) { 3541 findConstructionContexts( 3542 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE), 3543 MTE->getSubExpr()); 3544 3545 return VisitStmt(MTE, asc); 3546 } 3547 3548 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 3549 if (asc.alwaysAdd(*this, M)) { 3550 autoCreateBlock(); 3551 appendStmt(Block, M); 3552 } 3553 return Visit(M->getBase()); 3554 } 3555 3556 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 3557 // Objective-C fast enumeration 'for' statements: 3558 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 3559 // 3560 // for ( Type newVariable in collection_expression ) { statements } 3561 // 3562 // becomes: 3563 // 3564 // prologue: 3565 // 1. collection_expression 3566 // T. jump to loop_entry 3567 // loop_entry: 3568 // 1. side-effects of element expression 3569 // 1. ObjCForCollectionStmt [performs binding to newVariable] 3570 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 3571 // TB: 3572 // statements 3573 // T. jump to loop_entry 3574 // FB: 3575 // what comes after 3576 // 3577 // and 3578 // 3579 // Type existingItem; 3580 // for ( existingItem in expression ) { statements } 3581 // 3582 // becomes: 3583 // 3584 // the same with newVariable replaced with existingItem; the binding works 3585 // the same except that for one ObjCForCollectionStmt::getElement() returns 3586 // a DeclStmt and the other returns a DeclRefExpr. 3587 3588 CFGBlock *LoopSuccessor = nullptr; 3589 3590 if (Block) { 3591 if (badCFG) 3592 return nullptr; 3593 LoopSuccessor = Block; 3594 Block = nullptr; 3595 } else 3596 LoopSuccessor = Succ; 3597 3598 // Build the condition blocks. 3599 CFGBlock *ExitConditionBlock = createBlock(false); 3600 3601 // Set the terminator for the "exit" condition block. 3602 ExitConditionBlock->setTerminator(S); 3603 3604 // The last statement in the block should be the ObjCForCollectionStmt, which 3605 // performs the actual binding to 'element' and determines if there are any 3606 // more items in the collection. 3607 appendStmt(ExitConditionBlock, S); 3608 Block = ExitConditionBlock; 3609 3610 // Walk the 'element' expression to see if there are any side-effects. We 3611 // generate new blocks as necessary. We DON'T add the statement by default to 3612 // the CFG unless it contains control-flow. 3613 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 3614 AddStmtChoice::NotAlwaysAdd); 3615 if (Block) { 3616 if (badCFG) 3617 return nullptr; 3618 Block = nullptr; 3619 } 3620 3621 // The condition block is the implicit successor for the loop body as well as 3622 // any code above the loop. 3623 Succ = EntryConditionBlock; 3624 3625 // Now create the true branch. 3626 { 3627 // Save the current values for Succ, continue and break targets. 3628 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3629 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3630 save_break(BreakJumpTarget); 3631 3632 // Add an intermediate block between the BodyBlock and the 3633 // EntryConditionBlock to represent the "loop back" transition, for looping 3634 // back to the head of the loop. 3635 CFGBlock *LoopBackBlock = nullptr; 3636 Succ = LoopBackBlock = createBlock(); 3637 LoopBackBlock->setLoopTarget(S); 3638 3639 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3640 ContinueJumpTarget = JumpTarget(Succ, ScopePos); 3641 3642 CFGBlock *BodyBlock = addStmt(S->getBody()); 3643 3644 if (!BodyBlock) 3645 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;" 3646 else if (Block) { 3647 if (badCFG) 3648 return nullptr; 3649 } 3650 3651 // This new body block is a successor to our "exit" condition block. 3652 addSuccessor(ExitConditionBlock, BodyBlock); 3653 } 3654 3655 // Link up the condition block with the code that follows the loop. 3656 // (the false branch). 3657 addSuccessor(ExitConditionBlock, LoopSuccessor); 3658 3659 // Now create a prologue block to contain the collection expression. 3660 Block = createBlock(); 3661 return addStmt(S->getCollection()); 3662 } 3663 3664 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 3665 // Inline the body. 3666 return addStmt(S->getSubStmt()); 3667 // TODO: consider adding cleanups for the end of @autoreleasepool scope. 3668 } 3669 3670 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 3671 // FIXME: Add locking 'primitives' to CFG for @synchronized. 3672 3673 // Inline the body. 3674 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 3675 3676 // The sync body starts its own basic block. This makes it a little easier 3677 // for diagnostic clients. 3678 if (SyncBlock) { 3679 if (badCFG) 3680 return nullptr; 3681 3682 Block = nullptr; 3683 Succ = SyncBlock; 3684 } 3685 3686 // Add the @synchronized to the CFG. 3687 autoCreateBlock(); 3688 appendStmt(Block, S); 3689 3690 // Inline the sync expression. 3691 return addStmt(S->getSynchExpr()); 3692 } 3693 3694 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 3695 autoCreateBlock(); 3696 3697 // Add the PseudoObject as the last thing. 3698 appendStmt(Block, E); 3699 3700 CFGBlock *lastBlock = Block; 3701 3702 // Before that, evaluate all of the semantics in order. In 3703 // CFG-land, that means appending them in reverse order. 3704 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { 3705 Expr *Semantic = E->getSemanticExpr(--i); 3706 3707 // If the semantic is an opaque value, we're being asked to bind 3708 // it to its source expression. 3709 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 3710 Semantic = OVE->getSourceExpr(); 3711 3712 if (CFGBlock *B = Visit(Semantic)) 3713 lastBlock = B; 3714 } 3715 3716 return lastBlock; 3717 } 3718 3719 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 3720 CFGBlock *LoopSuccessor = nullptr; 3721 3722 // Save local scope position because in case of condition variable ScopePos 3723 // won't be restored when traversing AST. 3724 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3725 3726 // Create local scope for possible condition variable. 3727 // Store scope position for continue statement. 3728 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 3729 if (VarDecl *VD = W->getConditionVariable()) { 3730 addLocalScopeForVarDecl(VD); 3731 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3732 } 3733 addLoopExit(W); 3734 3735 // "while" is a control-flow statement. Thus we stop processing the current 3736 // block. 3737 if (Block) { 3738 if (badCFG) 3739 return nullptr; 3740 LoopSuccessor = Block; 3741 Block = nullptr; 3742 } else { 3743 LoopSuccessor = Succ; 3744 } 3745 3746 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr; 3747 3748 // Process the loop body. 3749 { 3750 assert(W->getBody()); 3751 3752 // Save the current values for Block, Succ, continue and break targets. 3753 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 3754 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 3755 save_break(BreakJumpTarget); 3756 3757 // Create an empty block to represent the transition block for looping back 3758 // to the head of the loop. 3759 Succ = TransitionBlock = createBlock(false); 3760 TransitionBlock->setLoopTarget(W); 3761 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 3762 3763 // All breaks should go to the code following the loop. 3764 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 3765 3766 // Loop body should end with destructor of Condition variable (if any). 3767 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W); 3768 3769 // If body is not a compound statement create implicit scope 3770 // and add destructors. 3771 if (!isa<CompoundStmt>(W->getBody())) 3772 addLocalScopeAndDtors(W->getBody()); 3773 3774 // Create the body. The returned block is the entry to the loop body. 3775 BodyBlock = addStmt(W->getBody()); 3776 3777 if (!BodyBlock) 3778 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 3779 else if (Block && badCFG) 3780 return nullptr; 3781 } 3782 3783 // Because of short-circuit evaluation, the condition of the loop can span 3784 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 3785 // evaluate the condition. 3786 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr; 3787 3788 do { 3789 Expr *C = W->getCond(); 3790 3791 // Specially handle logical operators, which have a slightly 3792 // more optimal CFG representation. 3793 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens())) 3794 if (Cond->isLogicalOp()) { 3795 std::tie(EntryConditionBlock, ExitConditionBlock) = 3796 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor); 3797 break; 3798 } 3799 3800 // The default case when not handling logical operators. 3801 ExitConditionBlock = createBlock(false); 3802 ExitConditionBlock->setTerminator(W); 3803 3804 // Now add the actual condition to the condition block. 3805 // Because the condition itself may contain control-flow, new blocks may 3806 // be created. Thus we update "Succ" after adding the condition. 3807 Block = ExitConditionBlock; 3808 Block = EntryConditionBlock = addStmt(C); 3809 3810 // If this block contains a condition variable, add both the condition 3811 // variable and initializer to the CFG. 3812 if (VarDecl *VD = W->getConditionVariable()) { 3813 if (Expr *Init = VD->getInit()) { 3814 autoCreateBlock(); 3815 const DeclStmt *DS = W->getConditionVariableDeclStmt(); 3816 assert(DS->isSingleDecl()); 3817 findConstructionContexts( 3818 ConstructionContextLayer::create(cfg->getBumpVectorContext(), 3819 const_cast<DeclStmt *>(DS)), 3820 Init); 3821 appendStmt(Block, DS); 3822 EntryConditionBlock = addStmt(Init); 3823 assert(Block == EntryConditionBlock); 3824 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C); 3825 } 3826 } 3827 3828 if (Block && badCFG) 3829 return nullptr; 3830 3831 // See if this is a known constant. 3832 const TryResult& KnownVal = tryEvaluateBool(C); 3833 3834 // Add the loop body entry as a successor to the condition. 3835 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock); 3836 // Link up the condition block with the code that follows the loop. (the 3837 // false branch). 3838 addSuccessor(ExitConditionBlock, 3839 KnownVal.isTrue() ? nullptr : LoopSuccessor); 3840 } while(false); 3841 3842 // Link up the loop-back block to the entry condition block. 3843 addSuccessor(TransitionBlock, EntryConditionBlock); 3844 3845 // There can be no more statements in the condition block since we loop back 3846 // to this block. NULL out Block to force lazy creation of another block. 3847 Block = nullptr; 3848 3849 // Return the condition block, which is the dominating block for the loop. 3850 Succ = EntryConditionBlock; 3851 return EntryConditionBlock; 3852 } 3853 3854 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) { 3855 // ObjCAtCatchStmt are treated like labels, so they are the first statement 3856 // in a block. 3857 3858 // Save local scope position because in case of exception variable ScopePos 3859 // won't be restored when traversing AST. 3860 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 3861 3862 if (CS->getCatchBody()) 3863 addStmt(CS->getCatchBody()); 3864 3865 CFGBlock *CatchBlock = Block; 3866 if (!CatchBlock) 3867 CatchBlock = createBlock(); 3868 3869 appendStmt(CatchBlock, CS); 3870 3871 // Also add the ObjCAtCatchStmt as a label, like with regular labels. 3872 CatchBlock->setLabel(CS); 3873 3874 // Bail out if the CFG is bad. 3875 if (badCFG) 3876 return nullptr; 3877 3878 // We set Block to NULL to allow lazy creation of a new block (if necessary). 3879 Block = nullptr; 3880 3881 return CatchBlock; 3882 } 3883 3884 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 3885 // If we were in the middle of a block we stop processing that block. 3886 if (badCFG) 3887 return nullptr; 3888 3889 // Create the new block. 3890 Block = createBlock(false); 3891 3892 if (TryTerminatedBlock) 3893 // The current try statement is the only successor. 3894 addSuccessor(Block, TryTerminatedBlock); 3895 else 3896 // otherwise the Exit block is the only successor. 3897 addSuccessor(Block, &cfg->getExit()); 3898 3899 // Add the statement to the block. This may create new blocks if S contains 3900 // control-flow (short-circuit operations). 3901 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 3902 } 3903 3904 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) { 3905 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the 3906 // current block. 3907 CFGBlock *TrySuccessor = nullptr; 3908 3909 if (Block) { 3910 if (badCFG) 3911 return nullptr; 3912 TrySuccessor = Block; 3913 } else 3914 TrySuccessor = Succ; 3915 3916 // FIXME: Implement @finally support. 3917 if (Terminator->getFinallyStmt()) 3918 return NYS(); 3919 3920 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 3921 3922 // Create a new block that will contain the try statement. 3923 CFGBlock *NewTryTerminatedBlock = createBlock(false); 3924 // Add the terminator in the try block. 3925 NewTryTerminatedBlock->setTerminator(Terminator); 3926 3927 bool HasCatchAll = false; 3928 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) { 3929 // The code after the try is the implicit successor. 3930 Succ = TrySuccessor; 3931 if (CS->hasEllipsis()) { 3932 HasCatchAll = true; 3933 } 3934 Block = nullptr; 3935 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS); 3936 if (!CatchBlock) 3937 return nullptr; 3938 // Add this block to the list of successors for the block with the try 3939 // statement. 3940 addSuccessor(NewTryTerminatedBlock, CatchBlock); 3941 } 3942 3943 // FIXME: This needs updating when @finally support is added. 3944 if (!HasCatchAll) { 3945 if (PrevTryTerminatedBlock) 3946 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 3947 else 3948 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 3949 } 3950 3951 // The code after the try is the implicit successor. 3952 Succ = TrySuccessor; 3953 3954 // Save the current "try" context. 3955 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 3956 cfg->addTryDispatchBlock(TryTerminatedBlock); 3957 3958 assert(Terminator->getTryBody() && "try must contain a non-NULL body"); 3959 Block = nullptr; 3960 return addStmt(Terminator->getTryBody()); 3961 } 3962 3963 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME, 3964 AddStmtChoice asc) { 3965 findConstructionContextsForArguments(ME); 3966 3967 autoCreateBlock(); 3968 appendObjCMessage(Block, ME); 3969 3970 return VisitChildren(ME); 3971 } 3972 3973 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 3974 // If we were in the middle of a block we stop processing that block. 3975 if (badCFG) 3976 return nullptr; 3977 3978 // Create the new block. 3979 Block = createBlock(false); 3980 3981 if (TryTerminatedBlock) 3982 // The current try statement is the only successor. 3983 addSuccessor(Block, TryTerminatedBlock); 3984 else 3985 // otherwise the Exit block is the only successor. 3986 addSuccessor(Block, &cfg->getExit()); 3987 3988 // Add the statement to the block. This may create new blocks if S contains 3989 // control-flow (short-circuit operations). 3990 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 3991 } 3992 3993 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 3994 CFGBlock *LoopSuccessor = nullptr; 3995 3996 addLoopExit(D); 3997 3998 // "do...while" is a control-flow statement. Thus we stop processing the 3999 // current block. 4000 if (Block) { 4001 if (badCFG) 4002 return nullptr; 4003 LoopSuccessor = Block; 4004 } else 4005 LoopSuccessor = Succ; 4006 4007 // Because of short-circuit evaluation, the condition of the loop can span 4008 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 4009 // evaluate the condition. 4010 CFGBlock *ExitConditionBlock = createBlock(false); 4011 CFGBlock *EntryConditionBlock = ExitConditionBlock; 4012 4013 // Set the terminator for the "exit" condition block. 4014 ExitConditionBlock->setTerminator(D); 4015 4016 // Now add the actual condition to the condition block. Because the condition 4017 // itself may contain control-flow, new blocks may be created. 4018 if (Stmt *C = D->getCond()) { 4019 Block = ExitConditionBlock; 4020 EntryConditionBlock = addStmt(C); 4021 if (Block) { 4022 if (badCFG) 4023 return nullptr; 4024 } 4025 } 4026 4027 // The condition block is the implicit successor for the loop body. 4028 Succ = EntryConditionBlock; 4029 4030 // See if this is a known constant. 4031 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 4032 4033 // Process the loop body. 4034 CFGBlock *BodyBlock = nullptr; 4035 { 4036 assert(D->getBody()); 4037 4038 // Save the current values for Block, Succ, and continue and break targets 4039 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 4040 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 4041 save_break(BreakJumpTarget); 4042 4043 // All continues within this loop should go to the condition block 4044 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 4045 4046 // All breaks should go to the code following the loop. 4047 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 4048 4049 // NULL out Block to force lazy instantiation of blocks for the body. 4050 Block = nullptr; 4051 4052 // If body is not a compound statement create implicit scope 4053 // and add destructors. 4054 if (!isa<CompoundStmt>(D->getBody())) 4055 addLocalScopeAndDtors(D->getBody()); 4056 4057 // Create the body. The returned block is the entry to the loop body. 4058 BodyBlock = addStmt(D->getBody()); 4059 4060 if (!BodyBlock) 4061 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 4062 else if (Block) { 4063 if (badCFG) 4064 return nullptr; 4065 } 4066 4067 // Add an intermediate block between the BodyBlock and the 4068 // ExitConditionBlock to represent the "loop back" transition. Create an 4069 // empty block to represent the transition block for looping back to the 4070 // head of the loop. 4071 // FIXME: Can we do this more efficiently without adding another block? 4072 Block = nullptr; 4073 Succ = BodyBlock; 4074 CFGBlock *LoopBackBlock = createBlock(); 4075 LoopBackBlock->setLoopTarget(D); 4076 4077 if (!KnownVal.isFalse()) 4078 // Add the loop body entry as a successor to the condition. 4079 addSuccessor(ExitConditionBlock, LoopBackBlock); 4080 else 4081 addSuccessor(ExitConditionBlock, nullptr); 4082 } 4083 4084 // Link up the condition block with the code that follows the loop. 4085 // (the false branch). 4086 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 4087 4088 // There can be no more statements in the body block(s) since we loop back to 4089 // the body. NULL out Block to force lazy creation of another block. 4090 Block = nullptr; 4091 4092 // Return the loop body, which is the dominating block for the loop. 4093 Succ = BodyBlock; 4094 return BodyBlock; 4095 } 4096 4097 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 4098 // "continue" is a control-flow statement. Thus we stop processing the 4099 // current block. 4100 if (badCFG) 4101 return nullptr; 4102 4103 // Now create a new block that ends with the continue statement. 4104 Block = createBlock(false); 4105 Block->setTerminator(C); 4106 4107 // If there is no target for the continue, then we are looking at an 4108 // incomplete AST. This means the CFG cannot be constructed. 4109 if (ContinueJumpTarget.block) { 4110 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C); 4111 addSuccessor(Block, ContinueJumpTarget.block); 4112 } else 4113 badCFG = true; 4114 4115 return Block; 4116 } 4117 4118 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 4119 AddStmtChoice asc) { 4120 if (asc.alwaysAdd(*this, E)) { 4121 autoCreateBlock(); 4122 appendStmt(Block, E); 4123 } 4124 4125 // VLA types have expressions that must be evaluated. 4126 // Evaluation is done only for `sizeof`. 4127 4128 if (E->getKind() != UETT_SizeOf) 4129 return Block; 4130 4131 CFGBlock *lastBlock = Block; 4132 4133 if (E->isArgumentType()) { 4134 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 4135 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) 4136 lastBlock = addStmt(VA->getSizeExpr()); 4137 } 4138 return lastBlock; 4139 } 4140 4141 /// VisitStmtExpr - Utility method to handle (nested) statement 4142 /// expressions (a GCC extension). 4143 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 4144 if (asc.alwaysAdd(*this, SE)) { 4145 autoCreateBlock(); 4146 appendStmt(Block, SE); 4147 } 4148 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true); 4149 } 4150 4151 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 4152 // "switch" is a control-flow statement. Thus we stop processing the current 4153 // block. 4154 CFGBlock *SwitchSuccessor = nullptr; 4155 4156 // Save local scope position because in case of condition variable ScopePos 4157 // won't be restored when traversing AST. 4158 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4159 4160 // Create local scope for C++17 switch init-stmt if one exists. 4161 if (Stmt *Init = Terminator->getInit()) 4162 addLocalScopeForStmt(Init); 4163 4164 // Create local scope for possible condition variable. 4165 // Store scope position. Add implicit destructor. 4166 if (VarDecl *VD = Terminator->getConditionVariable()) 4167 addLocalScopeForVarDecl(VD); 4168 4169 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator); 4170 4171 if (Block) { 4172 if (badCFG) 4173 return nullptr; 4174 SwitchSuccessor = Block; 4175 } else SwitchSuccessor = Succ; 4176 4177 // Save the current "switch" context. 4178 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 4179 save_default(DefaultCaseBlock); 4180 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 4181 4182 // Set the "default" case to be the block after the switch statement. If the 4183 // switch statement contains a "default:", this value will be overwritten with 4184 // the block for that code. 4185 DefaultCaseBlock = SwitchSuccessor; 4186 4187 // Create a new block that will contain the switch statement. 4188 SwitchTerminatedBlock = createBlock(false); 4189 4190 // Now process the switch body. The code after the switch is the implicit 4191 // successor. 4192 Succ = SwitchSuccessor; 4193 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 4194 4195 // When visiting the body, the case statements should automatically get linked 4196 // up to the switch. We also don't keep a pointer to the body, since all 4197 // control-flow from the switch goes to case/default statements. 4198 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 4199 Block = nullptr; 4200 4201 // For pruning unreachable case statements, save the current state 4202 // for tracking the condition value. 4203 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 4204 false); 4205 4206 // Determine if the switch condition can be explicitly evaluated. 4207 assert(Terminator->getCond() && "switch condition must be non-NULL"); 4208 Expr::EvalResult result; 4209 bool b = tryEvaluate(Terminator->getCond(), result); 4210 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 4211 b ? &result : nullptr); 4212 4213 // If body is not a compound statement create implicit scope 4214 // and add destructors. 4215 if (!isa<CompoundStmt>(Terminator->getBody())) 4216 addLocalScopeAndDtors(Terminator->getBody()); 4217 4218 addStmt(Terminator->getBody()); 4219 if (Block) { 4220 if (badCFG) 4221 return nullptr; 4222 } 4223 4224 // If we have no "default:" case, the default transition is to the code 4225 // following the switch body. Moreover, take into account if all the 4226 // cases of a switch are covered (e.g., switching on an enum value). 4227 // 4228 // Note: We add a successor to a switch that is considered covered yet has no 4229 // case statements if the enumeration has no enumerators. 4230 bool SwitchAlwaysHasSuccessor = false; 4231 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered; 4232 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() && 4233 Terminator->getSwitchCaseList(); 4234 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock, 4235 !SwitchAlwaysHasSuccessor); 4236 4237 // Add the terminator and condition in the switch block. 4238 SwitchTerminatedBlock->setTerminator(Terminator); 4239 Block = SwitchTerminatedBlock; 4240 CFGBlock *LastBlock = addStmt(Terminator->getCond()); 4241 4242 // If the SwitchStmt contains a condition variable, add both the 4243 // SwitchStmt and the condition variable initialization to the CFG. 4244 if (VarDecl *VD = Terminator->getConditionVariable()) { 4245 if (Expr *Init = VD->getInit()) { 4246 autoCreateBlock(); 4247 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 4248 LastBlock = addStmt(Init); 4249 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init); 4250 } 4251 } 4252 4253 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG. 4254 if (Stmt *Init = Terminator->getInit()) { 4255 autoCreateBlock(); 4256 LastBlock = addStmt(Init); 4257 } 4258 4259 return LastBlock; 4260 } 4261 4262 static bool shouldAddCase(bool &switchExclusivelyCovered, 4263 const Expr::EvalResult *switchCond, 4264 const CaseStmt *CS, 4265 ASTContext &Ctx) { 4266 if (!switchCond) 4267 return true; 4268 4269 bool addCase = false; 4270 4271 if (!switchExclusivelyCovered) { 4272 if (switchCond->Val.isInt()) { 4273 // Evaluate the LHS of the case value. 4274 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); 4275 const llvm::APSInt &condInt = switchCond->Val.getInt(); 4276 4277 if (condInt == lhsInt) { 4278 addCase = true; 4279 switchExclusivelyCovered = true; 4280 } 4281 else if (condInt > lhsInt) { 4282 if (const Expr *RHS = CS->getRHS()) { 4283 // Evaluate the RHS of the case value. 4284 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); 4285 if (V2 >= condInt) { 4286 addCase = true; 4287 switchExclusivelyCovered = true; 4288 } 4289 } 4290 } 4291 } 4292 else 4293 addCase = true; 4294 } 4295 return addCase; 4296 } 4297 4298 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 4299 // CaseStmts are essentially labels, so they are the first statement in a 4300 // block. 4301 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr; 4302 4303 if (Stmt *Sub = CS->getSubStmt()) { 4304 // For deeply nested chains of CaseStmts, instead of doing a recursion 4305 // (which can blow out the stack), manually unroll and create blocks 4306 // along the way. 4307 while (isa<CaseStmt>(Sub)) { 4308 CFGBlock *currentBlock = createBlock(false); 4309 currentBlock->setLabel(CS); 4310 4311 if (TopBlock) 4312 addSuccessor(LastBlock, currentBlock); 4313 else 4314 TopBlock = currentBlock; 4315 4316 addSuccessor(SwitchTerminatedBlock, 4317 shouldAddCase(switchExclusivelyCovered, switchCond, 4318 CS, *Context) 4319 ? currentBlock : nullptr); 4320 4321 LastBlock = currentBlock; 4322 CS = cast<CaseStmt>(Sub); 4323 Sub = CS->getSubStmt(); 4324 } 4325 4326 addStmt(Sub); 4327 } 4328 4329 CFGBlock *CaseBlock = Block; 4330 if (!CaseBlock) 4331 CaseBlock = createBlock(); 4332 4333 // Cases statements partition blocks, so this is the top of the basic block we 4334 // were processing (the "case XXX:" is the label). 4335 CaseBlock->setLabel(CS); 4336 4337 if (badCFG) 4338 return nullptr; 4339 4340 // Add this block to the list of successors for the block with the switch 4341 // statement. 4342 assert(SwitchTerminatedBlock); 4343 addSuccessor(SwitchTerminatedBlock, CaseBlock, 4344 shouldAddCase(switchExclusivelyCovered, switchCond, 4345 CS, *Context)); 4346 4347 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4348 Block = nullptr; 4349 4350 if (TopBlock) { 4351 addSuccessor(LastBlock, CaseBlock); 4352 Succ = TopBlock; 4353 } else { 4354 // This block is now the implicit successor of other blocks. 4355 Succ = CaseBlock; 4356 } 4357 4358 return Succ; 4359 } 4360 4361 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 4362 if (Terminator->getSubStmt()) 4363 addStmt(Terminator->getSubStmt()); 4364 4365 DefaultCaseBlock = Block; 4366 4367 if (!DefaultCaseBlock) 4368 DefaultCaseBlock = createBlock(); 4369 4370 // Default statements partition blocks, so this is the top of the basic block 4371 // we were processing (the "default:" is the label). 4372 DefaultCaseBlock->setLabel(Terminator); 4373 4374 if (badCFG) 4375 return nullptr; 4376 4377 // Unlike case statements, we don't add the default block to the successors 4378 // for the switch statement immediately. This is done when we finish 4379 // processing the switch statement. This allows for the default case 4380 // (including a fall-through to the code after the switch statement) to always 4381 // be the last successor of a switch-terminated block. 4382 4383 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4384 Block = nullptr; 4385 4386 // This block is now the implicit successor of other blocks. 4387 Succ = DefaultCaseBlock; 4388 4389 return DefaultCaseBlock; 4390 } 4391 4392 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 4393 // "try"/"catch" is a control-flow statement. Thus we stop processing the 4394 // current block. 4395 CFGBlock *TrySuccessor = nullptr; 4396 4397 if (Block) { 4398 if (badCFG) 4399 return nullptr; 4400 TrySuccessor = Block; 4401 } else 4402 TrySuccessor = Succ; 4403 4404 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 4405 4406 // Create a new block that will contain the try statement. 4407 CFGBlock *NewTryTerminatedBlock = createBlock(false); 4408 // Add the terminator in the try block. 4409 NewTryTerminatedBlock->setTerminator(Terminator); 4410 4411 bool HasCatchAll = false; 4412 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) { 4413 // The code after the try is the implicit successor. 4414 Succ = TrySuccessor; 4415 CXXCatchStmt *CS = Terminator->getHandler(I); 4416 if (CS->getExceptionDecl() == nullptr) { 4417 HasCatchAll = true; 4418 } 4419 Block = nullptr; 4420 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 4421 if (!CatchBlock) 4422 return nullptr; 4423 // Add this block to the list of successors for the block with the try 4424 // statement. 4425 addSuccessor(NewTryTerminatedBlock, CatchBlock); 4426 } 4427 if (!HasCatchAll) { 4428 if (PrevTryTerminatedBlock) 4429 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 4430 else 4431 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 4432 } 4433 4434 // The code after the try is the implicit successor. 4435 Succ = TrySuccessor; 4436 4437 // Save the current "try" context. 4438 SaveAndRestore<CFGBlock *> SaveTry(TryTerminatedBlock, NewTryTerminatedBlock); 4439 cfg->addTryDispatchBlock(TryTerminatedBlock); 4440 4441 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 4442 Block = nullptr; 4443 return addStmt(Terminator->getTryBlock()); 4444 } 4445 4446 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 4447 // CXXCatchStmt are treated like labels, so they are the first statement in a 4448 // block. 4449 4450 // Save local scope position because in case of exception variable ScopePos 4451 // won't be restored when traversing AST. 4452 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4453 4454 // Create local scope for possible exception variable. 4455 // Store scope position. Add implicit destructor. 4456 if (VarDecl *VD = CS->getExceptionDecl()) { 4457 LocalScope::const_iterator BeginScopePos = ScopePos; 4458 addLocalScopeForVarDecl(VD); 4459 addAutomaticObjHandling(ScopePos, BeginScopePos, CS); 4460 } 4461 4462 if (CS->getHandlerBlock()) 4463 addStmt(CS->getHandlerBlock()); 4464 4465 CFGBlock *CatchBlock = Block; 4466 if (!CatchBlock) 4467 CatchBlock = createBlock(); 4468 4469 // CXXCatchStmt is more than just a label. They have semantic meaning 4470 // as well, as they implicitly "initialize" the catch variable. Add 4471 // it to the CFG as a CFGElement so that the control-flow of these 4472 // semantics gets captured. 4473 appendStmt(CatchBlock, CS); 4474 4475 // Also add the CXXCatchStmt as a label, to mirror handling of regular 4476 // labels. 4477 CatchBlock->setLabel(CS); 4478 4479 // Bail out if the CFG is bad. 4480 if (badCFG) 4481 return nullptr; 4482 4483 // We set Block to NULL to allow lazy creation of a new block (if necessary). 4484 Block = nullptr; 4485 4486 return CatchBlock; 4487 } 4488 4489 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 4490 // C++0x for-range statements are specified as [stmt.ranged]: 4491 // 4492 // { 4493 // auto && __range = range-init; 4494 // for ( auto __begin = begin-expr, 4495 // __end = end-expr; 4496 // __begin != __end; 4497 // ++__begin ) { 4498 // for-range-declaration = *__begin; 4499 // statement 4500 // } 4501 // } 4502 4503 // Save local scope position before the addition of the implicit variables. 4504 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 4505 4506 // Create local scopes and destructors for range, begin and end variables. 4507 if (Stmt *Range = S->getRangeStmt()) 4508 addLocalScopeForStmt(Range); 4509 if (Stmt *Begin = S->getBeginStmt()) 4510 addLocalScopeForStmt(Begin); 4511 if (Stmt *End = S->getEndStmt()) 4512 addLocalScopeForStmt(End); 4513 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S); 4514 4515 LocalScope::const_iterator ContinueScopePos = ScopePos; 4516 4517 // "for" is a control-flow statement. Thus we stop processing the current 4518 // block. 4519 CFGBlock *LoopSuccessor = nullptr; 4520 if (Block) { 4521 if (badCFG) 4522 return nullptr; 4523 LoopSuccessor = Block; 4524 } else 4525 LoopSuccessor = Succ; 4526 4527 // Save the current value for the break targets. 4528 // All breaks should go to the code following the loop. 4529 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 4530 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 4531 4532 // The block for the __begin != __end expression. 4533 CFGBlock *ConditionBlock = createBlock(false); 4534 ConditionBlock->setTerminator(S); 4535 4536 // Now add the actual condition to the condition block. 4537 if (Expr *C = S->getCond()) { 4538 Block = ConditionBlock; 4539 CFGBlock *BeginConditionBlock = addStmt(C); 4540 if (badCFG) 4541 return nullptr; 4542 assert(BeginConditionBlock == ConditionBlock && 4543 "condition block in for-range was unexpectedly complex"); 4544 (void)BeginConditionBlock; 4545 } 4546 4547 // The condition block is the implicit successor for the loop body as well as 4548 // any code above the loop. 4549 Succ = ConditionBlock; 4550 4551 // See if this is a known constant. 4552 TryResult KnownVal(true); 4553 4554 if (S->getCond()) 4555 KnownVal = tryEvaluateBool(S->getCond()); 4556 4557 // Now create the loop body. 4558 { 4559 assert(S->getBody()); 4560 4561 // Save the current values for Block, Succ, and continue targets. 4562 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 4563 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 4564 4565 // Generate increment code in its own basic block. This is the target of 4566 // continue statements. 4567 Block = nullptr; 4568 Succ = addStmt(S->getInc()); 4569 if (badCFG) 4570 return nullptr; 4571 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 4572 4573 // The starting block for the loop increment is the block that should 4574 // represent the 'loop target' for looping back to the start of the loop. 4575 ContinueJumpTarget.block->setLoopTarget(S); 4576 4577 // Finish up the increment block and prepare to start the loop body. 4578 assert(Block); 4579 if (badCFG) 4580 return nullptr; 4581 Block = nullptr; 4582 4583 // Add implicit scope and dtors for loop variable. 4584 addLocalScopeAndDtors(S->getLoopVarStmt()); 4585 4586 // If body is not a compound statement create implicit scope 4587 // and add destructors. 4588 if (!isa<CompoundStmt>(S->getBody())) 4589 addLocalScopeAndDtors(S->getBody()); 4590 4591 // Populate a new block to contain the loop body and loop variable. 4592 addStmt(S->getBody()); 4593 4594 if (badCFG) 4595 return nullptr; 4596 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt()); 4597 if (badCFG) 4598 return nullptr; 4599 4600 // This new body block is a successor to our condition block. 4601 addSuccessor(ConditionBlock, 4602 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock); 4603 } 4604 4605 // Link up the condition block with the code that follows the loop (the 4606 // false branch). 4607 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor); 4608 4609 // Add the initialization statements. 4610 Block = createBlock(); 4611 addStmt(S->getBeginStmt()); 4612 addStmt(S->getEndStmt()); 4613 CFGBlock *Head = addStmt(S->getRangeStmt()); 4614 if (S->getInit()) 4615 Head = addStmt(S->getInit()); 4616 return Head; 4617 } 4618 4619 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 4620 AddStmtChoice asc, bool ExternallyDestructed) { 4621 if (BuildOpts.AddTemporaryDtors) { 4622 // If adding implicit destructors visit the full expression for adding 4623 // destructors of temporaries. 4624 TempDtorContext Context; 4625 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context); 4626 4627 // Full expression has to be added as CFGStmt so it will be sequenced 4628 // before destructors of it's temporaries. 4629 asc = asc.withAlwaysAdd(true); 4630 } 4631 return Visit(E->getSubExpr(), asc); 4632 } 4633 4634 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 4635 AddStmtChoice asc) { 4636 if (asc.alwaysAdd(*this, E)) { 4637 autoCreateBlock(); 4638 appendStmt(Block, E); 4639 4640 findConstructionContexts( 4641 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E), 4642 E->getSubExpr()); 4643 4644 // We do not want to propagate the AlwaysAdd property. 4645 asc = asc.withAlwaysAdd(false); 4646 } 4647 return Visit(E->getSubExpr(), asc); 4648 } 4649 4650 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 4651 AddStmtChoice asc) { 4652 // If the constructor takes objects as arguments by value, we need to properly 4653 // construct these objects. Construction contexts we find here aren't for the 4654 // constructor C, they're for its arguments only. 4655 findConstructionContextsForArguments(C); 4656 4657 autoCreateBlock(); 4658 appendConstructor(Block, C); 4659 4660 return VisitChildren(C); 4661 } 4662 4663 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE, 4664 AddStmtChoice asc) { 4665 autoCreateBlock(); 4666 appendStmt(Block, NE); 4667 4668 findConstructionContexts( 4669 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE), 4670 const_cast<CXXConstructExpr *>(NE->getConstructExpr())); 4671 4672 if (NE->getInitializer()) 4673 Block = Visit(NE->getInitializer()); 4674 4675 if (BuildOpts.AddCXXNewAllocator) 4676 appendNewAllocator(Block, NE); 4677 4678 if (NE->isArray() && *NE->getArraySize()) 4679 Block = Visit(*NE->getArraySize()); 4680 4681 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(), 4682 E = NE->placement_arg_end(); I != E; ++I) 4683 Block = Visit(*I); 4684 4685 return Block; 4686 } 4687 4688 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE, 4689 AddStmtChoice asc) { 4690 autoCreateBlock(); 4691 appendStmt(Block, DE); 4692 QualType DTy = DE->getDestroyedType(); 4693 if (!DTy.isNull()) { 4694 DTy = DTy.getNonReferenceType(); 4695 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl(); 4696 if (RD) { 4697 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor()) 4698 appendDeleteDtor(Block, RD, DE); 4699 } 4700 } 4701 4702 return VisitChildren(DE); 4703 } 4704 4705 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 4706 AddStmtChoice asc) { 4707 if (asc.alwaysAdd(*this, E)) { 4708 autoCreateBlock(); 4709 appendStmt(Block, E); 4710 // We do not want to propagate the AlwaysAdd property. 4711 asc = asc.withAlwaysAdd(false); 4712 } 4713 return Visit(E->getSubExpr(), asc); 4714 } 4715 4716 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 4717 AddStmtChoice asc) { 4718 // If the constructor takes objects as arguments by value, we need to properly 4719 // construct these objects. Construction contexts we find here aren't for the 4720 // constructor C, they're for its arguments only. 4721 findConstructionContextsForArguments(C); 4722 4723 autoCreateBlock(); 4724 appendConstructor(Block, C); 4725 return VisitChildren(C); 4726 } 4727 4728 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 4729 AddStmtChoice asc) { 4730 if (asc.alwaysAdd(*this, E)) { 4731 autoCreateBlock(); 4732 appendStmt(Block, E); 4733 } 4734 4735 if (E->getCastKind() == CK_IntegralToBoolean) 4736 tryEvaluateBool(E->getSubExpr()->IgnoreParens()); 4737 4738 return Visit(E->getSubExpr(), AddStmtChoice()); 4739 } 4740 4741 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) { 4742 return Visit(E->getSubExpr(), AddStmtChoice()); 4743 } 4744 4745 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 4746 // Lazily create the indirect-goto dispatch block if there isn't one already. 4747 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 4748 4749 if (!IBlock) { 4750 IBlock = createBlock(false); 4751 cfg->setIndirectGotoBlock(IBlock); 4752 } 4753 4754 // IndirectGoto is a control-flow statement. Thus we stop processing the 4755 // current block and create a new one. 4756 if (badCFG) 4757 return nullptr; 4758 4759 Block = createBlock(false); 4760 Block->setTerminator(I); 4761 addSuccessor(Block, IBlock); 4762 return addStmt(I->getTarget()); 4763 } 4764 4765 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed, 4766 TempDtorContext &Context) { 4767 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors); 4768 4769 tryAgain: 4770 if (!E) { 4771 badCFG = true; 4772 return nullptr; 4773 } 4774 switch (E->getStmtClass()) { 4775 default: 4776 return VisitChildrenForTemporaryDtors(E, false, Context); 4777 4778 case Stmt::InitListExprClass: 4779 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context); 4780 4781 case Stmt::BinaryOperatorClass: 4782 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E), 4783 ExternallyDestructed, 4784 Context); 4785 4786 case Stmt::CXXBindTemporaryExprClass: 4787 return VisitCXXBindTemporaryExprForTemporaryDtors( 4788 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context); 4789 4790 case Stmt::BinaryConditionalOperatorClass: 4791 case Stmt::ConditionalOperatorClass: 4792 return VisitConditionalOperatorForTemporaryDtors( 4793 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context); 4794 4795 case Stmt::ImplicitCastExprClass: 4796 // For implicit cast we want ExternallyDestructed to be passed further. 4797 E = cast<CastExpr>(E)->getSubExpr(); 4798 goto tryAgain; 4799 4800 case Stmt::CXXFunctionalCastExprClass: 4801 // For functional cast we want ExternallyDestructed to be passed further. 4802 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr(); 4803 goto tryAgain; 4804 4805 case Stmt::ConstantExprClass: 4806 E = cast<ConstantExpr>(E)->getSubExpr(); 4807 goto tryAgain; 4808 4809 case Stmt::ParenExprClass: 4810 E = cast<ParenExpr>(E)->getSubExpr(); 4811 goto tryAgain; 4812 4813 case Stmt::MaterializeTemporaryExprClass: { 4814 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E); 4815 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression); 4816 SmallVector<const Expr *, 2> CommaLHSs; 4817 SmallVector<SubobjectAdjustment, 2> Adjustments; 4818 // Find the expression whose lifetime needs to be extended. 4819 E = const_cast<Expr *>( 4820 cast<MaterializeTemporaryExpr>(E) 4821 ->getSubExpr() 4822 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments)); 4823 // Visit the skipped comma operator left-hand sides for other temporaries. 4824 for (const Expr *CommaLHS : CommaLHSs) { 4825 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS), 4826 /*ExternallyDestructed=*/false, Context); 4827 } 4828 goto tryAgain; 4829 } 4830 4831 case Stmt::BlockExprClass: 4832 // Don't recurse into blocks; their subexpressions don't get evaluated 4833 // here. 4834 return Block; 4835 4836 case Stmt::LambdaExprClass: { 4837 // For lambda expressions, only recurse into the capture initializers, 4838 // and not the body. 4839 auto *LE = cast<LambdaExpr>(E); 4840 CFGBlock *B = Block; 4841 for (Expr *Init : LE->capture_inits()) { 4842 if (Init) { 4843 if (CFGBlock *R = VisitForTemporaryDtors( 4844 Init, /*ExternallyDestructed=*/true, Context)) 4845 B = R; 4846 } 4847 } 4848 return B; 4849 } 4850 4851 case Stmt::StmtExprClass: 4852 // Don't recurse into statement expressions; any cleanups inside them 4853 // will be wrapped in their own ExprWithCleanups. 4854 return Block; 4855 4856 case Stmt::CXXDefaultArgExprClass: 4857 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4858 goto tryAgain; 4859 4860 case Stmt::CXXDefaultInitExprClass: 4861 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4862 goto tryAgain; 4863 } 4864 } 4865 4866 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E, 4867 bool ExternallyDestructed, 4868 TempDtorContext &Context) { 4869 if (isa<LambdaExpr>(E)) { 4870 // Do not visit the children of lambdas; they have their own CFGs. 4871 return Block; 4872 } 4873 4874 // When visiting children for destructors we want to visit them in reverse 4875 // order that they will appear in the CFG. Because the CFG is built 4876 // bottom-up, this means we visit them in their natural order, which 4877 // reverses them in the CFG. 4878 CFGBlock *B = Block; 4879 for (Stmt *Child : E->children()) 4880 if (Child) 4881 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context)) 4882 B = R; 4883 4884 return B; 4885 } 4886 4887 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors( 4888 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) { 4889 if (E->isCommaOp()) { 4890 // For the comma operator, the LHS expression is evaluated before the RHS 4891 // expression, so prepend temporary destructors for the LHS first. 4892 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4893 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context); 4894 return RHSBlock ? RHSBlock : LHSBlock; 4895 } 4896 4897 if (E->isLogicalOp()) { 4898 VisitForTemporaryDtors(E->getLHS(), false, Context); 4899 TryResult RHSExecuted = tryEvaluateBool(E->getLHS()); 4900 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr) 4901 RHSExecuted.negate(); 4902 4903 // We do not know at CFG-construction time whether the right-hand-side was 4904 // executed, thus we add a branch node that depends on the temporary 4905 // constructor call. 4906 TempDtorContext RHSContext( 4907 bothKnownTrue(Context.KnownExecuted, RHSExecuted)); 4908 VisitForTemporaryDtors(E->getRHS(), false, RHSContext); 4909 InsertTempDtorDecisionBlock(RHSContext); 4910 4911 return Block; 4912 } 4913 4914 if (E->isAssignmentOp()) { 4915 // For assignment operators, the RHS expression is evaluated before the LHS 4916 // expression, so prepend temporary destructors for the RHS first. 4917 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context); 4918 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context); 4919 return LHSBlock ? LHSBlock : RHSBlock; 4920 } 4921 4922 // Any other operator is visited normally. 4923 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context); 4924 } 4925 4926 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 4927 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) { 4928 // First add destructors for temporaries in subexpression. 4929 // Because VisitCXXBindTemporaryExpr calls setDestructed: 4930 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context); 4931 if (!ExternallyDestructed) { 4932 // If lifetime of temporary is not prolonged (by assigning to constant 4933 // reference) add destructor for it. 4934 4935 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 4936 4937 if (Dtor->getParent()->isAnyDestructorNoReturn()) { 4938 // If the destructor is marked as a no-return destructor, we need to 4939 // create a new block for the destructor which does not have as a 4940 // successor anything built thus far. Control won't flow out of this 4941 // block. 4942 if (B) Succ = B; 4943 Block = createNoReturnBlock(); 4944 } else if (Context.needsTempDtorBranch()) { 4945 // If we need to introduce a branch, we add a new block that we will hook 4946 // up to a decision block later. 4947 if (B) Succ = B; 4948 Block = createBlock(); 4949 } else { 4950 autoCreateBlock(); 4951 } 4952 if (Context.needsTempDtorBranch()) { 4953 Context.setDecisionPoint(Succ, E); 4954 } 4955 appendTemporaryDtor(Block, E); 4956 4957 B = Block; 4958 } 4959 return B; 4960 } 4961 4962 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context, 4963 CFGBlock *FalseSucc) { 4964 if (!Context.TerminatorExpr) { 4965 // If no temporary was found, we do not need to insert a decision point. 4966 return; 4967 } 4968 assert(Context.TerminatorExpr); 4969 CFGBlock *Decision = createBlock(false); 4970 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, 4971 CFGTerminator::TemporaryDtorsBranch)); 4972 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse()); 4973 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ, 4974 !Context.KnownExecuted.isTrue()); 4975 Block = Decision; 4976 } 4977 4978 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 4979 AbstractConditionalOperator *E, bool ExternallyDestructed, 4980 TempDtorContext &Context) { 4981 VisitForTemporaryDtors(E->getCond(), false, Context); 4982 CFGBlock *ConditionBlock = Block; 4983 CFGBlock *ConditionSucc = Succ; 4984 TryResult ConditionVal = tryEvaluateBool(E->getCond()); 4985 TryResult NegatedVal = ConditionVal; 4986 if (NegatedVal.isKnown()) NegatedVal.negate(); 4987 4988 TempDtorContext TrueContext( 4989 bothKnownTrue(Context.KnownExecuted, ConditionVal)); 4990 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext); 4991 CFGBlock *TrueBlock = Block; 4992 4993 Block = ConditionBlock; 4994 Succ = ConditionSucc; 4995 TempDtorContext FalseContext( 4996 bothKnownTrue(Context.KnownExecuted, NegatedVal)); 4997 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext); 4998 4999 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) { 5000 InsertTempDtorDecisionBlock(FalseContext, TrueBlock); 5001 } else if (TrueContext.TerminatorExpr) { 5002 Block = TrueBlock; 5003 InsertTempDtorDecisionBlock(TrueContext); 5004 } else { 5005 InsertTempDtorDecisionBlock(FalseContext); 5006 } 5007 return Block; 5008 } 5009 5010 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D, 5011 AddStmtChoice asc) { 5012 if (asc.alwaysAdd(*this, D)) { 5013 autoCreateBlock(); 5014 appendStmt(Block, D); 5015 } 5016 5017 // Iterate over all used expression in clauses. 5018 CFGBlock *B = Block; 5019 5020 // Reverse the elements to process them in natural order. Iterators are not 5021 // bidirectional, so we need to create temp vector. 5022 SmallVector<Stmt *, 8> Used( 5023 OMPExecutableDirective::used_clauses_children(D->clauses())); 5024 for (Stmt *S : llvm::reverse(Used)) { 5025 assert(S && "Expected non-null used-in-clause child."); 5026 if (CFGBlock *R = Visit(S)) 5027 B = R; 5028 } 5029 // Visit associated structured block if any. 5030 if (!D->isStandaloneDirective()) { 5031 Stmt *S = D->getRawStmt(); 5032 if (!isa<CompoundStmt>(S)) 5033 addLocalScopeAndDtors(S); 5034 if (CFGBlock *R = addStmt(S)) 5035 B = R; 5036 } 5037 5038 return B; 5039 } 5040 5041 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 5042 /// no successors or predecessors. If this is the first block created in the 5043 /// CFG, it is automatically set to be the Entry and Exit of the CFG. 5044 CFGBlock *CFG::createBlock() { 5045 bool first_block = begin() == end(); 5046 5047 // Create the block. 5048 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 5049 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); 5050 Blocks.push_back(Mem, BlkBVC); 5051 5052 // If this is the first block, set it as the Entry and Exit. 5053 if (first_block) 5054 Entry = Exit = &back(); 5055 5056 // Return the block. 5057 return &back(); 5058 } 5059 5060 /// buildCFG - Constructs a CFG from an AST. 5061 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement, 5062 ASTContext *C, const BuildOptions &BO) { 5063 CFGBuilder Builder(C, BO); 5064 return Builder.buildCFG(D, Statement); 5065 } 5066 5067 bool CFG::isLinear() const { 5068 // Quick path: if we only have the ENTRY block, the EXIT block, and some code 5069 // in between, then we have no room for control flow. 5070 if (size() <= 3) 5071 return true; 5072 5073 // Traverse the CFG until we find a branch. 5074 // TODO: While this should still be very fast, 5075 // maybe we should cache the answer. 5076 llvm::SmallPtrSet<const CFGBlock *, 4> Visited; 5077 const CFGBlock *B = Entry; 5078 while (B != Exit) { 5079 auto IteratorAndFlag = Visited.insert(B); 5080 if (!IteratorAndFlag.second) { 5081 // We looped back to a block that we've already visited. Not linear. 5082 return false; 5083 } 5084 5085 // Iterate over reachable successors. 5086 const CFGBlock *FirstReachableB = nullptr; 5087 for (const CFGBlock::AdjacentBlock &AB : B->succs()) { 5088 if (!AB.isReachable()) 5089 continue; 5090 5091 if (FirstReachableB == nullptr) { 5092 FirstReachableB = &*AB; 5093 } else { 5094 // We've encountered a branch. It's not a linear CFG. 5095 return false; 5096 } 5097 } 5098 5099 if (!FirstReachableB) { 5100 // We reached a dead end. EXIT is unreachable. This is linear enough. 5101 return true; 5102 } 5103 5104 // There's only one way to move forward. Proceed. 5105 B = FirstReachableB; 5106 } 5107 5108 // We reached EXIT and found no branches. 5109 return true; 5110 } 5111 5112 const CXXDestructorDecl * 5113 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 5114 switch (getKind()) { 5115 case CFGElement::Initializer: 5116 case CFGElement::NewAllocator: 5117 case CFGElement::LoopExit: 5118 case CFGElement::LifetimeEnds: 5119 case CFGElement::Statement: 5120 case CFGElement::Constructor: 5121 case CFGElement::CXXRecordTypedCall: 5122 case CFGElement::ScopeBegin: 5123 case CFGElement::ScopeEnd: 5124 llvm_unreachable("getDestructorDecl should only be used with " 5125 "ImplicitDtors"); 5126 case CFGElement::AutomaticObjectDtor: { 5127 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl(); 5128 QualType ty = var->getType(); 5129 5130 // FIXME: See CFGBuilder::addLocalScopeForVarDecl. 5131 // 5132 // Lifetime-extending constructs are handled here. This works for a single 5133 // temporary in an initializer expression. 5134 if (ty->isReferenceType()) { 5135 if (const Expr *Init = var->getInit()) { 5136 ty = getReferenceInitTemporaryType(Init); 5137 } 5138 } 5139 5140 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 5141 ty = arrayType->getElementType(); 5142 } 5143 5144 // The situation when the type of the lifetime-extending reference 5145 // does not correspond to the type of the object is supposed 5146 // to be handled by now. In particular, 'ty' is now the unwrapped 5147 // record type. 5148 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl(); 5149 assert(classDecl); 5150 return classDecl->getDestructor(); 5151 } 5152 case CFGElement::DeleteDtor: { 5153 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr(); 5154 QualType DTy = DE->getDestroyedType(); 5155 DTy = DTy.getNonReferenceType(); 5156 const CXXRecordDecl *classDecl = 5157 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl(); 5158 return classDecl->getDestructor(); 5159 } 5160 case CFGElement::TemporaryDtor: { 5161 const CXXBindTemporaryExpr *bindExpr = 5162 castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); 5163 const CXXTemporary *temp = bindExpr->getTemporary(); 5164 return temp->getDestructor(); 5165 } 5166 case CFGElement::BaseDtor: 5167 case CFGElement::MemberDtor: 5168 // Not yet supported. 5169 return nullptr; 5170 } 5171 llvm_unreachable("getKind() returned bogus value"); 5172 } 5173 5174 //===----------------------------------------------------------------------===// 5175 // CFGBlock operations. 5176 //===----------------------------------------------------------------------===// 5177 5178 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable) 5179 : ReachableBlock(IsReachable ? B : nullptr), 5180 UnreachableBlock(!IsReachable ? B : nullptr, 5181 B && IsReachable ? AB_Normal : AB_Unreachable) {} 5182 5183 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock) 5184 : ReachableBlock(B), 5185 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock, 5186 B == AlternateBlock ? AB_Alternate : AB_Normal) {} 5187 5188 void CFGBlock::addSuccessor(AdjacentBlock Succ, 5189 BumpVectorContext &C) { 5190 if (CFGBlock *B = Succ.getReachableBlock()) 5191 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C); 5192 5193 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock()) 5194 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C); 5195 5196 Succs.push_back(Succ, C); 5197 } 5198 5199 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 5200 const CFGBlock *From, const CFGBlock *To) { 5201 if (F.IgnoreNullPredecessors && !From) 5202 return true; 5203 5204 if (To && From && F.IgnoreDefaultsWithCoveredEnums) { 5205 // If the 'To' has no label or is labeled but the label isn't a 5206 // CaseStmt then filter this edge. 5207 if (const SwitchStmt *S = 5208 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) { 5209 if (S->isAllEnumCasesCovered()) { 5210 const Stmt *L = To->getLabel(); 5211 if (!L || !isa<CaseStmt>(L)) 5212 return true; 5213 } 5214 } 5215 } 5216 5217 return false; 5218 } 5219 5220 //===----------------------------------------------------------------------===// 5221 // CFG pretty printing 5222 //===----------------------------------------------------------------------===// 5223 5224 namespace { 5225 5226 class StmtPrinterHelper : public PrinterHelper { 5227 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>; 5228 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>; 5229 5230 StmtMapTy StmtMap; 5231 DeclMapTy DeclMap; 5232 signed currentBlock = 0; 5233 unsigned currStmt = 0; 5234 const LangOptions &LangOpts; 5235 5236 public: 5237 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 5238 : LangOpts(LO) { 5239 if (!cfg) 5240 return; 5241 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 5242 unsigned j = 1; 5243 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 5244 BI != BEnd; ++BI, ++j ) { 5245 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) { 5246 const Stmt *stmt= SE->getStmt(); 5247 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 5248 StmtMap[stmt] = P; 5249 5250 switch (stmt->getStmtClass()) { 5251 case Stmt::DeclStmtClass: 5252 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 5253 break; 5254 case Stmt::IfStmtClass: { 5255 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 5256 if (var) 5257 DeclMap[var] = P; 5258 break; 5259 } 5260 case Stmt::ForStmtClass: { 5261 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 5262 if (var) 5263 DeclMap[var] = P; 5264 break; 5265 } 5266 case Stmt::WhileStmtClass: { 5267 const VarDecl *var = 5268 cast<WhileStmt>(stmt)->getConditionVariable(); 5269 if (var) 5270 DeclMap[var] = P; 5271 break; 5272 } 5273 case Stmt::SwitchStmtClass: { 5274 const VarDecl *var = 5275 cast<SwitchStmt>(stmt)->getConditionVariable(); 5276 if (var) 5277 DeclMap[var] = P; 5278 break; 5279 } 5280 case Stmt::CXXCatchStmtClass: { 5281 const VarDecl *var = 5282 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 5283 if (var) 5284 DeclMap[var] = P; 5285 break; 5286 } 5287 default: 5288 break; 5289 } 5290 } 5291 } 5292 } 5293 } 5294 5295 ~StmtPrinterHelper() override = default; 5296 5297 const LangOptions &getLangOpts() const { return LangOpts; } 5298 void setBlockID(signed i) { currentBlock = i; } 5299 void setStmtID(unsigned i) { currStmt = i; } 5300 5301 bool handledStmt(Stmt *S, raw_ostream &OS) override { 5302 StmtMapTy::iterator I = StmtMap.find(S); 5303 5304 if (I == StmtMap.end()) 5305 return false; 5306 5307 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 5308 && I->second.second == currStmt) { 5309 return false; 5310 } 5311 5312 OS << "[B" << I->second.first << "." << I->second.second << "]"; 5313 return true; 5314 } 5315 5316 bool handleDecl(const Decl *D, raw_ostream &OS) { 5317 DeclMapTy::iterator I = DeclMap.find(D); 5318 5319 if (I == DeclMap.end()) 5320 return false; 5321 5322 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 5323 && I->second.second == currStmt) { 5324 return false; 5325 } 5326 5327 OS << "[B" << I->second.first << "." << I->second.second << "]"; 5328 return true; 5329 } 5330 }; 5331 5332 class CFGBlockTerminatorPrint 5333 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 5334 raw_ostream &OS; 5335 StmtPrinterHelper* Helper; 5336 PrintingPolicy Policy; 5337 5338 public: 5339 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 5340 const PrintingPolicy &Policy) 5341 : OS(os), Helper(helper), Policy(Policy) { 5342 this->Policy.IncludeNewlines = false; 5343 } 5344 5345 void VisitIfStmt(IfStmt *I) { 5346 OS << "if "; 5347 if (Stmt *C = I->getCond()) 5348 C->printPretty(OS, Helper, Policy); 5349 } 5350 5351 // Default case. 5352 void VisitStmt(Stmt *Terminator) { 5353 Terminator->printPretty(OS, Helper, Policy); 5354 } 5355 5356 void VisitDeclStmt(DeclStmt *DS) { 5357 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); 5358 OS << "static init " << VD->getName(); 5359 } 5360 5361 void VisitForStmt(ForStmt *F) { 5362 OS << "for (" ; 5363 if (F->getInit()) 5364 OS << "..."; 5365 OS << "; "; 5366 if (Stmt *C = F->getCond()) 5367 C->printPretty(OS, Helper, Policy); 5368 OS << "; "; 5369 if (F->getInc()) 5370 OS << "..."; 5371 OS << ")"; 5372 } 5373 5374 void VisitWhileStmt(WhileStmt *W) { 5375 OS << "while " ; 5376 if (Stmt *C = W->getCond()) 5377 C->printPretty(OS, Helper, Policy); 5378 } 5379 5380 void VisitDoStmt(DoStmt *D) { 5381 OS << "do ... while "; 5382 if (Stmt *C = D->getCond()) 5383 C->printPretty(OS, Helper, Policy); 5384 } 5385 5386 void VisitSwitchStmt(SwitchStmt *Terminator) { 5387 OS << "switch "; 5388 Terminator->getCond()->printPretty(OS, Helper, Policy); 5389 } 5390 5391 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; } 5392 5393 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; } 5394 5395 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; } 5396 5397 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 5398 if (Stmt *Cond = C->getCond()) 5399 Cond->printPretty(OS, Helper, Policy); 5400 OS << " ? ... : ..."; 5401 } 5402 5403 void VisitChooseExpr(ChooseExpr *C) { 5404 OS << "__builtin_choose_expr( "; 5405 if (Stmt *Cond = C->getCond()) 5406 Cond->printPretty(OS, Helper, Policy); 5407 OS << " )"; 5408 } 5409 5410 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 5411 OS << "goto *"; 5412 if (Stmt *T = I->getTarget()) 5413 T->printPretty(OS, Helper, Policy); 5414 } 5415 5416 void VisitBinaryOperator(BinaryOperator* B) { 5417 if (!B->isLogicalOp()) { 5418 VisitExpr(B); 5419 return; 5420 } 5421 5422 if (B->getLHS()) 5423 B->getLHS()->printPretty(OS, Helper, Policy); 5424 5425 switch (B->getOpcode()) { 5426 case BO_LOr: 5427 OS << " || ..."; 5428 return; 5429 case BO_LAnd: 5430 OS << " && ..."; 5431 return; 5432 default: 5433 llvm_unreachable("Invalid logical operator."); 5434 } 5435 } 5436 5437 void VisitExpr(Expr *E) { 5438 E->printPretty(OS, Helper, Policy); 5439 } 5440 5441 public: 5442 void print(CFGTerminator T) { 5443 switch (T.getKind()) { 5444 case CFGTerminator::StmtBranch: 5445 Visit(T.getStmt()); 5446 break; 5447 case CFGTerminator::TemporaryDtorsBranch: 5448 OS << "(Temp Dtor) "; 5449 Visit(T.getStmt()); 5450 break; 5451 case CFGTerminator::VirtualBaseBranch: 5452 OS << "(See if most derived ctor has already initialized vbases)"; 5453 break; 5454 } 5455 } 5456 }; 5457 5458 } // namespace 5459 5460 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper, 5461 const CXXCtorInitializer *I) { 5462 if (I->isBaseInitializer()) 5463 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 5464 else if (I->isDelegatingInitializer()) 5465 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName(); 5466 else 5467 OS << I->getAnyMember()->getName(); 5468 OS << "("; 5469 if (Expr *IE = I->getInit()) 5470 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5471 OS << ")"; 5472 5473 if (I->isBaseInitializer()) 5474 OS << " (Base initializer)"; 5475 else if (I->isDelegatingInitializer()) 5476 OS << " (Delegating initializer)"; 5477 else 5478 OS << " (Member initializer)"; 5479 } 5480 5481 static void print_construction_context(raw_ostream &OS, 5482 StmtPrinterHelper &Helper, 5483 const ConstructionContext *CC) { 5484 SmallVector<const Stmt *, 3> Stmts; 5485 switch (CC->getKind()) { 5486 case ConstructionContext::SimpleConstructorInitializerKind: { 5487 OS << ", "; 5488 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC); 5489 print_initializer(OS, Helper, SICC->getCXXCtorInitializer()); 5490 return; 5491 } 5492 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: { 5493 OS << ", "; 5494 const auto *CICC = 5495 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC); 5496 print_initializer(OS, Helper, CICC->getCXXCtorInitializer()); 5497 Stmts.push_back(CICC->getCXXBindTemporaryExpr()); 5498 break; 5499 } 5500 case ConstructionContext::SimpleVariableKind: { 5501 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC); 5502 Stmts.push_back(SDSCC->getDeclStmt()); 5503 break; 5504 } 5505 case ConstructionContext::CXX17ElidedCopyVariableKind: { 5506 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC); 5507 Stmts.push_back(CDSCC->getDeclStmt()); 5508 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr()); 5509 break; 5510 } 5511 case ConstructionContext::NewAllocatedObjectKind: { 5512 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 5513 Stmts.push_back(NECC->getCXXNewExpr()); 5514 break; 5515 } 5516 case ConstructionContext::SimpleReturnedValueKind: { 5517 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC); 5518 Stmts.push_back(RSCC->getReturnStmt()); 5519 break; 5520 } 5521 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 5522 const auto *RSCC = 5523 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC); 5524 Stmts.push_back(RSCC->getReturnStmt()); 5525 Stmts.push_back(RSCC->getCXXBindTemporaryExpr()); 5526 break; 5527 } 5528 case ConstructionContext::SimpleTemporaryObjectKind: { 5529 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC); 5530 Stmts.push_back(TOCC->getCXXBindTemporaryExpr()); 5531 Stmts.push_back(TOCC->getMaterializedTemporaryExpr()); 5532 break; 5533 } 5534 case ConstructionContext::ElidedTemporaryObjectKind: { 5535 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 5536 Stmts.push_back(TOCC->getCXXBindTemporaryExpr()); 5537 Stmts.push_back(TOCC->getMaterializedTemporaryExpr()); 5538 Stmts.push_back(TOCC->getConstructorAfterElision()); 5539 break; 5540 } 5541 case ConstructionContext::ArgumentKind: { 5542 const auto *ACC = cast<ArgumentConstructionContext>(CC); 5543 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) { 5544 OS << ", "; 5545 Helper.handledStmt(const_cast<Stmt *>(BTE), OS); 5546 } 5547 OS << ", "; 5548 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS); 5549 OS << "+" << ACC->getIndex(); 5550 return; 5551 } 5552 } 5553 for (auto I: Stmts) 5554 if (I) { 5555 OS << ", "; 5556 Helper.handledStmt(const_cast<Stmt *>(I), OS); 5557 } 5558 } 5559 5560 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, 5561 const CFGElement &E); 5562 5563 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const { 5564 StmtPrinterHelper Helper(nullptr, {}); 5565 print_elem(OS, Helper, *this); 5566 } 5567 5568 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper, 5569 const CFGElement &E) { 5570 switch (E.getKind()) { 5571 case CFGElement::Kind::Statement: 5572 case CFGElement::Kind::CXXRecordTypedCall: 5573 case CFGElement::Kind::Constructor: { 5574 CFGStmt CS = E.castAs<CFGStmt>(); 5575 const Stmt *S = CS.getStmt(); 5576 assert(S != nullptr && "Expecting non-null Stmt"); 5577 5578 // special printing for statement-expressions. 5579 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 5580 const CompoundStmt *Sub = SE->getSubStmt(); 5581 5582 auto Children = Sub->children(); 5583 if (Children.begin() != Children.end()) { 5584 OS << "({ ... ; "; 5585 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 5586 OS << " })\n"; 5587 return; 5588 } 5589 } 5590 // special printing for comma expressions. 5591 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 5592 if (B->getOpcode() == BO_Comma) { 5593 OS << "... , "; 5594 Helper.handledStmt(B->getRHS(),OS); 5595 OS << '\n'; 5596 return; 5597 } 5598 } 5599 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5600 5601 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) { 5602 if (isa<CXXOperatorCallExpr>(S)) 5603 OS << " (OperatorCall)"; 5604 OS << " (CXXRecordTypedCall"; 5605 print_construction_context(OS, Helper, VTC->getConstructionContext()); 5606 OS << ")"; 5607 } else if (isa<CXXOperatorCallExpr>(S)) { 5608 OS << " (OperatorCall)"; 5609 } else if (isa<CXXBindTemporaryExpr>(S)) { 5610 OS << " (BindTemporary)"; 5611 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { 5612 OS << " (CXXConstructExpr"; 5613 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) { 5614 print_construction_context(OS, Helper, CE->getConstructionContext()); 5615 } 5616 OS << ", " << CCE->getType().getAsString() << ")"; 5617 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { 5618 OS << " (" << CE->getStmtClassName() << ", " 5619 << CE->getCastKindName() 5620 << ", " << CE->getType().getAsString() 5621 << ")"; 5622 } 5623 5624 // Expressions need a newline. 5625 if (isa<Expr>(S)) 5626 OS << '\n'; 5627 5628 break; 5629 } 5630 5631 case CFGElement::Kind::Initializer: 5632 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer()); 5633 OS << '\n'; 5634 break; 5635 5636 case CFGElement::Kind::AutomaticObjectDtor: { 5637 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>(); 5638 const VarDecl *VD = DE.getVarDecl(); 5639 Helper.handleDecl(VD, OS); 5640 5641 QualType T = VD->getType(); 5642 if (T->isReferenceType()) 5643 T = getReferenceInitTemporaryType(VD->getInit(), nullptr); 5644 5645 OS << ".~"; 5646 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5647 OS << "() (Implicit destructor)\n"; 5648 break; 5649 } 5650 5651 case CFGElement::Kind::LifetimeEnds: 5652 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS); 5653 OS << " (Lifetime ends)\n"; 5654 break; 5655 5656 case CFGElement::Kind::LoopExit: 5657 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n"; 5658 break; 5659 5660 case CFGElement::Kind::ScopeBegin: 5661 OS << "CFGScopeBegin("; 5662 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl()) 5663 OS << VD->getQualifiedNameAsString(); 5664 OS << ")\n"; 5665 break; 5666 5667 case CFGElement::Kind::ScopeEnd: 5668 OS << "CFGScopeEnd("; 5669 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl()) 5670 OS << VD->getQualifiedNameAsString(); 5671 OS << ")\n"; 5672 break; 5673 5674 case CFGElement::Kind::NewAllocator: 5675 OS << "CFGNewAllocator("; 5676 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr()) 5677 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5678 OS << ")\n"; 5679 break; 5680 5681 case CFGElement::Kind::DeleteDtor: { 5682 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>(); 5683 const CXXRecordDecl *RD = DE.getCXXRecordDecl(); 5684 if (!RD) 5685 return; 5686 CXXDeleteExpr *DelExpr = 5687 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr()); 5688 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS); 5689 OS << "->~" << RD->getName().str() << "()"; 5690 OS << " (Implicit destructor)\n"; 5691 break; 5692 } 5693 5694 case CFGElement::Kind::BaseDtor: { 5695 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier(); 5696 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 5697 OS << " (Base object destructor)\n"; 5698 break; 5699 } 5700 5701 case CFGElement::Kind::MemberDtor: { 5702 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl(); 5703 const Type *T = FD->getType()->getBaseElementTypeUnsafe(); 5704 OS << "this->" << FD->getName(); 5705 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 5706 OS << " (Member object destructor)\n"; 5707 break; 5708 } 5709 5710 case CFGElement::Kind::TemporaryDtor: { 5711 const CXXBindTemporaryExpr *BT = 5712 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr(); 5713 OS << "~"; 5714 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts())); 5715 OS << "() (Temporary object destructor)\n"; 5716 break; 5717 } 5718 } 5719 } 5720 5721 static void print_block(raw_ostream &OS, const CFG* cfg, 5722 const CFGBlock &B, 5723 StmtPrinterHelper &Helper, bool print_edges, 5724 bool ShowColors) { 5725 Helper.setBlockID(B.getBlockID()); 5726 5727 // Print the header. 5728 if (ShowColors) 5729 OS.changeColor(raw_ostream::YELLOW, true); 5730 5731 OS << "\n [B" << B.getBlockID(); 5732 5733 if (&B == &cfg->getEntry()) 5734 OS << " (ENTRY)]\n"; 5735 else if (&B == &cfg->getExit()) 5736 OS << " (EXIT)]\n"; 5737 else if (&B == cfg->getIndirectGotoBlock()) 5738 OS << " (INDIRECT GOTO DISPATCH)]\n"; 5739 else if (B.hasNoReturnElement()) 5740 OS << " (NORETURN)]\n"; 5741 else 5742 OS << "]\n"; 5743 5744 if (ShowColors) 5745 OS.resetColor(); 5746 5747 // Print the label of this block. 5748 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 5749 if (print_edges) 5750 OS << " "; 5751 5752 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 5753 OS << L->getName(); 5754 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 5755 OS << "case "; 5756 if (const Expr *LHS = C->getLHS()) 5757 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5758 if (const Expr *RHS = C->getRHS()) { 5759 OS << " ... "; 5760 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts())); 5761 } 5762 } else if (isa<DefaultStmt>(Label)) 5763 OS << "default"; 5764 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 5765 OS << "catch ("; 5766 if (const VarDecl *ED = CS->getExceptionDecl()) 5767 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0); 5768 else 5769 OS << "..."; 5770 OS << ")"; 5771 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) { 5772 OS << "@catch ("; 5773 if (const VarDecl *PD = CS->getCatchParamDecl()) 5774 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0); 5775 else 5776 OS << "..."; 5777 OS << ")"; 5778 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) { 5779 OS << "__except ("; 5780 ES->getFilterExpr()->printPretty(OS, &Helper, 5781 PrintingPolicy(Helper.getLangOpts()), 0); 5782 OS << ")"; 5783 } else 5784 llvm_unreachable("Invalid label statement in CFGBlock."); 5785 5786 OS << ":\n"; 5787 } 5788 5789 // Iterate through the statements in the block and print them. 5790 unsigned j = 1; 5791 5792 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 5793 I != E ; ++I, ++j ) { 5794 // Print the statement # in the basic block and the statement itself. 5795 if (print_edges) 5796 OS << " "; 5797 5798 OS << llvm::format("%3d", j) << ": "; 5799 5800 Helper.setStmtID(j); 5801 5802 print_elem(OS, Helper, *I); 5803 } 5804 5805 // Print the terminator of this block. 5806 if (B.getTerminator().isValid()) { 5807 if (ShowColors) 5808 OS.changeColor(raw_ostream::GREEN); 5809 5810 OS << " T: "; 5811 5812 Helper.setBlockID(-1); 5813 5814 PrintingPolicy PP(Helper.getLangOpts()); 5815 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP); 5816 TPrinter.print(B.getTerminator()); 5817 OS << '\n'; 5818 5819 if (ShowColors) 5820 OS.resetColor(); 5821 } 5822 5823 if (print_edges) { 5824 // Print the predecessors of this block. 5825 if (!B.pred_empty()) { 5826 const raw_ostream::Colors Color = raw_ostream::BLUE; 5827 if (ShowColors) 5828 OS.changeColor(Color); 5829 OS << " Preds " ; 5830 if (ShowColors) 5831 OS.resetColor(); 5832 OS << '(' << B.pred_size() << "):"; 5833 unsigned i = 0; 5834 5835 if (ShowColors) 5836 OS.changeColor(Color); 5837 5838 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 5839 I != E; ++I, ++i) { 5840 if (i % 10 == 8) 5841 OS << "\n "; 5842 5843 CFGBlock *B = *I; 5844 bool Reachable = true; 5845 if (!B) { 5846 Reachable = false; 5847 B = I->getPossiblyUnreachableBlock(); 5848 } 5849 5850 OS << " B" << B->getBlockID(); 5851 if (!Reachable) 5852 OS << "(Unreachable)"; 5853 } 5854 5855 if (ShowColors) 5856 OS.resetColor(); 5857 5858 OS << '\n'; 5859 } 5860 5861 // Print the successors of this block. 5862 if (!B.succ_empty()) { 5863 const raw_ostream::Colors Color = raw_ostream::MAGENTA; 5864 if (ShowColors) 5865 OS.changeColor(Color); 5866 OS << " Succs "; 5867 if (ShowColors) 5868 OS.resetColor(); 5869 OS << '(' << B.succ_size() << "):"; 5870 unsigned i = 0; 5871 5872 if (ShowColors) 5873 OS.changeColor(Color); 5874 5875 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 5876 I != E; ++I, ++i) { 5877 if (i % 10 == 8) 5878 OS << "\n "; 5879 5880 CFGBlock *B = *I; 5881 5882 bool Reachable = true; 5883 if (!B) { 5884 Reachable = false; 5885 B = I->getPossiblyUnreachableBlock(); 5886 } 5887 5888 if (B) { 5889 OS << " B" << B->getBlockID(); 5890 if (!Reachable) 5891 OS << "(Unreachable)"; 5892 } 5893 else { 5894 OS << " NULL"; 5895 } 5896 } 5897 5898 if (ShowColors) 5899 OS.resetColor(); 5900 OS << '\n'; 5901 } 5902 } 5903 } 5904 5905 /// dump - A simple pretty printer of a CFG that outputs to stderr. 5906 void CFG::dump(const LangOptions &LO, bool ShowColors) const { 5907 print(llvm::errs(), LO, ShowColors); 5908 } 5909 5910 /// print - A simple pretty printer of a CFG that outputs to an ostream. 5911 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { 5912 StmtPrinterHelper Helper(this, LO); 5913 5914 // Print the entry block. 5915 print_block(OS, this, getEntry(), Helper, true, ShowColors); 5916 5917 // Iterate through the CFGBlocks and print them one by one. 5918 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 5919 // Skip the entry block, because we already printed it. 5920 if (&(**I) == &getEntry() || &(**I) == &getExit()) 5921 continue; 5922 5923 print_block(OS, this, **I, Helper, true, ShowColors); 5924 } 5925 5926 // Print the exit block. 5927 print_block(OS, this, getExit(), Helper, true, ShowColors); 5928 OS << '\n'; 5929 OS.flush(); 5930 } 5931 5932 size_t CFGBlock::getIndexInCFG() const { 5933 return llvm::find(*getParent(), this) - getParent()->begin(); 5934 } 5935 5936 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 5937 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, 5938 bool ShowColors) const { 5939 print(llvm::errs(), cfg, LO, ShowColors); 5940 } 5941 5942 LLVM_DUMP_METHOD void CFGBlock::dump() const { 5943 dump(getParent(), LangOptions(), false); 5944 } 5945 5946 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 5947 /// Generally this will only be called from CFG::print. 5948 void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 5949 const LangOptions &LO, bool ShowColors) const { 5950 StmtPrinterHelper Helper(cfg, LO); 5951 print_block(OS, cfg, *this, Helper, true, ShowColors); 5952 OS << '\n'; 5953 } 5954 5955 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 5956 void CFGBlock::printTerminator(raw_ostream &OS, 5957 const LangOptions &LO) const { 5958 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO)); 5959 TPrinter.print(getTerminator()); 5960 } 5961 5962 /// printTerminatorJson - Pretty-prints the terminator in JSON format. 5963 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO, 5964 bool AddQuotes) const { 5965 std::string Buf; 5966 llvm::raw_string_ostream TempOut(Buf); 5967 5968 printTerminator(TempOut, LO); 5969 5970 Out << JsonFormat(TempOut.str(), AddQuotes); 5971 } 5972 5973 // Returns true if by simply looking at the block, we can be sure that it 5974 // results in a sink during analysis. This is useful to know when the analysis 5975 // was interrupted, and we try to figure out if it would sink eventually. 5976 // There may be many more reasons why a sink would appear during analysis 5977 // (eg. checkers may generate sinks arbitrarily), but here we only consider 5978 // sinks that would be obvious by looking at the CFG. 5979 static bool isImmediateSinkBlock(const CFGBlock *Blk) { 5980 if (Blk->hasNoReturnElement()) 5981 return true; 5982 5983 // FIXME: Throw-expressions are currently generating sinks during analysis: 5984 // they're not supported yet, and also often used for actually terminating 5985 // the program. So we should treat them as sinks in this analysis as well, 5986 // at least for now, but once we have better support for exceptions, 5987 // we'd need to carefully handle the case when the throw is being 5988 // immediately caught. 5989 if (llvm::any_of(*Blk, [](const CFGElement &Elm) { 5990 if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>()) 5991 if (isa<CXXThrowExpr>(StmtElm->getStmt())) 5992 return true; 5993 return false; 5994 })) 5995 return true; 5996 5997 return false; 5998 } 5999 6000 bool CFGBlock::isInevitablySinking() const { 6001 const CFG &Cfg = *getParent(); 6002 6003 const CFGBlock *StartBlk = this; 6004 if (isImmediateSinkBlock(StartBlk)) 6005 return true; 6006 6007 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList; 6008 llvm::SmallPtrSet<const CFGBlock *, 32> Visited; 6009 6010 DFSWorkList.push_back(StartBlk); 6011 while (!DFSWorkList.empty()) { 6012 const CFGBlock *Blk = DFSWorkList.back(); 6013 DFSWorkList.pop_back(); 6014 Visited.insert(Blk); 6015 6016 // If at least one path reaches the CFG exit, it means that control is 6017 // returned to the caller. For now, say that we are not sure what 6018 // happens next. If necessary, this can be improved to analyze 6019 // the parent StackFrameContext's call site in a similar manner. 6020 if (Blk == &Cfg.getExit()) 6021 return false; 6022 6023 for (const auto &Succ : Blk->succs()) { 6024 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) { 6025 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) { 6026 // If the block has reachable child blocks that aren't no-return, 6027 // add them to the worklist. 6028 DFSWorkList.push_back(SuccBlk); 6029 } 6030 } 6031 } 6032 } 6033 6034 // Nothing reached the exit. It can only mean one thing: there's no return. 6035 return true; 6036 } 6037 6038 const Expr *CFGBlock::getLastCondition() const { 6039 // If the terminator is a temporary dtor or a virtual base, etc, we can't 6040 // retrieve a meaningful condition, bail out. 6041 if (Terminator.getKind() != CFGTerminator::StmtBranch) 6042 return nullptr; 6043 6044 // Also, if this method was called on a block that doesn't have 2 successors, 6045 // this block doesn't have retrievable condition. 6046 if (succ_size() < 2) 6047 return nullptr; 6048 6049 // FIXME: Is there a better condition expression we can return in this case? 6050 if (size() == 0) 6051 return nullptr; 6052 6053 auto StmtElem = rbegin()->getAs<CFGStmt>(); 6054 if (!StmtElem) 6055 return nullptr; 6056 6057 const Stmt *Cond = StmtElem->getStmt(); 6058 if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond)) 6059 return nullptr; 6060 6061 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence 6062 // the cast<>. 6063 return cast<Expr>(Cond)->IgnoreParens(); 6064 } 6065 6066 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) { 6067 Stmt *Terminator = getTerminatorStmt(); 6068 if (!Terminator) 6069 return nullptr; 6070 6071 Expr *E = nullptr; 6072 6073 switch (Terminator->getStmtClass()) { 6074 default: 6075 break; 6076 6077 case Stmt::CXXForRangeStmtClass: 6078 E = cast<CXXForRangeStmt>(Terminator)->getCond(); 6079 break; 6080 6081 case Stmt::ForStmtClass: 6082 E = cast<ForStmt>(Terminator)->getCond(); 6083 break; 6084 6085 case Stmt::WhileStmtClass: 6086 E = cast<WhileStmt>(Terminator)->getCond(); 6087 break; 6088 6089 case Stmt::DoStmtClass: 6090 E = cast<DoStmt>(Terminator)->getCond(); 6091 break; 6092 6093 case Stmt::IfStmtClass: 6094 E = cast<IfStmt>(Terminator)->getCond(); 6095 break; 6096 6097 case Stmt::ChooseExprClass: 6098 E = cast<ChooseExpr>(Terminator)->getCond(); 6099 break; 6100 6101 case Stmt::IndirectGotoStmtClass: 6102 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 6103 break; 6104 6105 case Stmt::SwitchStmtClass: 6106 E = cast<SwitchStmt>(Terminator)->getCond(); 6107 break; 6108 6109 case Stmt::BinaryConditionalOperatorClass: 6110 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 6111 break; 6112 6113 case Stmt::ConditionalOperatorClass: 6114 E = cast<ConditionalOperator>(Terminator)->getCond(); 6115 break; 6116 6117 case Stmt::BinaryOperatorClass: // '&&' and '||' 6118 E = cast<BinaryOperator>(Terminator)->getLHS(); 6119 break; 6120 6121 case Stmt::ObjCForCollectionStmtClass: 6122 return Terminator; 6123 } 6124 6125 if (!StripParens) 6126 return E; 6127 6128 return E ? E->IgnoreParens() : nullptr; 6129 } 6130 6131 //===----------------------------------------------------------------------===// 6132 // CFG Graphviz Visualization 6133 //===----------------------------------------------------------------------===// 6134 6135 #ifndef NDEBUG 6136 static StmtPrinterHelper* GraphHelper; 6137 #endif 6138 6139 void CFG::viewCFG(const LangOptions &LO) const { 6140 #ifndef NDEBUG 6141 StmtPrinterHelper H(this, LO); 6142 GraphHelper = &H; 6143 llvm::ViewGraph(this,"CFG"); 6144 GraphHelper = nullptr; 6145 #endif 6146 } 6147 6148 namespace llvm { 6149 6150 template<> 6151 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 6152 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 6153 6154 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 6155 #ifndef NDEBUG 6156 std::string OutSStr; 6157 llvm::raw_string_ostream Out(OutSStr); 6158 print_block(Out,Graph, *Node, *GraphHelper, false, false); 6159 std::string& OutStr = Out.str(); 6160 6161 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 6162 6163 // Process string output to make it nicer... 6164 for (unsigned i = 0; i != OutStr.length(); ++i) 6165 if (OutStr[i] == '\n') { // Left justify 6166 OutStr[i] = '\\'; 6167 OutStr.insert(OutStr.begin()+i+1, 'l'); 6168 } 6169 6170 return OutStr; 6171 #else 6172 return {}; 6173 #endif 6174 } 6175 }; 6176 6177 } // namespace llvm 6178