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