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