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