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