1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the CFG and CFGBuilder classes for representing and
10 // building Control-Flow Graphs (CFGs) from ASTs.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Analysis/CFG.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclGroup.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/OperationKinds.h"
24 #include "clang/AST/PrettyPrinter.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/StmtObjC.h"
28 #include "clang/AST/StmtVisitor.h"
29 #include "clang/AST/Type.h"
30 #include "clang/Analysis/ConstructionContext.h"
31 #include "clang/Analysis/Support/BumpVector.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/JsonSupport.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/APSInt.h"
41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/Optional.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/SetVector.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/Support/Allocator.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/DOTGraphTraits.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/GraphWriter.h"
55 #include "llvm/Support/SaveAndRestore.h"
56 #include "llvm/Support/raw_ostream.h"
64 using namespace clang;
66 static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(D))
68 if (Expr *Ex = VD->getInit())
69 return Ex->getSourceRange().getEnd();
70 return D->getLocation();
73 /// Returns true on constant values based around a single IntegerLiteral.
74 /// Allow for use of parentheses, integer casts, and negative signs.
75 static bool IsIntegerLiteralConstantExpr(const Expr *E) {
77 E = E->IgnoreParens();
79 // Allow conversions to different integer kind.
80 if (const auto *CE = dyn_cast<CastExpr>(E)) {
81 if (CE->getCastKind() != CK_IntegralCast)
86 // Allow negative numbers.
87 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
88 if (UO->getOpcode() != UO_Minus)
93 return isa<IntegerLiteral>(E);
96 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
97 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
99 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
100 E = E->IgnoreParens();
101 if (IsIntegerLiteralConstantExpr(E))
103 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
104 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
108 /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
109 /// NumExpr is an integer literal or an enum constant.
111 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
113 static std::tuple<const Expr *, BinaryOperatorKind, const Expr *>
114 tryNormalizeBinaryOperator(const BinaryOperator *B) {
115 BinaryOperatorKind Op = B->getOpcode();
117 const Expr *MaybeDecl = B->getLHS();
118 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
119 // Expr looked like `0 == Foo` instead of `Foo == 0`
120 if (Constant == nullptr) {
124 else if (Op == BO_GE)
126 else if (Op == BO_LT)
128 else if (Op == BO_LE)
131 MaybeDecl = B->getRHS();
132 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
135 return std::make_tuple(MaybeDecl, Op, Constant);
138 /// For an expression `x == Foo && x == Bar`, this determines whether the
139 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
142 /// It's an error to pass this arguments that are not either IntegerLiterals
143 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
144 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
145 // User intent isn't clear if they're mixing int literals with enum
147 if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
150 // Integer literal comparisons, regardless of literal type, are acceptable.
151 if (!isa<DeclRefExpr>(E1))
154 // IntegerLiterals are handled above and only EnumConstantDecls are expected
156 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
157 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
158 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
160 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
161 const DeclContext *DC1 = Decl1->getDeclContext();
162 const DeclContext *DC2 = Decl2->getDeclContext();
164 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
172 /// The CFG builder uses a recursive algorithm to build the CFG. When
173 /// we process an expression, sometimes we know that we must add the
174 /// subexpressions as block-level expressions. For example:
178 /// When processing the '||' expression, we know that exp1 and exp2
179 /// need to be added as block-level expressions, even though they
180 /// might not normally need to be. AddStmtChoice records this
181 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
182 /// the builder has an option not to add a subexpression as a
183 /// block-level expression.
184 class AddStmtChoice {
186 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
188 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
190 bool alwaysAdd(CFGBuilder &builder,
191 const Stmt *stmt) const;
193 /// Return a copy of this object, except with the 'always-add' bit
194 /// set as specified.
195 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
196 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
203 /// LocalScope - Node in tree of local scopes created for C++ implicit
204 /// destructor calls generation. It contains list of automatic variables
205 /// declared in the scope and link to position in previous scope this scope
208 /// The process of creating local scopes is as follows:
209 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
210 /// - Before processing statements in scope (e.g. CompoundStmt) create
211 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
212 /// and set CFGBuilder::ScopePos to the end of new scope,
213 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
215 /// - For every normal (without jump) end of scope add to CFGBlock destructors
216 /// for objects in the current scope,
217 /// - For every jump add to CFGBlock destructors for objects
218 /// between CFGBuilder::ScopePos and local scope position saved for jump
219 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
220 /// jump target position will be on the path to root from CFGBuilder::ScopePos
221 /// (adding any variable that doesn't need constructor to be called to
222 /// LocalScope can break this assumption),
226 friend class const_iterator;
228 using AutomaticVarsTy = BumpVector<VarDecl *>;
230 /// const_iterator - Iterates local scope backwards and jumps to previous
231 /// scope on reaching the beginning of currently iterated scope.
232 class const_iterator {
233 const LocalScope* Scope = nullptr;
235 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
236 /// Invalid iterator (with null Scope) has VarIter equal to 0.
237 unsigned VarIter = 0;
240 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
241 /// Incrementing invalid iterator is allowed and will result in invalid
243 const_iterator() = default;
245 /// Create valid iterator. In case when S.Prev is an invalid iterator and
246 /// I is equal to 0, this will create invalid iterator.
247 const_iterator(const LocalScope& S, unsigned I)
248 : Scope(&S), VarIter(I) {
249 // Iterator to "end" of scope is not allowed. Handle it by going up
250 // in scopes tree possibly up to invalid iterator in the root.
251 if (VarIter == 0 && Scope)
255 VarDecl *const* operator->() const {
256 assert(Scope && "Dereferencing invalid iterator is not allowed");
257 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
258 return &Scope->Vars[VarIter - 1];
261 const VarDecl *getFirstVarInScope() const {
262 assert(Scope && "Dereferencing invalid iterator is not allowed");
263 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
264 return Scope->Vars[0];
267 VarDecl *operator*() const {
268 return *this->operator->();
271 const_iterator &operator++() {
275 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
281 const_iterator operator++(int) {
282 const_iterator P = *this;
287 bool operator==(const const_iterator &rhs) const {
288 return Scope == rhs.Scope && VarIter == rhs.VarIter;
290 bool operator!=(const const_iterator &rhs) const {
291 return !(*this == rhs);
294 explicit operator bool() const {
295 return *this != const_iterator();
298 int distance(const_iterator L);
299 const_iterator shared_parent(const_iterator L);
300 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
304 BumpVectorContext ctx;
306 /// Automatic variables in order of declaration.
307 AutomaticVarsTy Vars;
309 /// Iterator to variable in previous scope that was declared just before
310 /// begin of this scope.
314 /// Constructs empty scope linked to previous scope in specified place.
315 LocalScope(BumpVectorContext ctx, const_iterator P)
316 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
318 /// Begin of scope in direction of CFG building (backwards).
319 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
321 void addVar(VarDecl *VD) {
322 Vars.push_back(VD, ctx);
328 /// distance - Calculates distance from this to L. L must be reachable from this
329 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
330 /// number of scopes between this and L.
331 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
333 const_iterator F = *this;
334 while (F.Scope != L.Scope) {
335 assert(F != const_iterator() &&
336 "L iterator is not reachable from F iterator.");
340 D += F.VarIter - L.VarIter;
344 /// Calculates the closest parent of this iterator
345 /// that is in a scope reachable through the parents of L.
346 /// I.e. when using 'goto' from this to L, the lifetime of all variables
347 /// between this and shared_parent(L) end.
348 LocalScope::const_iterator
349 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
350 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
352 ScopesOfL.insert(L.Scope);
353 if (L == const_iterator())
358 const_iterator F = *this;
360 if (ScopesOfL.count(F.Scope))
362 assert(F != const_iterator() &&
363 "L iterator is not reachable from F iterator.");
370 /// Structure for specifying position in CFG during its build process. It
371 /// consists of CFGBlock that specifies position in CFG and
372 /// LocalScope::const_iterator that specifies position in LocalScope graph.
373 struct BlockScopePosPair {
374 CFGBlock *block = nullptr;
375 LocalScope::const_iterator scopePosition;
377 BlockScopePosPair() = default;
378 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
379 : block(b), scopePosition(scopePos) {}
382 /// TryResult - a class representing a variant over the values
383 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
384 /// and is used by the CFGBuilder to decide if a branch condition
385 /// can be decided up front during CFG construction.
390 TryResult() = default;
391 TryResult(bool b) : X(b ? 1 : 0) {}
393 bool isTrue() const { return X == 1; }
394 bool isFalse() const { return X == 0; }
395 bool isKnown() const { return X >= 0; }
405 static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
406 if (!R1.isKnown() || !R2.isKnown())
408 return TryResult(R1.isTrue() && R2.isTrue());
413 class reverse_children {
414 llvm::SmallVector<Stmt *, 12> childrenBuf;
415 ArrayRef<Stmt *> children;
418 reverse_children(Stmt *S);
420 using iterator = ArrayRef<Stmt *>::reverse_iterator;
422 iterator begin() const { return children.rbegin(); }
423 iterator end() const { return children.rend(); }
428 reverse_children::reverse_children(Stmt *S) {
429 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
430 children = CE->getRawSubExprs();
433 switch (S->getStmtClass()) {
434 // Note: Fill in this switch with more cases we want to optimize.
435 case Stmt::InitListExprClass: {
436 InitListExpr *IE = cast<InitListExpr>(S);
437 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
445 // Default case for all other statements.
446 for (Stmt *SubStmt : S->children())
447 childrenBuf.push_back(SubStmt);
449 // This needs to be done *after* childrenBuf has been populated.
450 children = childrenBuf;
455 /// CFGBuilder - This class implements CFG construction from an AST.
456 /// The builder is stateful: an instance of the builder should be used to only
457 /// construct a single CFG.
461 /// CFGBuilder builder;
462 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
464 /// CFG construction is done via a recursive walk of an AST. We actually parse
465 /// the AST in reverse order so that the successor of a basic block is
466 /// constructed prior to its predecessor. This allows us to nicely capture
467 /// implicit fall-throughs without extra basic blocks.
469 using JumpTarget = BlockScopePosPair;
470 using JumpSource = BlockScopePosPair;
473 std::unique_ptr<CFG> cfg;
476 CFGBlock *Block = nullptr;
478 // Block after the current block.
479 CFGBlock *Succ = nullptr;
481 JumpTarget ContinueJumpTarget;
482 JumpTarget BreakJumpTarget;
483 JumpTarget SEHLeaveJumpTarget;
484 CFGBlock *SwitchTerminatedBlock = nullptr;
485 CFGBlock *DefaultCaseBlock = nullptr;
487 // This can point either to a try or a __try block. The frontend forbids
488 // mixing both kinds in one function, so having one for both is enough.
489 CFGBlock *TryTerminatedBlock = nullptr;
491 // Current position in local scope.
492 LocalScope::const_iterator ScopePos;
494 // LabelMap records the mapping from Label expressions to their jump targets.
495 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
498 // A list of blocks that end with a "goto" that must be backpatched to their
499 // resolved targets upon completion of CFG construction.
500 using BackpatchBlocksTy = std::vector<JumpSource>;
501 BackpatchBlocksTy BackpatchBlocks;
503 // A list of labels whose address has been taken (for indirect gotos).
504 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
505 LabelSetTy AddressTakenLabels;
507 // Information about the currently visited C++ object construction site.
508 // This is set in the construction trigger and read when the constructor
509 // or a function that returns an object by value is being visited.
510 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
511 ConstructionContextMap;
513 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
514 DeclsWithEndedScopeSetTy DeclsWithEndedScope;
517 const CFG::BuildOptions &BuildOpts;
519 // State to track for building switch statements.
520 bool switchExclusivelyCovered = false;
521 Expr::EvalResult *switchCond = nullptr;
523 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
524 const Stmt *lastLookup = nullptr;
526 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
527 // during construction of branches for chained logical operators.
528 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
529 CachedBoolEvalsTy CachedBoolEvals;
532 explicit CFGBuilder(ASTContext *astContext,
533 const CFG::BuildOptions &buildOpts)
534 : Context(astContext), cfg(new CFG()), // crew a new CFG
535 ConstructionContextMap(), BuildOpts(buildOpts) {}
538 // buildCFG - Used by external clients to construct the CFG.
539 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
541 bool alwaysAdd(const Stmt *stmt);
544 // Visitors to walk an AST and construct the CFG.
545 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
546 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
547 CFGBlock *VisitBreakStmt(BreakStmt *B);
548 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
549 CFGBlock *VisitCaseStmt(CaseStmt *C);
550 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
551 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
552 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
554 CFGBlock *VisitContinueStmt(ContinueStmt *C);
555 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
557 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
558 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
559 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
560 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
561 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
562 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
564 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
566 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
567 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
568 CFGBlock *VisitDeclStmt(DeclStmt *DS);
569 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
570 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
571 CFGBlock *VisitDoStmt(DoStmt *D);
572 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
573 AddStmtChoice asc, bool ExternallyDestructed);
574 CFGBlock *VisitForStmt(ForStmt *F);
575 CFGBlock *VisitGotoStmt(GotoStmt *G);
576 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
577 CFGBlock *VisitIfStmt(IfStmt *I);
578 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
579 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
580 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
581 CFGBlock *VisitLabelStmt(LabelStmt *L);
582 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
583 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
584 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
585 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
588 CFGBlock *FalseBlock);
589 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
591 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
592 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
593 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
594 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
595 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
596 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
597 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
598 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
599 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
600 CFGBlock *VisitReturnStmt(Stmt *S);
601 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
602 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
603 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
604 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
605 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
606 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
607 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
609 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
610 CFGBlock *VisitWhileStmt(WhileStmt *W);
612 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
613 bool ExternallyDestructed = false);
614 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
615 CFGBlock *VisitChildren(Stmt *S);
616 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
617 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
620 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
622 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
623 appendScopeBegin(B, VD, S);
626 /// When creating the CFG for temporary destructors, we want to mirror the
627 /// branch structure of the corresponding constructor calls.
628 /// Thus, while visiting a statement for temporary destructors, we keep a
629 /// context to keep track of the following information:
630 /// - whether a subexpression is executed unconditionally
631 /// - if a subexpression is executed conditionally, the first
632 /// CXXBindTemporaryExpr we encounter in that subexpression (which
633 /// corresponds to the last temporary destructor we have to call for this
634 /// subexpression) and the CFG block at that point (which will become the
635 /// successor block when inserting the decision point).
637 /// That way, we can build the branch structure for temporary destructors as
639 /// 1. If a subexpression is executed unconditionally, we add the temporary
640 /// destructor calls to the current block.
641 /// 2. If a subexpression is executed conditionally, when we encounter a
642 /// CXXBindTemporaryExpr:
643 /// a) If it is the first temporary destructor call in the subexpression,
644 /// we remember the CXXBindTemporaryExpr and the current block in the
645 /// TempDtorContext; we start a new block, and insert the temporary
647 /// b) Otherwise, add the temporary destructor call to the current block.
648 /// 3. When we finished visiting a conditionally executed subexpression,
649 /// and we found at least one temporary constructor during the visitation
650 /// (2.a has executed), we insert a decision block that uses the
651 /// CXXBindTemporaryExpr as terminator, and branches to the current block
652 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
653 /// branches to the stored successor.
654 struct TempDtorContext {
655 TempDtorContext() = default;
656 TempDtorContext(TryResult KnownExecuted)
657 : IsConditional(true), KnownExecuted(KnownExecuted) {}
659 /// Returns whether we need to start a new branch for a temporary destructor
660 /// call. This is the case when the temporary destructor is
661 /// conditionally executed, and it is the first one we encounter while
662 /// visiting a subexpression - other temporary destructors at the same level
663 /// will be added to the same block and are executed under the same
665 bool needsTempDtorBranch() const {
666 return IsConditional && !TerminatorExpr;
669 /// Remember the successor S of a temporary destructor decision branch for
670 /// the corresponding CXXBindTemporaryExpr E.
671 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
676 const bool IsConditional = false;
677 const TryResult KnownExecuted = true;
678 CFGBlock *Succ = nullptr;
679 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
682 // Visitors to walk an AST and generate destructors of temporaries in
684 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
685 TempDtorContext &Context);
686 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
687 TempDtorContext &Context);
688 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
689 bool ExternallyDestructed,
690 TempDtorContext &Context);
691 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
692 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
693 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
694 AbstractConditionalOperator *E, bool ExternallyDestructed,
695 TempDtorContext &Context);
696 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
697 CFGBlock *FalseSucc = nullptr);
699 // NYS == Not Yet Supported
705 // Remember to apply the construction context based on the current \p Layer
706 // when constructing the CFG element for \p CE.
707 void consumeConstructionContext(const ConstructionContextLayer *Layer,
710 // Scan \p Child statement to find constructors in it, while keeping in mind
711 // that its parent statement is providing a partial construction context
712 // described by \p Layer. If a constructor is found, it would be assigned
713 // the context based on the layer. If an additional construction context layer
714 // is found, the function recurses into that.
715 void findConstructionContexts(const ConstructionContextLayer *Layer,
718 // Scan all arguments of a call expression for a construction context.
719 // These sorts of call expressions don't have a common superclass,
720 // hence strict duck-typing.
721 template <typename CallLikeExpr,
722 typename = typename std::enable_if<
723 std::is_same<CallLikeExpr, CallExpr>::value ||
724 std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
725 std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
726 void findConstructionContextsForArguments(CallLikeExpr *E) {
727 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
728 Expr *Arg = E->getArg(i);
729 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
730 findConstructionContexts(
731 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
732 ConstructionContextItem(E, i)),
737 // Unset the construction context after consuming it. This is done immediately
738 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
739 // there's no need to do this manually in every Visit... function.
740 void cleanupConstructionContext(Expr *E);
742 void autoCreateBlock() { if (!Block) Block = createBlock(); }
743 CFGBlock *createBlock(bool add_successor = true);
744 CFGBlock *createNoReturnBlock();
746 CFGBlock *addStmt(Stmt *S) {
747 return Visit(S, AddStmtChoice::AlwaysAdd);
750 CFGBlock *addInitializer(CXXCtorInitializer *I);
751 void addLoopExit(const Stmt *LoopStmt);
752 void addAutomaticObjDtors(LocalScope::const_iterator B,
753 LocalScope::const_iterator E, Stmt *S);
754 void addLifetimeEnds(LocalScope::const_iterator B,
755 LocalScope::const_iterator E, Stmt *S);
756 void addAutomaticObjHandling(LocalScope::const_iterator B,
757 LocalScope::const_iterator E, Stmt *S);
758 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
759 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
762 void getDeclsWithEndedScope(LocalScope::const_iterator B,
763 LocalScope::const_iterator E, Stmt *S);
765 // Local scopes creation.
766 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
768 void addLocalScopeForStmt(Stmt *S);
769 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
770 LocalScope* Scope = nullptr);
771 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
773 void addLocalScopeAndDtors(Stmt *S);
775 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
776 if (!BuildOpts.AddRichCXXConstructors)
779 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
783 cleanupConstructionContext(E);
784 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
788 // Interface to CFGBlock - adding CFGElements.
790 void appendStmt(CFGBlock *B, const Stmt *S) {
791 if (alwaysAdd(S) && cachedEntry)
792 cachedEntry->second = B;
794 // All block-level expressions should have already been IgnoreParens()ed.
795 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
796 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
799 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
800 if (const ConstructionContext *CC =
801 retrieveAndCleanupConstructionContext(CE)) {
802 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
806 // No valid construction context found. Fall back to statement.
807 B->appendStmt(CE, cfg->getBumpVectorContext());
810 void appendCall(CFGBlock *B, CallExpr *CE) {
811 if (alwaysAdd(CE) && cachedEntry)
812 cachedEntry->second = B;
814 if (const ConstructionContext *CC =
815 retrieveAndCleanupConstructionContext(CE)) {
816 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
820 // No valid construction context found. Fall back to statement.
821 B->appendStmt(CE, cfg->getBumpVectorContext());
824 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
825 B->appendInitializer(I, cfg->getBumpVectorContext());
828 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
829 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
832 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
833 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
836 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
837 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
840 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
841 if (alwaysAdd(ME) && cachedEntry)
842 cachedEntry->second = B;
844 if (const ConstructionContext *CC =
845 retrieveAndCleanupConstructionContext(ME)) {
846 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
850 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
851 cfg->getBumpVectorContext());
854 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
855 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
858 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
859 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
862 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
863 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
866 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
867 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
870 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
871 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
874 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
875 LocalScope::const_iterator B, LocalScope::const_iterator E);
877 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
878 LocalScope::const_iterator B,
879 LocalScope::const_iterator E);
882 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
883 LocalScope::const_iterator B,
884 LocalScope::const_iterator E);
886 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
887 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
888 cfg->getBumpVectorContext());
891 /// Add a reachable successor to a block, with the alternate variant that is
893 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
894 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
895 cfg->getBumpVectorContext());
898 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
899 if (BuildOpts.AddScopes)
900 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
903 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
904 if (BuildOpts.AddScopes)
905 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
908 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
909 if (BuildOpts.AddScopes)
910 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
913 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
914 if (BuildOpts.AddScopes)
915 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
918 /// Find a relational comparison with an expression evaluating to a
919 /// boolean and a constant other than 0 and 1.
920 /// e.g. if ((x < y) == 10)
921 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
922 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
923 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
925 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
926 const Expr *BoolExpr = RHSExpr;
927 bool IntFirst = true;
929 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
934 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
937 llvm::APInt IntValue = IntLiteral->getValue();
938 if ((IntValue == 1) || (IntValue == 0))
941 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
942 !IntValue.isNegative();
944 BinaryOperatorKind Bok = B->getOpcode();
945 if (Bok == BO_GT || Bok == BO_GE) {
946 // Always true for 10 > bool and bool > -1
947 // Always false for -1 > bool and bool > 10
948 return TryResult(IntFirst == IntLarger);
950 // Always true for -1 < bool and bool < 10
951 // Always false for 10 < bool and bool < -1
952 return TryResult(IntFirst != IntLarger);
956 /// Find an incorrect equality comparison. Either with an expression
957 /// evaluating to a boolean and a constant other than 0 and 1.
958 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
959 /// true/false e.q. (x & 8) == 4.
960 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
961 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
962 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
964 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
965 const Expr *BoolExpr = RHSExpr;
968 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
975 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
976 if (BitOp && (BitOp->getOpcode() == BO_And ||
977 BitOp->getOpcode() == BO_Or)) {
978 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
979 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
981 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
984 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
989 llvm::APInt L1 = IntLiteral->getValue();
990 llvm::APInt L2 = IntLiteral2->getValue();
991 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
992 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
993 if (BuildOpts.Observer)
994 BuildOpts.Observer->compareBitwiseEquality(B,
995 B->getOpcode() != BO_EQ);
996 TryResult(B->getOpcode() != BO_EQ);
998 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
999 llvm::APInt IntValue = IntLiteral->getValue();
1000 if ((IntValue == 1) || (IntValue == 0)) {
1003 return TryResult(B->getOpcode() != BO_EQ);
1009 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
1010 const llvm::APSInt &Value1,
1011 const llvm::APSInt &Value2) {
1012 assert(Value1.isSigned() == Value2.isSigned());
1017 return TryResult(Value1 == Value2);
1019 return TryResult(Value1 != Value2);
1021 return TryResult(Value1 < Value2);
1023 return TryResult(Value1 <= Value2);
1025 return TryResult(Value1 > Value2);
1027 return TryResult(Value1 >= Value2);
1031 /// Find a pair of comparison expressions with or without parentheses
1032 /// with a shared variable and constants and a logical operator between them
1033 /// that always evaluates to either true or false.
1034 /// e.g. if (x != 3 || x != 4)
1035 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1036 assert(B->isLogicalOp());
1037 const BinaryOperator *LHS =
1038 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
1039 const BinaryOperator *RHS =
1040 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
1044 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
1047 const Expr *DeclExpr1;
1048 const Expr *NumExpr1;
1049 BinaryOperatorKind BO1;
1050 std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
1052 if (!DeclExpr1 || !NumExpr1)
1055 const Expr *DeclExpr2;
1056 const Expr *NumExpr2;
1057 BinaryOperatorKind BO2;
1058 std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
1060 if (!DeclExpr2 || !NumExpr2)
1063 // Check that it is the same variable on both sides.
1064 if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
1067 // Make sure the user's intent is clear (e.g. they're comparing against two
1068 // int literals, or two things from the same enum)
1069 if (!areExprTypesCompatible(NumExpr1, NumExpr2))
1072 Expr::EvalResult L1Result, L2Result;
1073 if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
1074 !NumExpr2->EvaluateAsInt(L2Result, *Context))
1077 llvm::APSInt L1 = L1Result.Val.getInt();
1078 llvm::APSInt L2 = L2Result.Val.getInt();
1080 // Can't compare signed with unsigned or with different bit width.
1081 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
1084 // Values that will be used to determine if result of logical
1085 // operator is always true/false
1086 const llvm::APSInt Values[] = {
1087 // Value less than both Value1 and Value2
1088 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1091 // Value between Value1 and Value2
1092 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1096 // Value greater than both Value1 and Value2
1097 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1100 // Check whether expression is always true/false by evaluating the following
1101 // * variable x is less than the smallest literal.
1102 // * variable x is equal to the smallest literal.
1103 // * Variable x is between smallest and largest literal.
1104 // * Variable x is equal to the largest literal.
1105 // * Variable x is greater than largest literal.
1106 bool AlwaysTrue = true, AlwaysFalse = true;
1107 // Track value of both subexpressions. If either side is always
1108 // true/false, another warning should have already been emitted.
1109 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
1110 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
1111 for (const llvm::APSInt &Value : Values) {
1112 TryResult Res1, Res2;
1113 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1114 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1116 if (!Res1.isKnown() || !Res2.isKnown())
1119 if (B->getOpcode() == BO_LAnd) {
1120 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1121 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1123 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1124 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1127 LHSAlwaysTrue &= Res1.isTrue();
1128 LHSAlwaysFalse &= Res1.isFalse();
1129 RHSAlwaysTrue &= Res2.isTrue();
1130 RHSAlwaysFalse &= Res2.isFalse();
1133 if (AlwaysTrue || AlwaysFalse) {
1134 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
1135 !RHSAlwaysFalse && BuildOpts.Observer)
1136 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1137 return TryResult(AlwaysTrue);
1142 /// A bitwise-or with a non-zero constant always evaluates to true.
1143 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
1144 const Expr *LHSConstant =
1145 tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
1146 const Expr *RHSConstant =
1147 tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
1149 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
1152 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
1154 Expr::EvalResult Result;
1155 if (!Constant->EvaluateAsInt(Result, *Context))
1158 if (Result.Val.getInt() == 0)
1161 if (BuildOpts.Observer)
1162 BuildOpts.Observer->compareBitwiseOr(B);
1164 return TryResult(true);
1167 /// Try and evaluate an expression to an integer constant.
1168 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1169 if (!BuildOpts.PruneTriviallyFalseEdges)
1171 return !S->isTypeDependent() &&
1172 !S->isValueDependent() &&
1173 S->EvaluateAsRValue(outResult, *Context);
1176 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1177 /// if we can evaluate to a known value, otherwise return -1.
1178 TryResult tryEvaluateBool(Expr *S) {
1179 if (!BuildOpts.PruneTriviallyFalseEdges ||
1180 S->isTypeDependent() || S->isValueDependent())
1183 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1184 if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
1185 // Check the cache first.
1186 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1187 if (I != CachedBoolEvals.end())
1188 return I->second; // already in map;
1190 // Retrieve result at first, or the map might be updated.
1191 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1192 CachedBoolEvals[S] = Result; // update or insert
1196 switch (Bop->getOpcode()) {
1198 // For 'x & 0' and 'x * 0', we can determine that
1199 // the value is always false.
1202 // If either operand is zero, we know the value
1204 Expr::EvalResult LHSResult;
1205 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1206 llvm::APSInt IntVal = LHSResult.Val.getInt();
1207 if (!IntVal.getBoolValue()) {
1208 return TryResult(false);
1211 Expr::EvalResult RHSResult;
1212 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1213 llvm::APSInt IntVal = RHSResult.Val.getInt();
1214 if (!IntVal.getBoolValue()) {
1215 return TryResult(false);
1224 return evaluateAsBooleanConditionNoCache(S);
1227 /// Evaluate as boolean \param E without using the cache.
1228 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1229 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1230 if (Bop->isLogicalOp()) {
1231 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1232 if (LHS.isKnown()) {
1233 // We were able to evaluate the LHS, see if we can get away with not
1234 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1235 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1236 return LHS.isTrue();
1238 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1239 if (RHS.isKnown()) {
1240 if (Bop->getOpcode() == BO_LOr)
1241 return LHS.isTrue() || RHS.isTrue();
1243 return LHS.isTrue() && RHS.isTrue();
1246 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1247 if (RHS.isKnown()) {
1248 // We can't evaluate the LHS; however, sometimes the result
1249 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1250 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1251 return RHS.isTrue();
1253 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1254 if (BopRes.isKnown())
1255 return BopRes.isTrue();
1260 } else if (Bop->isEqualityOp()) {
1261 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1262 if (BopRes.isKnown())
1263 return BopRes.isTrue();
1264 } else if (Bop->isRelationalOp()) {
1265 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1266 if (BopRes.isKnown())
1267 return BopRes.isTrue();
1268 } else if (Bop->getOpcode() == BO_Or) {
1269 TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
1270 if (BopRes.isKnown())
1271 return BopRes.isTrue();
1276 if (E->EvaluateAsBooleanCondition(Result, *Context))
1282 bool hasTrivialDestructor(VarDecl *VD);
1287 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1288 const Stmt *stmt) const {
1289 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1292 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1293 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1295 if (!BuildOpts.forcedBlkExprs)
1298 if (lastLookup == stmt) {
1300 assert(cachedEntry->first == stmt);
1308 // Perform the lookup!
1309 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1312 // No need to update 'cachedEntry', since it will always be null.
1313 assert(!cachedEntry);
1317 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1318 if (itr == fb->end()) {
1319 cachedEntry = nullptr;
1323 cachedEntry = &*itr;
1327 // FIXME: Add support for dependent-sized array types in C++?
1328 // Does it even make sense to build a CFG for an uninstantiated template?
1329 static const VariableArrayType *FindVA(const Type *t) {
1330 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1331 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1332 if (vat->getSizeExpr())
1335 t = vt->getElementType().getTypePtr();
1341 void CFGBuilder::consumeConstructionContext(
1342 const ConstructionContextLayer *Layer, Expr *E) {
1343 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1344 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
1345 if (const ConstructionContextLayer *PreviouslyStoredLayer =
1346 ConstructionContextMap.lookup(E)) {
1347 (void)PreviouslyStoredLayer;
1348 // We might have visited this child when we were finding construction
1349 // contexts within its parents.
1350 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
1351 "Already within a different construction context!");
1353 ConstructionContextMap[E] = Layer;
1357 void CFGBuilder::findConstructionContexts(
1358 const ConstructionContextLayer *Layer, Stmt *Child) {
1359 if (!BuildOpts.AddRichCXXConstructors)
1365 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1366 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1370 switch(Child->getStmtClass()) {
1371 case Stmt::CXXConstructExprClass:
1372 case Stmt::CXXTemporaryObjectExprClass: {
1373 // Support pre-C++17 copy elision AST.
1374 auto *CE = cast<CXXConstructExpr>(Child);
1375 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
1376 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1379 consumeConstructionContext(Layer, CE);
1382 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1383 // FIXME: An isa<> would look much better but this whole switch is a
1384 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1385 case Stmt::CallExprClass:
1386 case Stmt::CXXMemberCallExprClass:
1387 case Stmt::CXXOperatorCallExprClass:
1388 case Stmt::UserDefinedLiteralClass:
1389 case Stmt::ObjCMessageExprClass: {
1390 auto *E = cast<Expr>(Child);
1391 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1392 consumeConstructionContext(Layer, E);
1395 case Stmt::ExprWithCleanupsClass: {
1396 auto *Cleanups = cast<ExprWithCleanups>(Child);
1397 findConstructionContexts(Layer, Cleanups->getSubExpr());
1400 case Stmt::CXXFunctionalCastExprClass: {
1401 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
1402 findConstructionContexts(Layer, Cast->getSubExpr());
1405 case Stmt::ImplicitCastExprClass: {
1406 auto *Cast = cast<ImplicitCastExpr>(Child);
1407 // Should we support other implicit cast kinds?
1408 switch (Cast->getCastKind()) {
1410 case CK_ConstructorConversion:
1411 findConstructionContexts(Layer, Cast->getSubExpr());
1418 case Stmt::CXXBindTemporaryExprClass: {
1419 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
1420 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1423 case Stmt::MaterializeTemporaryExprClass: {
1424 // Normally we don't want to search in MaterializeTemporaryExpr because
1425 // it indicates the beginning of a temporary object construction context,
1426 // so it shouldn't be found in the middle. However, if it is the beginning
1427 // of an elidable copy or move construction context, we need to include it.
1428 if (Layer->getItem().getKind() ==
1429 ConstructionContextItem::ElidableConstructorKind) {
1430 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1431 findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr());
1435 case Stmt::ConditionalOperatorClass: {
1436 auto *CO = cast<ConditionalOperator>(Child);
1437 if (Layer->getItem().getKind() !=
1438 ConstructionContextItem::MaterializationKind) {
1439 // If the object returned by the conditional operator is not going to be a
1440 // temporary object that needs to be immediately materialized, then
1441 // it must be C++17 with its mandatory copy elision. Do not yet promise
1442 // to support this case.
1443 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1444 Context->getLangOpts().CPlusPlus17);
1447 findConstructionContexts(Layer, CO->getLHS());
1448 findConstructionContexts(Layer, CO->getRHS());
1451 case Stmt::InitListExprClass: {
1452 auto *ILE = cast<InitListExpr>(Child);
1453 if (ILE->isTransparent()) {
1454 findConstructionContexts(Layer, ILE->getInit(0));
1457 // TODO: Handle other cases. For now, fail to find construction contexts.
1465 void CFGBuilder::cleanupConstructionContext(Expr *E) {
1466 assert(BuildOpts.AddRichCXXConstructors &&
1467 "We should not be managing construction contexts!");
1468 assert(ConstructionContextMap.count(E) &&
1469 "Cannot exit construction context without the context!");
1470 ConstructionContextMap.erase(E);
1474 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1475 /// arbitrary statement. Examples include a single expression or a function
1476 /// body (compound statement). The ownership of the returned CFG is
1477 /// transferred to the caller. If CFG construction fails, this method returns
1479 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1484 // Create an empty block that will serve as the exit block for the CFG. Since
1485 // this is the first block added to the CFG, it will be implicitly registered
1486 // as the exit block.
1487 Succ = createBlock();
1488 assert(Succ == &cfg->getExit());
1489 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1491 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1492 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1494 if (BuildOpts.AddImplicitDtors)
1495 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1496 addImplicitDtorsForDestructor(DD);
1498 // Visit the statements and create the CFG.
1499 CFGBlock *B = addStmt(Statement);
1504 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1505 // are ignored unless the object is of the most derived class.
1506 // class VBase { VBase() = default; VBase(int) {} };
1507 // class A : virtual public VBase { A() : VBase(0) {} };
1508 // class B : public A {};
1509 // B b; // Constructor calls in order: VBase(), A(), B().
1510 // // VBase(0) is ignored because A isn't the most derived class.
1511 // This may result in the virtual base(s) being already initialized at this
1512 // point, in which case we should jump right onto non-virtual bases and
1513 // fields. To handle this, make a CFG branch. We only need to add one such
1514 // branch per constructor, since the Standard states that all virtual bases
1515 // shall be initialized before non-virtual bases and direct data members.
1516 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1517 CFGBlock *VBaseSucc = nullptr;
1518 for (auto *I : llvm::reverse(CD->inits())) {
1519 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1520 I->isBaseInitializer() && I->isBaseVirtual()) {
1521 // We've reached the first virtual base init while iterating in reverse
1522 // order. Make a new block for virtual base initializers so that we
1524 VBaseSucc = Succ = B ? B : &cfg->getExit();
1525 Block = createBlock();
1527 B = addInitializer(I);
1532 // Make a branch block for potentially skipping virtual base initializers.
1536 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1537 addSuccessor(B, Block, true);
1544 // Backpatch the gotos whose label -> block mappings we didn't know when we
1545 // encountered them.
1546 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1547 E = BackpatchBlocks.end(); I != E; ++I ) {
1549 CFGBlock *B = I->block;
1550 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1551 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1552 // If there is no target for the goto, then we are looking at an
1553 // incomplete AST. Handle this by not registering a successor.
1554 if (LI == LabelMap.end())
1556 JumpTarget JT = LI->second;
1557 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1559 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1561 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
1562 B, I->scopePosition, JT.scopePosition);
1563 appendScopeBegin(JT.block, VD, G);
1564 addSuccessor(B, JT.block);
1566 if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1567 CFGBlock *Successor = (I+1)->block;
1568 for (auto *L : G->labels()) {
1569 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1570 // If there is no target for the goto, then we are looking at an
1571 // incomplete AST. Handle this by not registering a successor.
1572 if (LI == LabelMap.end())
1574 JumpTarget JT = LI->second;
1575 // Successor has been added, so skip it.
1576 if (JT.block == Successor)
1578 addSuccessor(B, JT.block);
1584 // Add successors to the Indirect Goto Dispatch block (if we have one).
1585 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1586 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1587 E = AddressTakenLabels.end(); I != E; ++I ) {
1588 // Lookup the target block.
1589 LabelMapTy::iterator LI = LabelMap.find(*I);
1591 // If there is no target block that contains label, then we are looking
1592 // at an incomplete AST. Handle this by not registering a successor.
1593 if (LI == LabelMap.end()) continue;
1595 addSuccessor(B, LI->second.block);
1598 // Create an empty entry block that has no predecessors.
1599 cfg->setEntry(createBlock());
1601 if (BuildOpts.AddRichCXXConstructors)
1602 assert(ConstructionContextMap.empty() &&
1603 "Not all construction contexts were cleaned up!");
1605 return std::move(cfg);
1608 /// createBlock - Used to lazily create blocks that are connected
1609 /// to the current (global) succcessor.
1610 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1611 CFGBlock *B = cfg->createBlock();
1612 if (add_successor && Succ)
1613 addSuccessor(B, Succ);
1617 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1618 /// CFG. It is *not* connected to the current (global) successor, and instead
1619 /// directly tied to the exit block in order to be reachable.
1620 CFGBlock *CFGBuilder::createNoReturnBlock() {
1621 CFGBlock *B = createBlock(false);
1622 B->setHasNoReturnElement();
1623 addSuccessor(B, &cfg->getExit(), Succ);
1627 /// addInitializer - Add C++ base or member initializer element to CFG.
1628 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1629 if (!BuildOpts.AddInitializers)
1632 bool HasTemporaries = false;
1634 // Destructors of temporaries in initialization expression should be called
1635 // after initialization finishes.
1636 Expr *Init = I->getInit();
1638 HasTemporaries = isa<ExprWithCleanups>(Init);
1640 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1641 // Generate destructors for temporaries in initialization expression.
1642 TempDtorContext Context;
1643 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1644 /*ExternallyDestructed=*/false, Context);
1649 appendInitializer(Block, I);
1652 findConstructionContexts(
1653 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
1656 if (HasTemporaries) {
1657 // For expression with temporaries go directly to subexpression to omit
1658 // generating destructors for the second time.
1659 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1661 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1662 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1663 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1664 // may cause the same Expr to appear more than once in the CFG. Doing it
1665 // here is safe because there's only one initializer per field.
1667 appendStmt(Block, Default);
1668 if (Stmt *Child = Default->getExpr())
1669 if (CFGBlock *R = Visit(Child))
1680 /// Retrieve the type of the temporary object whose lifetime was
1681 /// extended by a local reference with the given initializer.
1682 static QualType getReferenceInitTemporaryType(const Expr *Init,
1683 bool *FoundMTE = nullptr) {
1685 // Skip parentheses.
1686 Init = Init->IgnoreParens();
1688 // Skip through cleanups.
1689 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1690 Init = EWC->getSubExpr();
1694 // Skip through the temporary-materialization expression.
1695 if (const MaterializeTemporaryExpr *MTE
1696 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1697 Init = MTE->GetTemporaryExpr();
1703 // Skip sub-object accesses into rvalues.
1704 SmallVector<const Expr *, 2> CommaLHSs;
1705 SmallVector<SubobjectAdjustment, 2> Adjustments;
1706 const Expr *SkippedInit =
1707 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1708 if (SkippedInit != Init) {
1716 return Init->getType();
1719 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1720 // ended by ReturnStmt, GotoStmt or ThrowExpr.
1721 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1722 if(!BuildOpts.AddLoopExit)
1725 appendLoopExit(Block, LoopStmt);
1728 void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
1729 LocalScope::const_iterator E, Stmt *S) {
1730 if (!BuildOpts.AddScopes)
1736 // To go from B to E, one first goes up the scopes from B to P
1737 // then sideways in one scope from P to P' and then down
1738 // the scopes from P' to E.
1739 // The lifetime of all objects between B and P end.
1740 LocalScope::const_iterator P = B.shared_parent(E);
1741 int Dist = B.distance(P);
1745 for (LocalScope::const_iterator I = B; I != P; ++I)
1746 if (I.pointsToFirstDeclaredVar())
1747 DeclsWithEndedScope.insert(*I);
1750 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1751 LocalScope::const_iterator E,
1753 getDeclsWithEndedScope(B, E, S);
1754 if (BuildOpts.AddScopes)
1755 addScopesEnd(B, E, S);
1756 if (BuildOpts.AddImplicitDtors)
1757 addAutomaticObjDtors(B, E, S);
1758 if (BuildOpts.AddLifetime)
1759 addLifetimeEnds(B, E, S);
1762 /// Add to current block automatic objects that leave the scope.
1763 void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1764 LocalScope::const_iterator E, Stmt *S) {
1765 if (!BuildOpts.AddLifetime)
1771 // To go from B to E, one first goes up the scopes from B to P
1772 // then sideways in one scope from P to P' and then down
1773 // the scopes from P' to E.
1774 // The lifetime of all objects between B and P end.
1775 LocalScope::const_iterator P = B.shared_parent(E);
1776 int dist = B.distance(P);
1780 // We need to perform the scope leaving in reverse order
1781 SmallVector<VarDecl *, 10> DeclsTrivial;
1782 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1783 DeclsTrivial.reserve(dist);
1784 DeclsNonTrivial.reserve(dist);
1786 for (LocalScope::const_iterator I = B; I != P; ++I)
1787 if (hasTrivialDestructor(*I))
1788 DeclsTrivial.push_back(*I);
1790 DeclsNonTrivial.push_back(*I);
1793 // object with trivial destructor end their lifetime last (when storage
1795 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1796 E = DeclsTrivial.rend();
1798 appendLifetimeEnds(Block, *I, S);
1800 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1801 I = DeclsNonTrivial.rbegin(),
1802 E = DeclsNonTrivial.rend();
1804 appendLifetimeEnds(Block, *I, S);
1807 /// Add to current block markers for ending scopes.
1808 void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
1809 LocalScope::const_iterator E, Stmt *S) {
1810 // If implicit destructors are enabled, we'll add scope ends in
1811 // addAutomaticObjDtors.
1812 if (BuildOpts.AddImplicitDtors)
1817 for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
1819 appendScopeEnd(Block, *I, S);
1824 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1825 /// for objects in range of local scope positions. Use S as trigger statement
1826 /// for destructors.
1827 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1828 LocalScope::const_iterator E, Stmt *S) {
1829 if (!BuildOpts.AddImplicitDtors)
1835 // We need to append the destructors in reverse order, but any one of them
1836 // may be a no-return destructor which changes the CFG. As a result, buffer
1837 // this sequence up and replay them in reverse order when appending onto the
1839 SmallVector<VarDecl*, 10> Decls;
1840 Decls.reserve(B.distance(E));
1841 for (LocalScope::const_iterator I = B; I != E; ++I)
1842 Decls.push_back(*I);
1844 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1847 if (hasTrivialDestructor(*I)) {
1848 // If AddScopes is enabled and *I is a first variable in a scope, add a
1849 // ScopeEnd marker in a Block.
1850 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
1852 appendScopeEnd(Block, *I, S);
1856 // If this destructor is marked as a no-return destructor, we need to
1857 // create a new block for the destructor which does not have as a successor
1858 // anything built thus far: control won't flow out of this block.
1859 QualType Ty = (*I)->getType();
1860 if (Ty->isReferenceType()) {
1861 Ty = getReferenceInitTemporaryType((*I)->getInit());
1863 Ty = Context->getBaseElementType(Ty);
1865 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1866 Block = createNoReturnBlock();
1870 // Add ScopeEnd just after automatic obj destructor.
1871 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
1872 appendScopeEnd(Block, *I, S);
1873 appendAutomaticObjDtor(Block, *I, S);
1877 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1878 /// base and member objects in destructor.
1879 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1880 assert(BuildOpts.AddImplicitDtors &&
1881 "Can be called only when dtors should be added");
1882 const CXXRecordDecl *RD = DD->getParent();
1884 // At the end destroy virtual base objects.
1885 for (const auto &VI : RD->vbases()) {
1886 // TODO: Add a VirtualBaseBranch to see if the most derived class
1887 // (which is different from the current class) is responsible for
1889 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1890 if (!CD->hasTrivialDestructor()) {
1892 appendBaseDtor(Block, &VI);
1896 // Before virtual bases destroy direct base objects.
1897 for (const auto &BI : RD->bases()) {
1898 if (!BI.isVirtual()) {
1899 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1900 if (!CD->hasTrivialDestructor()) {
1902 appendBaseDtor(Block, &BI);
1907 // First destroy member objects.
1908 for (auto *FI : RD->fields()) {
1909 // Check for constant size array. Set type to array element type.
1910 QualType QT = FI->getType();
1911 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1912 if (AT->getSize() == 0)
1914 QT = AT->getElementType();
1917 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1918 if (!CD->hasTrivialDestructor()) {
1920 appendMemberDtor(Block, FI);
1925 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1926 /// way return valid LocalScope object.
1927 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1930 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1931 return new (alloc.Allocate<LocalScope>())
1932 LocalScope(BumpVectorContext(alloc), ScopePos);
1935 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1936 /// that should create implicit scope (e.g. if/else substatements).
1937 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1938 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1939 !BuildOpts.AddScopes)
1942 LocalScope *Scope = nullptr;
1944 // For compound statement we will be creating explicit scope.
1945 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1946 for (auto *BI : CS->body()) {
1947 Stmt *SI = BI->stripLabelLikeStatements();
1948 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1949 Scope = addLocalScopeForDeclStmt(DS, Scope);
1954 // For any other statement scope will be implicit and as such will be
1955 // interesting only for DeclStmt.
1956 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1957 addLocalScopeForDeclStmt(DS);
1960 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1961 /// reuse Scope if not NULL.
1962 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1963 LocalScope* Scope) {
1964 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1965 !BuildOpts.AddScopes)
1968 for (auto *DI : DS->decls())
1969 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1970 Scope = addLocalScopeForVarDecl(VD, Scope);
1974 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1975 // Check for const references bound to temporary. Set type to pointee.
1976 QualType QT = VD->getType();
1977 if (QT->isReferenceType()) {
1978 // Attempt to determine whether this declaration lifetime-extends a
1981 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1982 // temporaries, and a single declaration can extend multiple temporaries.
1983 // We should look at the storage duration on each nested
1984 // MaterializeTemporaryExpr instead.
1986 const Expr *Init = VD->getInit();
1988 // Probably an exception catch-by-reference variable.
1989 // FIXME: It doesn't really mean that the object has a trivial destructor.
1990 // Also are there other cases?
1994 // Lifetime-extending a temporary?
1995 bool FoundMTE = false;
1996 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
2001 // Check for constant size array. Set type to array element type.
2002 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2003 if (AT->getSize() == 0)
2005 QT = AT->getElementType();
2008 // Check if type is a C++ class with non-trivial destructor.
2009 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2010 return !CD->hasDefinition() || CD->hasTrivialDestructor();
2014 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2015 /// create add scope for automatic objects and temporary objects bound to
2016 /// const reference. Will reuse Scope if not NULL.
2017 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
2018 LocalScope* Scope) {
2019 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
2020 "AddImplicitDtors and AddLifetime cannot be used at the same time");
2021 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2022 !BuildOpts.AddScopes)
2025 // Check if variable is local.
2026 switch (VD->getStorageClass()) {
2031 default: return Scope;
2034 if (BuildOpts.AddImplicitDtors) {
2035 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
2036 // Add the variable to scope
2037 Scope = createOrReuseLocalScope(Scope);
2039 ScopePos = Scope->begin();
2044 assert(BuildOpts.AddLifetime);
2045 // Add the variable to scope
2046 Scope = createOrReuseLocalScope(Scope);
2048 ScopePos = Scope->begin();
2052 /// addLocalScopeAndDtors - For given statement add local scope for it and
2053 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
2054 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
2055 LocalScope::const_iterator scopeBeginPos = ScopePos;
2056 addLocalScopeForStmt(S);
2057 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
2060 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
2061 /// variables with automatic storage duration to CFGBlock's elements vector.
2062 /// Elements will be prepended to physical beginning of the vector which
2063 /// happens to be logical end. Use blocks terminator as statement that specifies
2064 /// destructors call site.
2065 /// FIXME: This mechanism for adding automatic destructors doesn't handle
2066 /// no-return destructors properly.
2067 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
2068 LocalScope::const_iterator B, LocalScope::const_iterator E) {
2069 if (!BuildOpts.AddImplicitDtors)
2071 BumpVectorContext &C = cfg->getBumpVectorContext();
2072 CFGBlock::iterator InsertPos
2073 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
2074 for (LocalScope::const_iterator I = B; I != E; ++I)
2075 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
2076 Blk->getTerminatorStmt());
2079 /// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
2080 /// variables with automatic storage duration to CFGBlock's elements vector.
2081 /// Elements will be prepended to physical beginning of the vector which
2082 /// happens to be logical end. Use blocks terminator as statement that specifies
2083 /// where lifetime ends.
2084 void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
2085 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2086 if (!BuildOpts.AddLifetime)
2088 BumpVectorContext &C = cfg->getBumpVectorContext();
2089 CFGBlock::iterator InsertPos =
2090 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
2091 for (LocalScope::const_iterator I = B; I != E; ++I) {
2093 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
2097 /// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
2098 /// variables with automatic storage duration to CFGBlock's elements vector.
2099 /// Elements will be prepended to physical beginning of the vector which
2100 /// happens to be logical end. Use blocks terminator as statement that specifies
2101 /// where scope ends.
2103 CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
2104 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2105 if (!BuildOpts.AddScopes)
2107 BumpVectorContext &C = cfg->getBumpVectorContext();
2108 CFGBlock::iterator InsertPos =
2109 Blk->beginScopeEndInsert(Blk->end(), 1, C);
2110 LocalScope::const_iterator PlaceToInsert = B;
2111 for (LocalScope::const_iterator I = B; I != E; ++I)
2113 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
2114 return *PlaceToInsert;
2117 /// Visit - Walk the subtree of a statement and add extra
2118 /// blocks for ternary operators, &&, and ||. We also process "," and
2119 /// DeclStmts (which may contain nested control-flow).
2120 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
2121 bool ExternallyDestructed) {
2127 if (Expr *E = dyn_cast<Expr>(S))
2128 S = E->IgnoreParens();
2130 if (Context->getLangOpts().OpenMP)
2131 if (auto *D = dyn_cast<OMPExecutableDirective>(S))
2132 return VisitOMPExecutableDirective(D, asc);
2134 switch (S->getStmtClass()) {
2136 return VisitStmt(S, asc);
2138 case Stmt::AddrLabelExprClass:
2139 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
2141 case Stmt::BinaryConditionalOperatorClass:
2142 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2144 case Stmt::BinaryOperatorClass:
2145 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
2147 case Stmt::BlockExprClass:
2148 return VisitBlockExpr(cast<BlockExpr>(S), asc);
2150 case Stmt::BreakStmtClass:
2151 return VisitBreakStmt(cast<BreakStmt>(S));
2153 case Stmt::CallExprClass:
2154 case Stmt::CXXOperatorCallExprClass:
2155 case Stmt::CXXMemberCallExprClass:
2156 case Stmt::UserDefinedLiteralClass:
2157 return VisitCallExpr(cast<CallExpr>(S), asc);
2159 case Stmt::CaseStmtClass:
2160 return VisitCaseStmt(cast<CaseStmt>(S));
2162 case Stmt::ChooseExprClass:
2163 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
2165 case Stmt::CompoundStmtClass:
2166 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
2168 case Stmt::ConditionalOperatorClass:
2169 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
2171 case Stmt::ContinueStmtClass:
2172 return VisitContinueStmt(cast<ContinueStmt>(S));
2174 case Stmt::CXXCatchStmtClass:
2175 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2177 case Stmt::ExprWithCleanupsClass:
2178 return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
2179 asc, ExternallyDestructed);
2181 case Stmt::CXXDefaultArgExprClass:
2182 case Stmt::CXXDefaultInitExprClass:
2183 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2184 // called function's declaration, not by the caller. If we simply add
2185 // this expression to the CFG, we could end up with the same Expr
2186 // appearing multiple times.
2187 // PR13385 / <rdar://problem/12156507>
2189 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2190 // expression to be used in the same function (through aggregate
2192 return VisitStmt(S, asc);
2194 case Stmt::CXXBindTemporaryExprClass:
2195 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2197 case Stmt::CXXConstructExprClass:
2198 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2200 case Stmt::CXXNewExprClass:
2201 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2203 case Stmt::CXXDeleteExprClass:
2204 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2206 case Stmt::CXXFunctionalCastExprClass:
2207 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2209 case Stmt::CXXTemporaryObjectExprClass:
2210 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2212 case Stmt::CXXThrowExprClass:
2213 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
2215 case Stmt::CXXTryStmtClass:
2216 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
2218 case Stmt::CXXForRangeStmtClass:
2219 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2221 case Stmt::DeclStmtClass:
2222 return VisitDeclStmt(cast<DeclStmt>(S));
2224 case Stmt::DefaultStmtClass:
2225 return VisitDefaultStmt(cast<DefaultStmt>(S));
2227 case Stmt::DoStmtClass:
2228 return VisitDoStmt(cast<DoStmt>(S));
2230 case Stmt::ForStmtClass:
2231 return VisitForStmt(cast<ForStmt>(S));
2233 case Stmt::GotoStmtClass:
2234 return VisitGotoStmt(cast<GotoStmt>(S));
2236 case Stmt::GCCAsmStmtClass:
2237 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2239 case Stmt::IfStmtClass:
2240 return VisitIfStmt(cast<IfStmt>(S));
2242 case Stmt::ImplicitCastExprClass:
2243 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
2245 case Stmt::ConstantExprClass:
2246 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2248 case Stmt::IndirectGotoStmtClass:
2249 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
2251 case Stmt::LabelStmtClass:
2252 return VisitLabelStmt(cast<LabelStmt>(S));
2254 case Stmt::LambdaExprClass:
2255 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2257 case Stmt::MaterializeTemporaryExprClass:
2258 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2261 case Stmt::MemberExprClass:
2262 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2264 case Stmt::NullStmtClass:
2267 case Stmt::ObjCAtCatchStmtClass:
2268 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2270 case Stmt::ObjCAutoreleasePoolStmtClass:
2271 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2273 case Stmt::ObjCAtSynchronizedStmtClass:
2274 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
2276 case Stmt::ObjCAtThrowStmtClass:
2277 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
2279 case Stmt::ObjCAtTryStmtClass:
2280 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
2282 case Stmt::ObjCForCollectionStmtClass:
2283 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
2285 case Stmt::ObjCMessageExprClass:
2286 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2288 case Stmt::OpaqueValueExprClass:
2291 case Stmt::PseudoObjectExprClass:
2292 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2294 case Stmt::ReturnStmtClass:
2295 case Stmt::CoreturnStmtClass:
2296 return VisitReturnStmt(S);
2298 case Stmt::SEHExceptStmtClass:
2299 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2301 case Stmt::SEHFinallyStmtClass:
2302 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2304 case Stmt::SEHLeaveStmtClass:
2305 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2307 case Stmt::SEHTryStmtClass:
2308 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2310 case Stmt::UnaryExprOrTypeTraitExprClass:
2311 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2314 case Stmt::StmtExprClass:
2315 return VisitStmtExpr(cast<StmtExpr>(S), asc);
2317 case Stmt::SwitchStmtClass:
2318 return VisitSwitchStmt(cast<SwitchStmt>(S));
2320 case Stmt::UnaryOperatorClass:
2321 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2323 case Stmt::WhileStmtClass:
2324 return VisitWhileStmt(cast<WhileStmt>(S));
2328 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
2329 if (asc.alwaysAdd(*this, S)) {
2331 appendStmt(Block, S);
2334 return VisitChildren(S);
2337 /// VisitChildren - Visit the children of a Stmt.
2338 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2339 CFGBlock *B = Block;
2341 // Visit the children in their reverse order so that they appear in
2342 // left-to-right (natural) order in the CFG.
2343 reverse_children RChildren(S);
2344 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
2346 if (Stmt *Child = *I)
2347 if (CFGBlock *R = Visit(Child))
2353 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2354 AddStmtChoice asc) {
2355 AddressTakenLabels.insert(A->getLabel());
2357 if (asc.alwaysAdd(*this, A)) {
2359 appendStmt(Block, A);
2365 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
2366 AddStmtChoice asc) {
2367 if (asc.alwaysAdd(*this, U)) {
2369 appendStmt(Block, U);
2372 if (U->getOpcode() == UO_LNot)
2373 tryEvaluateBool(U->getSubExpr()->IgnoreParens());
2375 return Visit(U->getSubExpr(), AddStmtChoice());
2378 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2379 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2380 appendStmt(ConfluenceBlock, B);
2385 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2386 ConfluenceBlock).first;
2389 std::pair<CFGBlock*, CFGBlock*>
2390 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2392 CFGBlock *TrueBlock,
2393 CFGBlock *FalseBlock) {
2394 // Introspect the RHS. If it is a nested logical operation, we recursively
2395 // build the CFG using this function. Otherwise, resort to default
2396 // CFG construction behavior.
2397 Expr *RHS = B->getRHS()->IgnoreParens();
2398 CFGBlock *RHSBlock, *ExitBlock;
2401 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2402 if (B_RHS->isLogicalOp()) {
2403 std::tie(RHSBlock, ExitBlock) =
2404 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2408 // The RHS is not a nested logical operation. Don't push the terminator
2409 // down further, but instead visit RHS and construct the respective
2410 // pieces of the CFG, and link up the RHSBlock with the terminator
2411 // we have been provided.
2412 ExitBlock = RHSBlock = createBlock(false);
2414 // Even though KnownVal is only used in the else branch of the next
2415 // conditional, tryEvaluateBool performs additional checking on the
2416 // Expr, so it should be called unconditionally.
2417 TryResult KnownVal = tryEvaluateBool(RHS);
2418 if (!KnownVal.isKnown())
2419 KnownVal = tryEvaluateBool(B);
2422 assert(TrueBlock == FalseBlock);
2423 addSuccessor(RHSBlock, TrueBlock);
2426 RHSBlock->setTerminator(Term);
2427 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2428 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
2432 RHSBlock = addStmt(RHS);
2437 return std::make_pair(nullptr, nullptr);
2439 // Generate the blocks for evaluating the LHS.
2440 Expr *LHS = B->getLHS()->IgnoreParens();
2442 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2443 if (B_LHS->isLogicalOp()) {
2444 if (B->getOpcode() == BO_LOr)
2445 FalseBlock = RHSBlock;
2447 TrueBlock = RHSBlock;
2449 // For the LHS, treat 'B' as the terminator that we want to sink
2450 // into the nested branch. The RHS always gets the top-most
2452 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2455 // Create the block evaluating the LHS.
2456 // This contains the '&&' or '||' as the terminator.
2457 CFGBlock *LHSBlock = createBlock(false);
2458 LHSBlock->setTerminator(B);
2461 CFGBlock *EntryLHSBlock = addStmt(LHS);
2464 return std::make_pair(nullptr, nullptr);
2466 // See if this is a known constant.
2467 TryResult KnownVal = tryEvaluateBool(LHS);
2469 // Now link the LHSBlock with RHSBlock.
2470 if (B->getOpcode() == BO_LOr) {
2471 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2472 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
2474 assert(B->getOpcode() == BO_LAnd);
2475 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2476 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
2479 return std::make_pair(EntryLHSBlock, ExitBlock);
2482 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2483 AddStmtChoice asc) {
2485 if (B->isLogicalOp())
2486 return VisitLogicalOperator(B);
2488 if (B->getOpcode() == BO_Comma) { // ,
2490 appendStmt(Block, B);
2491 addStmt(B->getRHS());
2492 return addStmt(B->getLHS());
2495 if (B->isAssignmentOp()) {
2496 if (asc.alwaysAdd(*this, B)) {
2498 appendStmt(Block, B);
2501 return Visit(B->getRHS());
2504 if (asc.alwaysAdd(*this, B)) {
2506 appendStmt(Block, B);
2509 if (B->isEqualityOp() || B->isRelationalOp())
2512 CFGBlock *RBlock = Visit(B->getRHS());
2513 CFGBlock *LBlock = Visit(B->getLHS());
2514 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2515 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2516 // return RBlock. Otherwise we'll incorrectly return NULL.
2517 return (LBlock ? LBlock : RBlock);
2520 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2521 if (asc.alwaysAdd(*this, E)) {
2523 appendStmt(Block, E);
2528 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2529 // "break" is a control-flow statement. Thus we stop processing the current
2534 // Now create a new block that ends with the break statement.
2535 Block = createBlock(false);
2536 Block->setTerminator(B);
2538 // If there is no target for the break, then we are looking at an incomplete
2539 // AST. This means that the CFG cannot be constructed.
2540 if (BreakJumpTarget.block) {
2541 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
2542 addSuccessor(Block, BreakJumpTarget.block);
2549 static bool CanThrow(Expr *E, ASTContext &Ctx) {
2550 QualType Ty = E->getType();
2551 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
2552 Ty = Ty->getPointeeType();
2554 const FunctionType *FT = Ty->getAs<FunctionType>();
2556 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
2557 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
2564 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2565 // Compute the callee type.
2566 QualType calleeType = C->getCallee()->getType();
2567 if (calleeType == Context->BoundMemberTy) {
2568 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2570 // We should only get a null bound type if processing a dependent
2571 // CFG. Recover by assuming nothing.
2572 if (!boundType.isNull()) calleeType = boundType;
2575 // If this is a call to a no-return function, this stops the block here.
2576 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2578 bool AddEHEdge = false;
2580 // Languages without exceptions are assumed to not throw.
2581 if (Context->getLangOpts().Exceptions) {
2582 if (BuildOpts.AddEHEdges)
2586 // If this is a call to a builtin function, it might not actually evaluate
2587 // its arguments. Don't add them to the CFG if this is the case.
2588 bool OmitArguments = false;
2590 if (FunctionDecl *FD = C->getDirectCallee()) {
2591 // TODO: Support construction contexts for variadic function arguments.
2592 // These are a bit problematic and not very useful because passing
2593 // C++ objects as C-style variadic arguments doesn't work in general
2594 // (see [expr.call]).
2595 if (!FD->isVariadic())
2596 findConstructionContextsForArguments(C);
2598 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
2600 if (FD->hasAttr<NoThrowAttr>())
2602 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2603 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
2604 OmitArguments = true;
2607 if (!CanThrow(C->getCallee(), *Context))
2610 if (OmitArguments) {
2611 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2612 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2614 appendStmt(Block, C);
2615 return Visit(C->getCallee());
2618 if (!NoReturn && !AddEHEdge) {
2620 appendCall(Block, C);
2622 return VisitChildren(C);
2632 Block = createNoReturnBlock();
2634 Block = createBlock();
2636 appendCall(Block, C);
2639 // Add exceptional edges.
2640 if (TryTerminatedBlock)
2641 addSuccessor(Block, TryTerminatedBlock);
2643 addSuccessor(Block, &cfg->getExit());
2646 return VisitChildren(C);
2649 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2650 AddStmtChoice asc) {
2651 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2652 appendStmt(ConfluenceBlock, C);
2656 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2657 Succ = ConfluenceBlock;
2659 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2663 Succ = ConfluenceBlock;
2665 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2669 Block = createBlock(false);
2670 // See if this is a known constant.
2671 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2672 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2673 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2674 Block->setTerminator(C);
2675 return addStmt(C->getCond());
2678 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed) {
2679 LocalScope::const_iterator scopeBeginPos = ScopePos;
2680 addLocalScopeForStmt(C);
2682 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2683 // If the body ends with a ReturnStmt, the dtors will be added in
2685 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2688 CFGBlock *LastBlock = Block;
2690 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2692 // If we hit a segment of code just containing ';' (NullStmts), we can
2693 // get a null block back. In such cases, just use the LastBlock
2694 CFGBlock *newBlock = Visit(*I, AddStmtChoice::AlwaysAdd,
2695 ExternallyDestructed);
2698 LastBlock = newBlock;
2703 ExternallyDestructed = false;
2709 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2710 AddStmtChoice asc) {
2711 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2712 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2714 // Create the confluence block that will "merge" the results of the ternary
2716 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2717 appendStmt(ConfluenceBlock, C);
2721 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2723 // Create a block for the LHS expression if there is an LHS expression. A
2724 // GCC extension allows LHS to be NULL, causing the condition to be the
2725 // value that is returned instead.
2726 // e.g: x ?: y is shorthand for: x ? x : y;
2727 Succ = ConfluenceBlock;
2729 CFGBlock *LHSBlock = nullptr;
2730 const Expr *trueExpr = C->getTrueExpr();
2731 if (trueExpr != opaqueValue) {
2732 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2738 LHSBlock = ConfluenceBlock;
2740 // Create the block for the RHS expression.
2741 Succ = ConfluenceBlock;
2742 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2746 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2747 if (BinaryOperator *Cond =
2748 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2749 if (Cond->isLogicalOp())
2750 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2752 // Create the block that will contain the condition.
2753 Block = createBlock(false);
2755 // See if this is a known constant.
2756 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2757 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2758 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2759 Block->setTerminator(C);
2760 Expr *condExpr = C->getCond();
2763 // Run the condition expression if it's not trivially expressed in
2764 // terms of the opaque value (or if there is no opaque value).
2765 if (condExpr != opaqueValue)
2768 // Before that, run the common subexpression if there was one.
2769 // At least one of this or the above will be run.
2770 return addStmt(BCO->getCommon());
2773 return addStmt(condExpr);
2776 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2777 // Check if the Decl is for an __label__. If so, elide it from the
2779 if (isa<LabelDecl>(*DS->decl_begin()))
2782 // This case also handles static_asserts.
2783 if (DS->isSingleDecl())
2784 return VisitDeclSubExpr(DS);
2786 CFGBlock *B = nullptr;
2788 // Build an individual DeclStmt for each decl.
2789 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2790 E = DS->decl_rend();
2793 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2794 // automatically freed with the CFG.
2795 DeclGroupRef DG(*I);
2797 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2798 cfg->addSyntheticDeclStmt(DSNew, DS);
2800 // Append the fake DeclStmt to block.
2801 B = VisitDeclSubExpr(DSNew);
2807 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2808 /// DeclStmts and initializers in them.
2809 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2810 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2811 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2814 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2815 // runtime semantics.
2819 bool HasTemporaries = false;
2821 // Guard static initializers under a branch.
2822 CFGBlock *blockAfterStaticInit = nullptr;
2824 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2825 // For static variables, we need to create a branch to track
2826 // whether or not they are initialized.
2833 blockAfterStaticInit = Succ;
2836 // Destructors of temporaries in initialization expression should be called
2837 // after initialization finishes.
2838 Expr *Init = VD->getInit();
2840 HasTemporaries = isa<ExprWithCleanups>(Init);
2842 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2843 // Generate destructors for temporaries in initialization expression.
2844 TempDtorContext Context;
2845 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2846 /*ExternallyDestructed=*/true, Context);
2851 appendStmt(Block, DS);
2853 findConstructionContexts(
2854 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
2857 // Keep track of the last non-null block, as 'Block' can be nulled out
2858 // if the initializer expression is something like a 'while' in a
2859 // statement-expression.
2860 CFGBlock *LastBlock = Block;
2863 if (HasTemporaries) {
2864 // For expression with temporaries go directly to subexpression to omit
2865 // generating destructors for the second time.
2866 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2867 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2868 LastBlock = newBlock;
2871 if (CFGBlock *newBlock = Visit(Init))
2872 LastBlock = newBlock;
2876 // If the type of VD is a VLA, then we must process its size expressions.
2877 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2878 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2879 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2880 LastBlock = newBlock;
2883 maybeAddScopeBeginForVarDecl(Block, VD, DS);
2885 // Remove variable from local scope.
2886 if (ScopePos && VD == *ScopePos)
2889 CFGBlock *B = LastBlock;
2890 if (blockAfterStaticInit) {
2892 Block = createBlock(false);
2893 Block->setTerminator(DS);
2894 addSuccessor(Block, blockAfterStaticInit);
2895 addSuccessor(Block, B);
2902 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2903 // We may see an if statement in the middle of a basic block, or it may be the
2904 // first statement we are processing. In either case, we create a new basic
2905 // block. First, we create the blocks for the then...else statements, and
2906 // then we create the block containing the if statement. If we were in the
2907 // middle of a block, we stop processing that block. That block is then the
2908 // implicit successor for the "then" and "else" clauses.
2910 // Save local scope position because in case of condition variable ScopePos
2911 // won't be restored when traversing AST.
2912 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2914 // Create local scope for C++17 if init-stmt if one exists.
2915 if (Stmt *Init = I->getInit())
2916 addLocalScopeForStmt(Init);
2918 // Create local scope for possible condition variable.
2919 // Store scope position. Add implicit destructor.
2920 if (VarDecl *VD = I->getConditionVariable())
2921 addLocalScopeForVarDecl(VD);
2923 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
2925 // The block we were processing is now finished. Make it the successor
2933 // Process the false branch.
2934 CFGBlock *ElseBlock = Succ;
2936 if (Stmt *Else = I->getElse()) {
2937 SaveAndRestore<CFGBlock*> sv(Succ);
2939 // NULL out Block so that the recursive call to Visit will
2940 // create a new basic block.
2943 // If branch is not a compound statement create implicit scope
2944 // and add destructors.
2945 if (!isa<CompoundStmt>(Else))
2946 addLocalScopeAndDtors(Else);
2948 ElseBlock = addStmt(Else);
2950 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2951 ElseBlock = sv.get();
2958 // Process the true branch.
2959 CFGBlock *ThenBlock;
2961 Stmt *Then = I->getThen();
2963 SaveAndRestore<CFGBlock*> sv(Succ);
2966 // If branch is not a compound statement create implicit scope
2967 // and add destructors.
2968 if (!isa<CompoundStmt>(Then))
2969 addLocalScopeAndDtors(Then);
2971 ThenBlock = addStmt(Then);
2974 // We can reach here if the "then" body has all NullStmts.
2975 // Create an empty block so we can distinguish between true and false
2976 // branches in path-sensitive analyses.
2977 ThenBlock = createBlock(false);
2978 addSuccessor(ThenBlock, sv.get());
2985 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2986 // having these handle the actual control-flow jump. Note that
2987 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2988 // we resort to the old control-flow behavior. This special handling
2989 // removes infeasible paths from the control-flow graph by having the
2990 // control-flow transfer of '&&' or '||' go directly into the then/else
2992 BinaryOperator *Cond =
2993 I->getConditionVariable()
2995 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2996 CFGBlock *LastBlock;
2997 if (Cond && Cond->isLogicalOp())
2998 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
3000 // Now create a new block containing the if statement.
3001 Block = createBlock(false);
3003 // Set the terminator of the new block to the If statement.
3004 Block->setTerminator(I);
3006 // See if this is a known constant.
3007 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
3009 // Add the successors. If we know that specific branches are
3010 // unreachable, inform addSuccessor() of that knowledge.
3011 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
3012 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
3014 // Add the condition as the last statement in the new block. This may
3015 // create new blocks as the condition may contain control-flow. Any newly
3016 // created blocks will be pointed to be "Block".
3017 LastBlock = addStmt(I->getCond());
3019 // If the IfStmt contains a condition variable, add it and its
3020 // initializer to the CFG.
3021 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
3023 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
3027 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3028 if (Stmt *Init = I->getInit()) {
3030 LastBlock = addStmt(Init);
3036 CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
3037 // If we were in the middle of a block we stop processing that block.
3039 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3040 // means that the code afterwards is DEAD (unreachable). We still keep
3041 // a basic block for that code; a simple "mark-and-sweep" from the entry
3042 // block will be able to report such dead blocks.
3043 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
3045 // Create the new block.
3046 Block = createBlock(false);
3048 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
3050 if (auto *R = dyn_cast<ReturnStmt>(S))
3051 findConstructionContexts(
3052 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
3055 // If the one of the destructors does not return, we already have the Exit
3056 // block as a successor.
3057 if (!Block->hasNoReturnElement())
3058 addSuccessor(Block, &cfg->getExit());
3060 // Add the return statement to the block.
3061 appendStmt(Block, S);
3064 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
3065 if (Expr *O = RS->getRetValue())
3066 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
3068 } else { // co_return
3069 return VisitChildren(S);
3073 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3074 // SEHExceptStmt are treated like labels, so they are the first statement in a
3077 // Save local scope position because in case of exception variable ScopePos
3078 // won't be restored when traversing AST.
3079 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3081 addStmt(ES->getBlock());
3082 CFGBlock *SEHExceptBlock = Block;
3083 if (!SEHExceptBlock)
3084 SEHExceptBlock = createBlock();
3086 appendStmt(SEHExceptBlock, ES);
3088 // Also add the SEHExceptBlock as a label, like with regular labels.
3089 SEHExceptBlock->setLabel(ES);
3091 // Bail out if the CFG is bad.
3095 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3098 return SEHExceptBlock;
3101 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3102 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
3105 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3106 // "__leave" is a control-flow statement. Thus we stop processing the current
3111 // Now create a new block that ends with the __leave statement.
3112 Block = createBlock(false);
3113 Block->setTerminator(LS);
3115 // If there is no target for the __leave, then we are looking at an incomplete
3116 // AST. This means that the CFG cannot be constructed.
3117 if (SEHLeaveJumpTarget.block) {
3118 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3119 addSuccessor(Block, SEHLeaveJumpTarget.block);
3126 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3127 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3128 // processing the current block.
3129 CFGBlock *SEHTrySuccessor = nullptr;
3134 SEHTrySuccessor = Block;
3135 } else SEHTrySuccessor = Succ;
3137 // FIXME: Implement __finally support.
3138 if (Terminator->getFinallyHandler())
3141 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3143 // Create a new block that will contain the __try statement.
3144 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3146 // Add the terminator in the __try block.
3147 NewTryTerminatedBlock->setTerminator(Terminator);
3149 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3150 // The code after the try is the implicit successor if there's an __except.
3151 Succ = SEHTrySuccessor;
3153 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3156 // Add this block to the list of successors for the block with the try
3158 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3160 if (PrevSEHTryTerminatedBlock)
3161 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3163 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3165 // The code after the try is the implicit successor.
3166 Succ = SEHTrySuccessor;
3168 // Save the current "__try" context.
3169 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
3170 NewTryTerminatedBlock);
3171 cfg->addTryDispatchBlock(TryTerminatedBlock);
3173 // Save the current value for the __leave target.
3174 // All __leaves should go to the code following the __try
3175 // (FIXME: or if the __try has a __finally, to the __finally.)
3176 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
3177 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3179 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3181 return addStmt(Terminator->getTryBlock());
3184 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3185 // Get the block of the labeled statement. Add it to our map.
3186 addStmt(L->getSubStmt());
3187 CFGBlock *LabelBlock = Block;
3189 if (!LabelBlock) // This can happen when the body is empty, i.e.
3190 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3192 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
3193 "label already in map");
3194 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3196 // Labels partition blocks, so this is the end of the basic block we were
3197 // processing (L is the block's label). Because this is label (and we have
3198 // already processed the substatement) there is no extra control-flow to worry
3200 LabelBlock->setLabel(L);
3204 // We set Block to NULL to allow lazy creation of a new block (if necessary);
3207 // This block is now the implicit successor of other blocks.
3213 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3214 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3215 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3216 if (Expr *CopyExpr = CI.getCopyExpr()) {
3217 CFGBlock *Tmp = Visit(CopyExpr);
3225 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3226 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3227 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3228 et = E->capture_init_end(); it != et; ++it) {
3229 if (Expr *Init = *it) {
3230 CFGBlock *Tmp = Visit(Init);
3238 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3239 // Goto is a control-flow statement. Thus we stop processing the current
3240 // block and create a new one.
3242 Block = createBlock(false);
3243 Block->setTerminator(G);
3245 // If we already know the mapping to the label block add the successor now.
3246 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
3248 if (I == LabelMap.end())
3249 // We will need to backpatch this block later.
3250 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3252 JumpTarget JT = I->second;
3253 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
3254 addSuccessor(Block, JT.block);
3260 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3261 // Goto is a control-flow statement. Thus we stop processing the current
3262 // block and create a new one.
3264 if (!G->isAsmGoto())
3265 return VisitStmt(G, asc);
3272 Block = createBlock();
3273 Block->setTerminator(G);
3274 // We will backpatch this block later for all the labels.
3275 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3276 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3277 // used to avoid adding "Succ" again.
3278 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3282 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3283 CFGBlock *LoopSuccessor = nullptr;
3285 // Save local scope position because in case of condition variable ScopePos
3286 // won't be restored when traversing AST.
3287 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3289 // Create local scope for init statement and possible condition variable.
3290 // Add destructor for init statement and condition variable.
3291 // Store scope position for continue statement.
3292 if (Stmt *Init = F->getInit())
3293 addLocalScopeForStmt(Init);
3294 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3296 if (VarDecl *VD = F->getConditionVariable())
3297 addLocalScopeForVarDecl(VD);
3298 LocalScope::const_iterator ContinueScopePos = ScopePos;
3300 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
3304 // "for" is a control-flow statement. Thus we stop processing the current
3309 LoopSuccessor = Block;
3311 LoopSuccessor = Succ;
3313 // Save the current value for the break targets.
3314 // All breaks should go to the code following the loop.
3315 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3316 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3318 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3320 // Now create the loop body.
3322 assert(F->getBody());
3324 // Save the current values for Block, Succ, continue and break targets.
3325 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3326 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3328 // Create an empty block to represent the transition block for looping back
3329 // to the head of the loop. If we have increment code, it will
3330 // go in this block as well.
3331 Block = Succ = TransitionBlock = createBlock(false);
3332 TransitionBlock->setLoopTarget(F);
3334 if (Stmt *I = F->getInc()) {
3335 // Generate increment code in its own basic block. This is the target of
3336 // continue statements.
3340 // Finish up the increment (or empty) block if it hasn't been already.
3342 assert(Block == Succ);
3348 // The starting block for the loop increment is the block that should
3349 // represent the 'loop target' for looping back to the start of the loop.
3350 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3351 ContinueJumpTarget.block->setLoopTarget(F);
3353 // Loop body should end with destructor of Condition variable (if any).
3354 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
3356 // If body is not a compound statement create implicit scope
3357 // and add destructors.
3358 if (!isa<CompoundStmt>(F->getBody()))
3359 addLocalScopeAndDtors(F->getBody());
3361 // Now populate the body block, and in the process create new blocks as we
3362 // walk the body of the loop.
3363 BodyBlock = addStmt(F->getBody());
3366 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3367 // Use the continue jump target as the proxy for the body.
3368 BodyBlock = ContinueJumpTarget.block;
3374 // Because of short-circuit evaluation, the condition of the loop can span
3375 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3376 // evaluate the condition.
3377 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3380 Expr *C = F->getCond();
3381 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3383 // Specially handle logical operators, which have a slightly
3384 // more optimal CFG representation.
3385 if (BinaryOperator *Cond =
3386 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
3387 if (Cond->isLogicalOp()) {
3388 std::tie(EntryConditionBlock, ExitConditionBlock) =
3389 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3393 // The default case when not handling logical operators.
3394 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3395 ExitConditionBlock->setTerminator(F);
3397 // See if this is a known constant.
3398 TryResult KnownVal(true);
3401 // Now add the actual condition to the condition block.
3402 // Because the condition itself may contain control-flow, new blocks may
3403 // be created. Thus we update "Succ" after adding the condition.
3404 Block = ExitConditionBlock;
3405 EntryConditionBlock = addStmt(C);
3407 // If this block contains a condition variable, add both the condition
3408 // variable and initializer to the CFG.
3409 if (VarDecl *VD = F->getConditionVariable()) {
3410 if (Expr *Init = VD->getInit()) {
3412 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3413 assert(DS->isSingleDecl());
3414 findConstructionContexts(
3415 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3417 appendStmt(Block, DS);
3418 EntryConditionBlock = addStmt(Init);
3419 assert(Block == EntryConditionBlock);
3420 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3424 if (Block && badCFG)
3427 KnownVal = tryEvaluateBool(C);
3430 // Add the loop body entry as a successor to the condition.
3431 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3432 // Link up the condition block with the code that follows the loop. (the
3434 addSuccessor(ExitConditionBlock,
3435 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3438 // Link up the loop-back block to the entry condition block.
3439 addSuccessor(TransitionBlock, EntryConditionBlock);
3441 // The condition block is the implicit successor for any code above the loop.
3442 Succ = EntryConditionBlock;
3444 // If the loop contains initialization, create a new block for those
3445 // statements. This block can also contain statements that precede the loop.
3446 if (Stmt *I = F->getInit()) {
3447 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3448 ScopePos = LoopBeginScopePos;
3449 Block = createBlock();
3453 // There is no loop initialization. We are thus basically a while loop.
3454 // NULL out Block to force lazy block construction.
3456 Succ = EntryConditionBlock;
3457 return EntryConditionBlock;
3461 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3462 AddStmtChoice asc) {
3463 findConstructionContexts(
3464 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
3465 MTE->getTemporary());
3467 return VisitStmt(MTE, asc);
3470 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3471 if (asc.alwaysAdd(*this, M)) {
3473 appendStmt(Block, M);
3475 return Visit(M->getBase());
3478 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3479 // Objective-C fast enumeration 'for' statements:
3480 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3482 // for ( Type newVariable in collection_expression ) { statements }
3487 // 1. collection_expression
3488 // T. jump to loop_entry
3490 // 1. side-effects of element expression
3491 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3492 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3495 // T. jump to loop_entry
3501 // Type existingItem;
3502 // for ( existingItem in expression ) { statements }
3506 // the same with newVariable replaced with existingItem; the binding works
3507 // the same except that for one ObjCForCollectionStmt::getElement() returns
3508 // a DeclStmt and the other returns a DeclRefExpr.
3510 CFGBlock *LoopSuccessor = nullptr;
3515 LoopSuccessor = Block;
3518 LoopSuccessor = Succ;
3520 // Build the condition blocks.
3521 CFGBlock *ExitConditionBlock = createBlock(false);
3523 // Set the terminator for the "exit" condition block.
3524 ExitConditionBlock->setTerminator(S);
3526 // The last statement in the block should be the ObjCForCollectionStmt, which
3527 // performs the actual binding to 'element' and determines if there are any
3528 // more items in the collection.
3529 appendStmt(ExitConditionBlock, S);
3530 Block = ExitConditionBlock;
3532 // Walk the 'element' expression to see if there are any side-effects. We
3533 // generate new blocks as necessary. We DON'T add the statement by default to
3534 // the CFG unless it contains control-flow.
3535 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3536 AddStmtChoice::NotAlwaysAdd);
3543 // The condition block is the implicit successor for the loop body as well as
3544 // any code above the loop.
3545 Succ = EntryConditionBlock;
3547 // Now create the true branch.
3549 // Save the current values for Succ, continue and break targets.
3550 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3551 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3552 save_break(BreakJumpTarget);
3554 // Add an intermediate block between the BodyBlock and the
3555 // EntryConditionBlock to represent the "loop back" transition, for looping
3556 // back to the head of the loop.
3557 CFGBlock *LoopBackBlock = nullptr;
3558 Succ = LoopBackBlock = createBlock();
3559 LoopBackBlock->setLoopTarget(S);
3561 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3562 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3564 CFGBlock *BodyBlock = addStmt(S->getBody());
3567 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3573 // This new body block is a successor to our "exit" condition block.
3574 addSuccessor(ExitConditionBlock, BodyBlock);
3577 // Link up the condition block with the code that follows the loop.
3578 // (the false branch).
3579 addSuccessor(ExitConditionBlock, LoopSuccessor);
3581 // Now create a prologue block to contain the collection expression.
3582 Block = createBlock();
3583 return addStmt(S->getCollection());
3586 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3588 return addStmt(S->getSubStmt());
3589 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3592 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3593 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3596 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3598 // The sync body starts its own basic block. This makes it a little easier
3599 // for diagnostic clients.
3608 // Add the @synchronized to the CFG.
3610 appendStmt(Block, S);
3612 // Inline the sync expression.
3613 return addStmt(S->getSynchExpr());
3616 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
3621 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3624 // Add the PseudoObject as the last thing.
3625 appendStmt(Block, E);
3627 CFGBlock *lastBlock = Block;
3629 // Before that, evaluate all of the semantics in order. In
3630 // CFG-land, that means appending them in reverse order.
3631 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3632 Expr *Semantic = E->getSemanticExpr(--i);
3634 // If the semantic is an opaque value, we're being asked to bind
3635 // it to its source expression.
3636 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3637 Semantic = OVE->getSourceExpr();
3639 if (CFGBlock *B = Visit(Semantic))
3646 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3647 CFGBlock *LoopSuccessor = nullptr;
3649 // Save local scope position because in case of condition variable ScopePos
3650 // won't be restored when traversing AST.
3651 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3653 // Create local scope for possible condition variable.
3654 // Store scope position for continue statement.
3655 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3656 if (VarDecl *VD = W->getConditionVariable()) {
3657 addLocalScopeForVarDecl(VD);
3658 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3662 // "while" is a control-flow statement. Thus we stop processing the current
3667 LoopSuccessor = Block;
3670 LoopSuccessor = Succ;
3673 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3675 // Process the loop body.
3677 assert(W->getBody());
3679 // Save the current values for Block, Succ, continue and break targets.
3680 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3681 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3682 save_break(BreakJumpTarget);
3684 // Create an empty block to represent the transition block for looping back
3685 // to the head of the loop.
3686 Succ = TransitionBlock = createBlock(false);
3687 TransitionBlock->setLoopTarget(W);
3688 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
3690 // All breaks should go to the code following the loop.
3691 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3693 // Loop body should end with destructor of Condition variable (if any).
3694 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3696 // If body is not a compound statement create implicit scope
3697 // and add destructors.
3698 if (!isa<CompoundStmt>(W->getBody()))
3699 addLocalScopeAndDtors(W->getBody());
3701 // Create the body. The returned block is the entry to the loop body.
3702 BodyBlock = addStmt(W->getBody());
3705 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
3706 else if (Block && badCFG)
3710 // Because of short-circuit evaluation, the condition of the loop can span
3711 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3712 // evaluate the condition.
3713 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3716 Expr *C = W->getCond();
3718 // Specially handle logical operators, which have a slightly
3719 // more optimal CFG representation.
3720 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
3721 if (Cond->isLogicalOp()) {
3722 std::tie(EntryConditionBlock, ExitConditionBlock) =
3723 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
3727 // The default case when not handling logical operators.
3728 ExitConditionBlock = createBlock(false);
3729 ExitConditionBlock->setTerminator(W);
3731 // Now add the actual condition to the condition block.
3732 // Because the condition itself may contain control-flow, new blocks may
3733 // be created. Thus we update "Succ" after adding the condition.
3734 Block = ExitConditionBlock;
3735 Block = EntryConditionBlock = addStmt(C);
3737 // If this block contains a condition variable, add both the condition
3738 // variable and initializer to the CFG.
3739 if (VarDecl *VD = W->getConditionVariable()) {
3740 if (Expr *Init = VD->getInit()) {
3742 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3743 assert(DS->isSingleDecl());
3744 findConstructionContexts(
3745 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3746 const_cast<DeclStmt *>(DS)),
3748 appendStmt(Block, DS);
3749 EntryConditionBlock = addStmt(Init);
3750 assert(Block == EntryConditionBlock);
3751 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3755 if (Block && badCFG)
3758 // See if this is a known constant.
3759 const TryResult& KnownVal = tryEvaluateBool(C);
3761 // Add the loop body entry as a successor to the condition.
3762 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3763 // Link up the condition block with the code that follows the loop. (the
3765 addSuccessor(ExitConditionBlock,
3766 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3769 // Link up the loop-back block to the entry condition block.
3770 addSuccessor(TransitionBlock, EntryConditionBlock);
3772 // There can be no more statements in the condition block since we loop back
3773 // to this block. NULL out Block to force lazy creation of another block.
3776 // Return the condition block, which is the dominating block for the loop.
3777 Succ = EntryConditionBlock;
3778 return EntryConditionBlock;
3781 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
3782 // FIXME: For now we pretend that @catch and the code it contains does not
3787 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
3788 // FIXME: This isn't complete. We basically treat @throw like a return
3791 // If we were in the middle of a block we stop processing that block.
3795 // Create the new block.
3796 Block = createBlock(false);
3798 // The Exit block is the only successor.
3799 addSuccessor(Block, &cfg->getExit());
3801 // Add the statement to the block. This may create new blocks if S contains
3802 // control-flow (short-circuit operations).
3803 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
3806 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
3807 AddStmtChoice asc) {
3808 findConstructionContextsForArguments(ME);
3811 appendObjCMessage(Block, ME);
3813 return VisitChildren(ME);
3816 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
3817 // If we were in the middle of a block we stop processing that block.
3821 // Create the new block.
3822 Block = createBlock(false);
3824 if (TryTerminatedBlock)
3825 // The current try statement is the only successor.
3826 addSuccessor(Block, TryTerminatedBlock);
3828 // otherwise the Exit block is the only successor.
3829 addSuccessor(Block, &cfg->getExit());
3831 // Add the statement to the block. This may create new blocks if S contains
3832 // control-flow (short-circuit operations).
3833 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
3836 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
3837 CFGBlock *LoopSuccessor = nullptr;
3841 // "do...while" is a control-flow statement. Thus we stop processing the
3846 LoopSuccessor = Block;
3848 LoopSuccessor = Succ;
3850 // Because of short-circuit evaluation, the condition of the loop can span
3851 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3852 // evaluate the condition.
3853 CFGBlock *ExitConditionBlock = createBlock(false);
3854 CFGBlock *EntryConditionBlock = ExitConditionBlock;
3856 // Set the terminator for the "exit" condition block.
3857 ExitConditionBlock->setTerminator(D);
3859 // Now add the actual condition to the condition block. Because the condition
3860 // itself may contain control-flow, new blocks may be created.
3861 if (Stmt *C = D->getCond()) {
3862 Block = ExitConditionBlock;
3863 EntryConditionBlock = addStmt(C);
3870 // The condition block is the implicit successor for the loop body.
3871 Succ = EntryConditionBlock;
3873 // See if this is a known constant.
3874 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
3876 // Process the loop body.
3877 CFGBlock *BodyBlock = nullptr;
3879 assert(D->getBody());
3881 // Save the current values for Block, Succ, and continue and break targets
3882 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3883 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3884 save_break(BreakJumpTarget);
3886 // All continues within this loop should go to the condition block
3887 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
3889 // All breaks should go to the code following the loop.
3890 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3892 // NULL out Block to force lazy instantiation of blocks for the body.
3895 // If body is not a compound statement create implicit scope
3896 // and add destructors.
3897 if (!isa<CompoundStmt>(D->getBody()))
3898 addLocalScopeAndDtors(D->getBody());
3900 // Create the body. The returned block is the entry to the loop body.
3901 BodyBlock = addStmt(D->getBody());
3904 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
3910 // Add an intermediate block between the BodyBlock and the
3911 // ExitConditionBlock to represent the "loop back" transition. Create an
3912 // empty block to represent the transition block for looping back to the
3913 // head of the loop.
3914 // FIXME: Can we do this more efficiently without adding another block?
3917 CFGBlock *LoopBackBlock = createBlock();
3918 LoopBackBlock->setLoopTarget(D);
3920 if (!KnownVal.isFalse())
3921 // Add the loop body entry as a successor to the condition.
3922 addSuccessor(ExitConditionBlock, LoopBackBlock);
3924 addSuccessor(ExitConditionBlock, nullptr);
3927 // Link up the condition block with the code that follows the loop.
3928 // (the false branch).
3929 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3931 // There can be no more statements in the body block(s) since we loop back to
3932 // the body. NULL out Block to force lazy creation of another block.
3935 // Return the loop body, which is the dominating block for the loop.
3940 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
3941 // "continue" is a control-flow statement. Thus we stop processing the
3946 // Now create a new block that ends with the continue statement.
3947 Block = createBlock(false);
3948 Block->setTerminator(C);
3950 // If there is no target for the continue, then we are looking at an
3951 // incomplete AST. This means the CFG cannot be constructed.
3952 if (ContinueJumpTarget.block) {
3953 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
3954 addSuccessor(Block, ContinueJumpTarget.block);
3961 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3962 AddStmtChoice asc) {
3963 if (asc.alwaysAdd(*this, E)) {
3965 appendStmt(Block, E);
3968 // VLA types have expressions that must be evaluated.
3969 CFGBlock *lastBlock = Block;
3971 if (E->isArgumentType()) {
3972 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
3973 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
3974 lastBlock = addStmt(VA->getSizeExpr());
3979 /// VisitStmtExpr - Utility method to handle (nested) statement
3980 /// expressions (a GCC extension).
3981 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
3982 if (asc.alwaysAdd(*this, SE)) {
3984 appendStmt(Block, SE);
3986 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
3989 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
3990 // "switch" is a control-flow statement. Thus we stop processing the current
3992 CFGBlock *SwitchSuccessor = nullptr;
3994 // Save local scope position because in case of condition variable ScopePos
3995 // won't be restored when traversing AST.
3996 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3998 // Create local scope for C++17 switch init-stmt if one exists.
3999 if (Stmt *Init = Terminator->getInit())
4000 addLocalScopeForStmt(Init);
4002 // Create local scope for possible condition variable.
4003 // Store scope position. Add implicit destructor.
4004 if (VarDecl *VD = Terminator->getConditionVariable())
4005 addLocalScopeForVarDecl(VD);
4007 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4012 SwitchSuccessor = Block;
4013 } else SwitchSuccessor = Succ;
4015 // Save the current "switch" context.
4016 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
4017 save_default(DefaultCaseBlock);
4018 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4020 // Set the "default" case to be the block after the switch statement. If the
4021 // switch statement contains a "default:", this value will be overwritten with
4022 // the block for that code.
4023 DefaultCaseBlock = SwitchSuccessor;
4025 // Create a new block that will contain the switch statement.
4026 SwitchTerminatedBlock = createBlock(false);
4028 // Now process the switch body. The code after the switch is the implicit
4030 Succ = SwitchSuccessor;
4031 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4033 // When visiting the body, the case statements should automatically get linked
4034 // up to the switch. We also don't keep a pointer to the body, since all
4035 // control-flow from the switch goes to case/default statements.
4036 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4039 // For pruning unreachable case statements, save the current state
4040 // for tracking the condition value.
4041 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
4044 // Determine if the switch condition can be explicitly evaluated.
4045 assert(Terminator->getCond() && "switch condition must be non-NULL");
4046 Expr::EvalResult result;
4047 bool b = tryEvaluate(Terminator->getCond(), result);
4048 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
4049 b ? &result : nullptr);
4051 // If body is not a compound statement create implicit scope
4052 // and add destructors.
4053 if (!isa<CompoundStmt>(Terminator->getBody()))
4054 addLocalScopeAndDtors(Terminator->getBody());
4056 addStmt(Terminator->getBody());
4062 // If we have no "default:" case, the default transition is to the code
4063 // following the switch body. Moreover, take into account if all the
4064 // cases of a switch are covered (e.g., switching on an enum value).
4066 // Note: We add a successor to a switch that is considered covered yet has no
4067 // case statements if the enumeration has no enumerators.
4068 bool SwitchAlwaysHasSuccessor = false;
4069 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4070 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
4071 Terminator->getSwitchCaseList();
4072 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
4073 !SwitchAlwaysHasSuccessor);
4075 // Add the terminator and condition in the switch block.
4076 SwitchTerminatedBlock->setTerminator(Terminator);
4077 Block = SwitchTerminatedBlock;
4078 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4080 // If the SwitchStmt contains a condition variable, add both the
4081 // SwitchStmt and the condition variable initialization to the CFG.
4082 if (VarDecl *VD = Terminator->getConditionVariable()) {
4083 if (Expr *Init = VD->getInit()) {
4085 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
4086 LastBlock = addStmt(Init);
4087 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4091 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4092 if (Stmt *Init = Terminator->getInit()) {
4094 LastBlock = addStmt(Init);
4100 static bool shouldAddCase(bool &switchExclusivelyCovered,
4101 const Expr::EvalResult *switchCond,
4107 bool addCase = false;
4109 if (!switchExclusivelyCovered) {
4110 if (switchCond->Val.isInt()) {
4111 // Evaluate the LHS of the case value.
4112 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4113 const llvm::APSInt &condInt = switchCond->Val.getInt();
4115 if (condInt == lhsInt) {
4117 switchExclusivelyCovered = true;
4119 else if (condInt > lhsInt) {
4120 if (const Expr *RHS = CS->getRHS()) {
4121 // Evaluate the RHS of the case value.
4122 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4123 if (V2 >= condInt) {
4125 switchExclusivelyCovered = true;
4136 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4137 // CaseStmts are essentially labels, so they are the first statement in a
4139 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4141 if (Stmt *Sub = CS->getSubStmt()) {
4142 // For deeply nested chains of CaseStmts, instead of doing a recursion
4143 // (which can blow out the stack), manually unroll and create blocks
4145 while (isa<CaseStmt>(Sub)) {
4146 CFGBlock *currentBlock = createBlock(false);
4147 currentBlock->setLabel(CS);
4150 addSuccessor(LastBlock, currentBlock);
4152 TopBlock = currentBlock;
4154 addSuccessor(SwitchTerminatedBlock,
4155 shouldAddCase(switchExclusivelyCovered, switchCond,
4157 ? currentBlock : nullptr);
4159 LastBlock = currentBlock;
4160 CS = cast<CaseStmt>(Sub);
4161 Sub = CS->getSubStmt();
4167 CFGBlock *CaseBlock = Block;
4169 CaseBlock = createBlock();
4171 // Cases statements partition blocks, so this is the top of the basic block we
4172 // were processing (the "case XXX:" is the label).
4173 CaseBlock->setLabel(CS);
4178 // Add this block to the list of successors for the block with the switch
4180 assert(SwitchTerminatedBlock);
4181 addSuccessor(SwitchTerminatedBlock, CaseBlock,
4182 shouldAddCase(switchExclusivelyCovered, switchCond,
4185 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4189 addSuccessor(LastBlock, CaseBlock);
4192 // This block is now the implicit successor of other blocks.
4199 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4200 if (Terminator->getSubStmt())
4201 addStmt(Terminator->getSubStmt());
4203 DefaultCaseBlock = Block;
4205 if (!DefaultCaseBlock)
4206 DefaultCaseBlock = createBlock();
4208 // Default statements partition blocks, so this is the top of the basic block
4209 // we were processing (the "default:" is the label).
4210 DefaultCaseBlock->setLabel(Terminator);
4215 // Unlike case statements, we don't add the default block to the successors
4216 // for the switch statement immediately. This is done when we finish
4217 // processing the switch statement. This allows for the default case
4218 // (including a fall-through to the code after the switch statement) to always
4219 // be the last successor of a switch-terminated block.
4221 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4224 // This block is now the implicit successor of other blocks.
4225 Succ = DefaultCaseBlock;
4227 return DefaultCaseBlock;
4230 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4231 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4233 CFGBlock *TrySuccessor = nullptr;
4238 TrySuccessor = Block;
4239 } else TrySuccessor = Succ;
4241 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4243 // Create a new block that will contain the try statement.
4244 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4245 // Add the terminator in the try block.
4246 NewTryTerminatedBlock->setTerminator(Terminator);
4248 bool HasCatchAll = false;
4249 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
4250 // The code after the try is the implicit successor.
4251 Succ = TrySuccessor;
4252 CXXCatchStmt *CS = Terminator->getHandler(h);
4253 if (CS->getExceptionDecl() == nullptr) {
4257 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
4260 // Add this block to the list of successors for the block with the try
4262 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4265 if (PrevTryTerminatedBlock)
4266 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4268 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4271 // The code after the try is the implicit successor.
4272 Succ = TrySuccessor;
4274 // Save the current "try" context.
4275 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
4276 cfg->addTryDispatchBlock(TryTerminatedBlock);
4278 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4280 return addStmt(Terminator->getTryBlock());
4283 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4284 // CXXCatchStmt are treated like labels, so they are the first statement in a
4287 // Save local scope position because in case of exception variable ScopePos
4288 // won't be restored when traversing AST.
4289 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4291 // Create local scope for possible exception variable.
4292 // Store scope position. Add implicit destructor.
4293 if (VarDecl *VD = CS->getExceptionDecl()) {
4294 LocalScope::const_iterator BeginScopePos = ScopePos;
4295 addLocalScopeForVarDecl(VD);
4296 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
4299 if (CS->getHandlerBlock())
4300 addStmt(CS->getHandlerBlock());
4302 CFGBlock *CatchBlock = Block;
4304 CatchBlock = createBlock();
4306 // CXXCatchStmt is more than just a label. They have semantic meaning
4307 // as well, as they implicitly "initialize" the catch variable. Add
4308 // it to the CFG as a CFGElement so that the control-flow of these
4309 // semantics gets captured.
4310 appendStmt(CatchBlock, CS);
4312 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4314 CatchBlock->setLabel(CS);
4316 // Bail out if the CFG is bad.
4320 // We set Block to NULL to allow lazy creation of a new block (if necessary)
4326 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4327 // C++0x for-range statements are specified as [stmt.ranged]:
4330 // auto && __range = range-init;
4331 // for ( auto __begin = begin-expr,
4332 // __end = end-expr;
4333 // __begin != __end;
4335 // for-range-declaration = *__begin;
4340 // Save local scope position before the addition of the implicit variables.
4341 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4343 // Create local scopes and destructors for range, begin and end variables.
4344 if (Stmt *Range = S->getRangeStmt())
4345 addLocalScopeForStmt(Range);
4346 if (Stmt *Begin = S->getBeginStmt())
4347 addLocalScopeForStmt(Begin);
4348 if (Stmt *End = S->getEndStmt())
4349 addLocalScopeForStmt(End);
4350 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
4352 LocalScope::const_iterator ContinueScopePos = ScopePos;
4354 // "for" is a control-flow statement. Thus we stop processing the current
4356 CFGBlock *LoopSuccessor = nullptr;
4360 LoopSuccessor = Block;
4362 LoopSuccessor = Succ;
4364 // Save the current value for the break targets.
4365 // All breaks should go to the code following the loop.
4366 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4367 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4369 // The block for the __begin != __end expression.
4370 CFGBlock *ConditionBlock = createBlock(false);
4371 ConditionBlock->setTerminator(S);
4373 // Now add the actual condition to the condition block.
4374 if (Expr *C = S->getCond()) {
4375 Block = ConditionBlock;
4376 CFGBlock *BeginConditionBlock = addStmt(C);
4379 assert(BeginConditionBlock == ConditionBlock &&
4380 "condition block in for-range was unexpectedly complex");
4381 (void)BeginConditionBlock;
4384 // The condition block is the implicit successor for the loop body as well as
4385 // any code above the loop.
4386 Succ = ConditionBlock;
4388 // See if this is a known constant.
4389 TryResult KnownVal(true);
4392 KnownVal = tryEvaluateBool(S->getCond());
4394 // Now create the loop body.
4396 assert(S->getBody());
4398 // Save the current values for Block, Succ, and continue targets.
4399 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
4400 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
4402 // Generate increment code in its own basic block. This is the target of
4403 // continue statements.
4405 Succ = addStmt(S->getInc());
4408 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4410 // The starting block for the loop increment is the block that should
4411 // represent the 'loop target' for looping back to the start of the loop.
4412 ContinueJumpTarget.block->setLoopTarget(S);
4414 // Finish up the increment block and prepare to start the loop body.
4420 // Add implicit scope and dtors for loop variable.
4421 addLocalScopeAndDtors(S->getLoopVarStmt());
4423 // Populate a new block to contain the loop body and loop variable.
4424 addStmt(S->getBody());
4427 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
4431 // This new body block is a successor to our condition block.
4432 addSuccessor(ConditionBlock,
4433 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4436 // Link up the condition block with the code that follows the loop (the
4438 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4440 // Add the initialization statements.
4441 Block = createBlock();
4442 addStmt(S->getBeginStmt());
4443 addStmt(S->getEndStmt());
4444 CFGBlock *Head = addStmt(S->getRangeStmt());
4446 Head = addStmt(S->getInit());
4450 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4451 AddStmtChoice asc, bool ExternallyDestructed) {
4452 if (BuildOpts.AddTemporaryDtors) {
4453 // If adding implicit destructors visit the full expression for adding
4454 // destructors of temporaries.
4455 TempDtorContext Context;
4456 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
4458 // Full expression has to be added as CFGStmt so it will be sequenced
4459 // before destructors of it's temporaries.
4460 asc = asc.withAlwaysAdd(true);
4462 return Visit(E->getSubExpr(), asc);
4465 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4466 AddStmtChoice asc) {
4467 if (asc.alwaysAdd(*this, E)) {
4469 appendStmt(Block, E);
4471 findConstructionContexts(
4472 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
4475 // We do not want to propagate the AlwaysAdd property.
4476 asc = asc.withAlwaysAdd(false);
4478 return Visit(E->getSubExpr(), asc);
4481 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4482 AddStmtChoice asc) {
4483 // If the constructor takes objects as arguments by value, we need to properly
4484 // construct these objects. Construction contexts we find here aren't for the
4485 // constructor C, they're for its arguments only.
4486 findConstructionContextsForArguments(C);
4489 appendConstructor(Block, C);
4491 return VisitChildren(C);
4494 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4495 AddStmtChoice asc) {
4497 appendStmt(Block, NE);
4499 findConstructionContexts(
4500 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
4501 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
4503 if (NE->getInitializer())
4504 Block = Visit(NE->getInitializer());
4506 if (BuildOpts.AddCXXNewAllocator)
4507 appendNewAllocator(Block, NE);
4509 if (NE->isArray() && *NE->getArraySize())
4510 Block = Visit(*NE->getArraySize());
4512 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4513 E = NE->placement_arg_end(); I != E; ++I)
4519 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4520 AddStmtChoice asc) {
4522 appendStmt(Block, DE);
4523 QualType DTy = DE->getDestroyedType();
4524 if (!DTy.isNull()) {
4525 DTy = DTy.getNonReferenceType();
4526 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4528 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4529 appendDeleteDtor(Block, RD, DE);
4533 return VisitChildren(DE);
4536 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4537 AddStmtChoice asc) {
4538 if (asc.alwaysAdd(*this, E)) {
4540 appendStmt(Block, E);
4541 // We do not want to propagate the AlwaysAdd property.
4542 asc = asc.withAlwaysAdd(false);
4544 return Visit(E->getSubExpr(), asc);
4547 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4548 AddStmtChoice asc) {
4549 // If the constructor takes objects as arguments by value, we need to properly
4550 // construct these objects. Construction contexts we find here aren't for the
4551 // constructor C, they're for its arguments only.
4552 findConstructionContextsForArguments(C);
4555 appendConstructor(Block, C);
4556 return VisitChildren(C);
4559 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4560 AddStmtChoice asc) {
4561 if (asc.alwaysAdd(*this, E)) {
4563 appendStmt(Block, E);
4566 if (E->getCastKind() == CK_IntegralToBoolean)
4567 tryEvaluateBool(E->getSubExpr()->IgnoreParens());
4569 return Visit(E->getSubExpr(), AddStmtChoice());
4572 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4573 return Visit(E->getSubExpr(), AddStmtChoice());
4576 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4577 // Lazily create the indirect-goto dispatch block if there isn't one already.
4578 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
4581 IBlock = createBlock(false);
4582 cfg->setIndirectGotoBlock(IBlock);
4585 // IndirectGoto is a control-flow statement. Thus we stop processing the
4586 // current block and create a new one.
4590 Block = createBlock(false);
4591 Block->setTerminator(I);
4592 addSuccessor(Block, IBlock);
4593 return addStmt(I->getTarget());
4596 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
4597 TempDtorContext &Context) {
4598 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4605 switch (E->getStmtClass()) {
4607 return VisitChildrenForTemporaryDtors(E, false, Context);
4609 case Stmt::InitListExprClass:
4610 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
4612 case Stmt::BinaryOperatorClass:
4613 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4614 ExternallyDestructed,
4617 case Stmt::CXXBindTemporaryExprClass:
4618 return VisitCXXBindTemporaryExprForTemporaryDtors(
4619 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
4621 case Stmt::BinaryConditionalOperatorClass:
4622 case Stmt::ConditionalOperatorClass:
4623 return VisitConditionalOperatorForTemporaryDtors(
4624 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
4626 case Stmt::ImplicitCastExprClass:
4627 // For implicit cast we want ExternallyDestructed to be passed further.
4628 E = cast<CastExpr>(E)->getSubExpr();
4631 case Stmt::CXXFunctionalCastExprClass:
4632 // For functional cast we want ExternallyDestructed to be passed further.
4633 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4636 case Stmt::ConstantExprClass:
4637 E = cast<ConstantExpr>(E)->getSubExpr();
4640 case Stmt::ParenExprClass:
4641 E = cast<ParenExpr>(E)->getSubExpr();
4644 case Stmt::MaterializeTemporaryExprClass: {
4645 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4646 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
4647 SmallVector<const Expr *, 2> CommaLHSs;
4648 SmallVector<SubobjectAdjustment, 2> Adjustments;
4649 // Find the expression whose lifetime needs to be extended.
4650 E = const_cast<Expr *>(
4651 cast<MaterializeTemporaryExpr>(E)
4652 ->GetTemporaryExpr()
4653 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4654 // Visit the skipped comma operator left-hand sides for other temporaries.
4655 for (const Expr *CommaLHS : CommaLHSs) {
4656 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
4657 /*ExternallyDestructed=*/false, Context);
4662 case Stmt::BlockExprClass:
4663 // Don't recurse into blocks; their subexpressions don't get evaluated
4667 case Stmt::LambdaExprClass: {
4668 // For lambda expressions, only recurse into the capture initializers,
4669 // and not the body.
4670 auto *LE = cast<LambdaExpr>(E);
4671 CFGBlock *B = Block;
4672 for (Expr *Init : LE->capture_inits()) {
4674 if (CFGBlock *R = VisitForTemporaryDtors(
4675 Init, /*ExternallyDestructed=*/true, Context))
4682 case Stmt::StmtExprClass:
4683 // Don't recurse into statement expressions; any cleanups inside them
4684 // will be wrapped in their own ExprWithCleanups.
4687 case Stmt::CXXDefaultArgExprClass:
4688 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4691 case Stmt::CXXDefaultInitExprClass:
4692 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4697 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4698 bool ExternallyDestructed,
4699 TempDtorContext &Context) {
4700 if (isa<LambdaExpr>(E)) {
4701 // Do not visit the children of lambdas; they have their own CFGs.
4705 // When visiting children for destructors we want to visit them in reverse
4706 // order that they will appear in the CFG. Because the CFG is built
4707 // bottom-up, this means we visit them in their natural order, which
4708 // reverses them in the CFG.
4709 CFGBlock *B = Block;
4710 for (Stmt *Child : E->children())
4712 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
4718 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4719 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
4720 if (E->isCommaOp()) {
4721 // For comma operator LHS expression is visited
4722 // before RHS expression. For destructors visit them in reverse order.
4723 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
4724 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4725 return LHSBlock ? LHSBlock : RHSBlock;
4728 if (E->isLogicalOp()) {
4729 VisitForTemporaryDtors(E->getLHS(), false, Context);
4730 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4731 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4732 RHSExecuted.negate();
4734 // We do not know at CFG-construction time whether the right-hand-side was
4735 // executed, thus we add a branch node that depends on the temporary
4736 // constructor call.
4737 TempDtorContext RHSContext(
4738 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
4739 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
4740 InsertTempDtorDecisionBlock(RHSContext);
4745 if (E->isAssignmentOp()) {
4746 // For assignment operator (=) LHS expression is visited
4747 // before RHS expression. For destructors visit them in reverse order.
4748 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4749 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4750 return LHSBlock ? LHSBlock : RHSBlock;
4753 // For any other binary operator RHS expression is visited before
4754 // LHS expression (order of children). For destructors visit them in reverse
4756 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4757 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4758 return RHSBlock ? RHSBlock : LHSBlock;
4761 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
4762 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
4763 // First add destructors for temporaries in subexpression.
4764 // Because VisitCXXBindTemporaryExpr calls setDestructed:
4765 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
4766 if (!ExternallyDestructed) {
4767 // If lifetime of temporary is not prolonged (by assigning to constant
4768 // reference) add destructor for it.
4770 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
4772 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
4773 // If the destructor is marked as a no-return destructor, we need to
4774 // create a new block for the destructor which does not have as a
4775 // successor anything built thus far. Control won't flow out of this
4778 Block = createNoReturnBlock();
4779 } else if (Context.needsTempDtorBranch()) {
4780 // If we need to introduce a branch, we add a new block that we will hook
4781 // up to a decision block later.
4783 Block = createBlock();
4787 if (Context.needsTempDtorBranch()) {
4788 Context.setDecisionPoint(Succ, E);
4790 appendTemporaryDtor(Block, E);
4797 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4798 CFGBlock *FalseSucc) {
4799 if (!Context.TerminatorExpr) {
4800 // If no temporary was found, we do not need to insert a decision point.
4803 assert(Context.TerminatorExpr);
4804 CFGBlock *Decision = createBlock(false);
4805 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
4806 CFGTerminator::TemporaryDtorsBranch));
4807 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
4808 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
4809 !Context.KnownExecuted.isTrue());
4813 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
4814 AbstractConditionalOperator *E, bool ExternallyDestructed,
4815 TempDtorContext &Context) {
4816 VisitForTemporaryDtors(E->getCond(), false, Context);
4817 CFGBlock *ConditionBlock = Block;
4818 CFGBlock *ConditionSucc = Succ;
4819 TryResult ConditionVal = tryEvaluateBool(E->getCond());
4820 TryResult NegatedVal = ConditionVal;
4821 if (NegatedVal.isKnown()) NegatedVal.negate();
4823 TempDtorContext TrueContext(
4824 bothKnownTrue(Context.KnownExecuted, ConditionVal));
4825 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
4826 CFGBlock *TrueBlock = Block;
4828 Block = ConditionBlock;
4829 Succ = ConditionSucc;
4830 TempDtorContext FalseContext(
4831 bothKnownTrue(Context.KnownExecuted, NegatedVal));
4832 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
4834 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
4835 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
4836 } else if (TrueContext.TerminatorExpr) {
4838 InsertTempDtorDecisionBlock(TrueContext);
4840 InsertTempDtorDecisionBlock(FalseContext);
4845 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
4846 AddStmtChoice asc) {
4847 if (asc.alwaysAdd(*this, D)) {
4849 appendStmt(Block, D);
4852 // Iterate over all used expression in clauses.
4853 CFGBlock *B = Block;
4855 // Reverse the elements to process them in natural order. Iterators are not
4856 // bidirectional, so we need to create temp vector.
4857 SmallVector<Stmt *, 8> Used(
4858 OMPExecutableDirective::used_clauses_children(D->clauses()));
4859 for (Stmt *S : llvm::reverse(Used)) {
4860 assert(S && "Expected non-null used-in-clause child.");
4861 if (CFGBlock *R = Visit(S))
4864 // Visit associated structured block if any.
4865 if (!D->isStandaloneDirective())
4866 if (CapturedStmt *CS = D->getInnermostCapturedStmt()) {
4867 Stmt *S = CS->getCapturedStmt();
4868 if (!isa<CompoundStmt>(S))
4869 addLocalScopeAndDtors(S);
4870 if (CFGBlock *R = addStmt(S))
4877 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4878 /// no successors or predecessors. If this is the first block created in the
4879 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
4880 CFGBlock *CFG::createBlock() {
4881 bool first_block = begin() == end();
4883 // Create the block.
4884 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
4885 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
4886 Blocks.push_back(Mem, BlkBVC);
4888 // If this is the first block, set it as the Entry and Exit.
4890 Entry = Exit = &back();
4892 // Return the block.
4896 /// buildCFG - Constructs a CFG from an AST.
4897 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4898 ASTContext *C, const BuildOptions &BO) {
4899 CFGBuilder Builder(C, BO);
4900 return Builder.buildCFG(D, Statement);
4903 bool CFG::isLinear() const {
4904 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
4905 // in between, then we have no room for control flow.
4909 // Traverse the CFG until we find a branch.
4910 // TODO: While this should still be very fast,
4911 // maybe we should cache the answer.
4912 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
4913 const CFGBlock *B = Entry;
4915 auto IteratorAndFlag = Visited.insert(B);
4916 if (!IteratorAndFlag.second) {
4917 // We looped back to a block that we've already visited. Not linear.
4921 // Iterate over reachable successors.
4922 const CFGBlock *FirstReachableB = nullptr;
4923 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
4924 if (!AB.isReachable())
4927 if (FirstReachableB == nullptr) {
4928 FirstReachableB = &*AB;
4930 // We've encountered a branch. It's not a linear CFG.
4935 if (!FirstReachableB) {
4936 // We reached a dead end. EXIT is unreachable. This is linear enough.
4940 // There's only one way to move forward. Proceed.
4941 B = FirstReachableB;
4944 // We reached EXIT and found no branches.
4948 const CXXDestructorDecl *
4949 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
4950 switch (getKind()) {
4951 case CFGElement::Initializer:
4952 case CFGElement::NewAllocator:
4953 case CFGElement::LoopExit:
4954 case CFGElement::LifetimeEnds:
4955 case CFGElement::Statement:
4956 case CFGElement::Constructor:
4957 case CFGElement::CXXRecordTypedCall:
4958 case CFGElement::ScopeBegin:
4959 case CFGElement::ScopeEnd:
4960 llvm_unreachable("getDestructorDecl should only be used with "
4962 case CFGElement::AutomaticObjectDtor: {
4963 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
4964 QualType ty = var->getType();
4966 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4968 // Lifetime-extending constructs are handled here. This works for a single
4969 // temporary in an initializer expression.
4970 if (ty->isReferenceType()) {
4971 if (const Expr *Init = var->getInit()) {
4972 ty = getReferenceInitTemporaryType(Init);
4976 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
4977 ty = arrayType->getElementType();
4980 // The situation when the type of the lifetime-extending reference
4981 // does not correspond to the type of the object is supposed
4982 // to be handled by now. In particular, 'ty' is now the unwrapped
4984 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
4986 return classDecl->getDestructor();
4988 case CFGElement::DeleteDtor: {
4989 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4990 QualType DTy = DE->getDestroyedType();
4991 DTy = DTy.getNonReferenceType();
4992 const CXXRecordDecl *classDecl =
4993 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4994 return classDecl->getDestructor();
4996 case CFGElement::TemporaryDtor: {
4997 const CXXBindTemporaryExpr *bindExpr =
4998 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
4999 const CXXTemporary *temp = bindExpr->getTemporary();
5000 return temp->getDestructor();
5002 case CFGElement::BaseDtor:
5003 case CFGElement::MemberDtor:
5004 // Not yet supported.
5007 llvm_unreachable("getKind() returned bogus value");
5010 //===----------------------------------------------------------------------===//
5011 // CFGBlock operations.
5012 //===----------------------------------------------------------------------===//
5014 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
5015 : ReachableBlock(IsReachable ? B : nullptr),
5016 UnreachableBlock(!IsReachable ? B : nullptr,
5017 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5019 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
5020 : ReachableBlock(B),
5021 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5022 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5024 void CFGBlock::addSuccessor(AdjacentBlock Succ,
5025 BumpVectorContext &C) {
5026 if (CFGBlock *B = Succ.getReachableBlock())
5027 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
5029 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5030 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
5032 Succs.push_back(Succ, C);
5035 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
5036 const CFGBlock *From, const CFGBlock *To) {
5037 if (F.IgnoreNullPredecessors && !From)
5040 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5041 // If the 'To' has no label or is labeled but the label isn't a
5042 // CaseStmt then filter this edge.
5043 if (const SwitchStmt *S =
5044 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
5045 if (S->isAllEnumCasesCovered()) {
5046 const Stmt *L = To->getLabel();
5047 if (!L || !isa<CaseStmt>(L))
5056 //===----------------------------------------------------------------------===//
5057 // CFG pretty printing
5058 //===----------------------------------------------------------------------===//
5062 class StmtPrinterHelper : public PrinterHelper {
5063 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5064 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5068 signed currentBlock = 0;
5069 unsigned currStmt = 0;
5070 const LangOptions &LangOpts;
5073 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5077 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5079 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5080 BI != BEnd; ++BI, ++j ) {
5081 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5082 const Stmt *stmt= SE->getStmt();
5083 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5086 switch (stmt->getStmtClass()) {
5087 case Stmt::DeclStmtClass:
5088 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
5090 case Stmt::IfStmtClass: {
5091 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
5096 case Stmt::ForStmtClass: {
5097 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
5102 case Stmt::WhileStmtClass: {
5103 const VarDecl *var =
5104 cast<WhileStmt>(stmt)->getConditionVariable();
5109 case Stmt::SwitchStmtClass: {
5110 const VarDecl *var =
5111 cast<SwitchStmt>(stmt)->getConditionVariable();
5116 case Stmt::CXXCatchStmtClass: {
5117 const VarDecl *var =
5118 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5131 ~StmtPrinterHelper() override = default;
5133 const LangOptions &getLangOpts() const { return LangOpts; }
5134 void setBlockID(signed i) { currentBlock = i; }
5135 void setStmtID(unsigned i) { currStmt = i; }
5137 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5138 StmtMapTy::iterator I = StmtMap.find(S);
5140 if (I == StmtMap.end())
5143 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5144 && I->second.second == currStmt) {
5148 OS << "[B" << I->second.first << "." << I->second.second << "]";
5152 bool handleDecl(const Decl *D, raw_ostream &OS) {
5153 DeclMapTy::iterator I = DeclMap.find(D);
5155 if (I == DeclMap.end())
5158 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5159 && I->second.second == currStmt) {
5163 OS << "[B" << I->second.first << "." << I->second.second << "]";
5168 class CFGBlockTerminatorPrint
5169 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5171 StmtPrinterHelper* Helper;
5172 PrintingPolicy Policy;
5175 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5176 const PrintingPolicy &Policy)
5177 : OS(os), Helper(helper), Policy(Policy) {
5178 this->Policy.IncludeNewlines = false;
5181 void VisitIfStmt(IfStmt *I) {
5183 if (Stmt *C = I->getCond())
5184 C->printPretty(OS, Helper, Policy);
5188 void VisitStmt(Stmt *Terminator) {
5189 Terminator->printPretty(OS, Helper, Policy);
5192 void VisitDeclStmt(DeclStmt *DS) {
5193 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5194 OS << "static init " << VD->getName();
5197 void VisitForStmt(ForStmt *F) {
5202 if (Stmt *C = F->getCond())
5203 C->printPretty(OS, Helper, Policy);
5210 void VisitWhileStmt(WhileStmt *W) {
5212 if (Stmt *C = W->getCond())
5213 C->printPretty(OS, Helper, Policy);
5216 void VisitDoStmt(DoStmt *D) {
5217 OS << "do ... while ";
5218 if (Stmt *C = D->getCond())
5219 C->printPretty(OS, Helper, Policy);
5222 void VisitSwitchStmt(SwitchStmt *Terminator) {
5224 Terminator->getCond()->printPretty(OS, Helper, Policy);
5227 void VisitCXXTryStmt(CXXTryStmt *CS) {
5231 void VisitSEHTryStmt(SEHTryStmt *CS) {
5235 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5236 if (Stmt *Cond = C->getCond())
5237 Cond->printPretty(OS, Helper, Policy);
5238 OS << " ? ... : ...";
5241 void VisitChooseExpr(ChooseExpr *C) {
5242 OS << "__builtin_choose_expr( ";
5243 if (Stmt *Cond = C->getCond())
5244 Cond->printPretty(OS, Helper, Policy);
5248 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5250 if (Stmt *T = I->getTarget())
5251 T->printPretty(OS, Helper, Policy);
5254 void VisitBinaryOperator(BinaryOperator* B) {
5255 if (!B->isLogicalOp()) {
5261 B->getLHS()->printPretty(OS, Helper, Policy);
5263 switch (B->getOpcode()) {
5271 llvm_unreachable("Invalid logical operator.");
5275 void VisitExpr(Expr *E) {
5276 E->printPretty(OS, Helper, Policy);
5280 void print(CFGTerminator T) {
5281 switch (T.getKind()) {
5282 case CFGTerminator::StmtBranch:
5285 case CFGTerminator::TemporaryDtorsBranch:
5286 OS << "(Temp Dtor) ";
5289 case CFGTerminator::VirtualBaseBranch:
5290 OS << "(See if most derived ctor has already initialized vbases)";
5298 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5299 const CXXCtorInitializer *I) {
5300 if (I->isBaseInitializer())
5301 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5302 else if (I->isDelegatingInitializer())
5303 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5305 OS << I->getAnyMember()->getName();
5307 if (Expr *IE = I->getInit())
5308 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5311 if (I->isBaseInitializer())
5312 OS << " (Base initializer)";
5313 else if (I->isDelegatingInitializer())
5314 OS << " (Delegating initializer)";
5316 OS << " (Member initializer)";
5319 static void print_construction_context(raw_ostream &OS,
5320 StmtPrinterHelper &Helper,
5321 const ConstructionContext *CC) {
5322 SmallVector<const Stmt *, 3> Stmts;
5323 switch (CC->getKind()) {
5324 case ConstructionContext::SimpleConstructorInitializerKind: {
5326 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5327 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5330 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5333 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5334 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
5335 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5338 case ConstructionContext::SimpleVariableKind: {
5339 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
5340 Stmts.push_back(SDSCC->getDeclStmt());
5343 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5344 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
5345 Stmts.push_back(CDSCC->getDeclStmt());
5346 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5349 case ConstructionContext::NewAllocatedObjectKind: {
5350 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
5351 Stmts.push_back(NECC->getCXXNewExpr());
5354 case ConstructionContext::SimpleReturnedValueKind: {
5355 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
5356 Stmts.push_back(RSCC->getReturnStmt());
5359 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5361 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
5362 Stmts.push_back(RSCC->getReturnStmt());
5363 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5366 case ConstructionContext::SimpleTemporaryObjectKind: {
5367 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5368 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5369 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5372 case ConstructionContext::ElidedTemporaryObjectKind: {
5373 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5374 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5375 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5376 Stmts.push_back(TOCC->getConstructorAfterElision());
5379 case ConstructionContext::ArgumentKind: {
5380 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5381 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5383 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5386 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5387 OS << "+" << ACC->getIndex();
5394 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5398 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5399 const CFGElement &E);
5401 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
5402 StmtPrinterHelper Helper(nullptr, {});
5403 print_elem(OS, Helper, *this);
5406 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5407 const CFGElement &E) {
5408 switch (E.getKind()) {
5409 case CFGElement::Kind::Statement:
5410 case CFGElement::Kind::CXXRecordTypedCall:
5411 case CFGElement::Kind::Constructor: {
5412 CFGStmt CS = E.castAs<CFGStmt>();
5413 const Stmt *S = CS.getStmt();
5414 assert(S != nullptr && "Expecting non-null Stmt");
5416 // special printing for statement-expressions.
5417 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5418 const CompoundStmt *Sub = SE->getSubStmt();
5420 auto Children = Sub->children();
5421 if (Children.begin() != Children.end()) {
5423 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5428 // special printing for comma expressions.
5429 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5430 if (B->getOpcode() == BO_Comma) {
5432 Helper.handledStmt(B->getRHS(),OS);
5437 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5439 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5440 if (isa<CXXOperatorCallExpr>(S))
5441 OS << " (OperatorCall)";
5442 OS << " (CXXRecordTypedCall";
5443 print_construction_context(OS, Helper, VTC->getConstructionContext());
5445 } else if (isa<CXXOperatorCallExpr>(S)) {
5446 OS << " (OperatorCall)";
5447 } else if (isa<CXXBindTemporaryExpr>(S)) {
5448 OS << " (BindTemporary)";
5449 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
5450 OS << " (CXXConstructExpr";
5451 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
5452 print_construction_context(OS, Helper, CE->getConstructionContext());
5454 OS << ", " << CCE->getType().getAsString() << ")";
5455 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
5456 OS << " (" << CE->getStmtClassName() << ", "
5457 << CE->getCastKindName()
5458 << ", " << CE->getType().getAsString()
5462 // Expressions need a newline.
5469 case CFGElement::Kind::Initializer:
5470 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
5474 case CFGElement::Kind::AutomaticObjectDtor: {
5475 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
5476 const VarDecl *VD = DE.getVarDecl();
5477 Helper.handleDecl(VD, OS);
5479 QualType T = VD->getType();
5480 if (T->isReferenceType())
5481 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5484 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5485 OS << "() (Implicit destructor)\n";
5489 case CFGElement::Kind::LifetimeEnds:
5490 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
5491 OS << " (Lifetime ends)\n";
5494 case CFGElement::Kind::LoopExit:
5495 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
5498 case CFGElement::Kind::ScopeBegin:
5499 OS << "CFGScopeBegin(";
5500 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
5501 OS << VD->getQualifiedNameAsString();
5505 case CFGElement::Kind::ScopeEnd:
5506 OS << "CFGScopeEnd(";
5507 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
5508 OS << VD->getQualifiedNameAsString();
5512 case CFGElement::Kind::NewAllocator:
5513 OS << "CFGNewAllocator(";
5514 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
5515 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5519 case CFGElement::Kind::DeleteDtor: {
5520 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
5521 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
5524 CXXDeleteExpr *DelExpr =
5525 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
5526 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
5527 OS << "->~" << RD->getName().str() << "()";
5528 OS << " (Implicit destructor)\n";
5532 case CFGElement::Kind::BaseDtor: {
5533 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
5534 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
5535 OS << " (Base object destructor)\n";
5539 case CFGElement::Kind::MemberDtor: {
5540 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
5541 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
5542 OS << "this->" << FD->getName();
5543 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
5544 OS << " (Member object destructor)\n";
5548 case CFGElement::Kind::TemporaryDtor: {
5549 const CXXBindTemporaryExpr *BT = E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5551 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5552 OS << "() (Temporary object destructor)\n";
5558 static void print_block(raw_ostream &OS, const CFG* cfg,
5560 StmtPrinterHelper &Helper, bool print_edges,
5562 Helper.setBlockID(B.getBlockID());
5564 // Print the header.
5566 OS.changeColor(raw_ostream::YELLOW, true);
5568 OS << "\n [B" << B.getBlockID();
5570 if (&B == &cfg->getEntry())
5571 OS << " (ENTRY)]\n";
5572 else if (&B == &cfg->getExit())
5574 else if (&B == cfg->getIndirectGotoBlock())
5575 OS << " (INDIRECT GOTO DISPATCH)]\n";
5576 else if (B.hasNoReturnElement())
5577 OS << " (NORETURN)]\n";
5584 // Print the label of this block.
5585 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
5589 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
5591 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
5594 C->getLHS()->printPretty(OS, &Helper,
5595 PrintingPolicy(Helper.getLangOpts()));
5598 C->getRHS()->printPretty(OS, &Helper,
5599 PrintingPolicy(Helper.getLangOpts()));
5601 } else if (isa<DefaultStmt>(Label))
5603 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
5605 if (CS->getExceptionDecl())
5606 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
5611 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5613 ES->getFilterExpr()->printPretty(OS, &Helper,
5614 PrintingPolicy(Helper.getLangOpts()), 0);
5617 llvm_unreachable("Invalid label statement in CFGBlock.");
5622 // Iterate through the statements in the block and print them.
5625 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5626 I != E ; ++I, ++j ) {
5627 // Print the statement # in the basic block and the statement itself.
5631 OS << llvm::format("%3d", j) << ": ";
5633 Helper.setStmtID(j);
5635 print_elem(OS, Helper, *I);
5638 // Print the terminator of this block.
5639 if (B.getTerminator().isValid()) {
5641 OS.changeColor(raw_ostream::GREEN);
5645 Helper.setBlockID(-1);
5647 PrintingPolicy PP(Helper.getLangOpts());
5648 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
5649 TPrinter.print(B.getTerminator());
5657 // Print the predecessors of this block.
5658 if (!B.pred_empty()) {
5659 const raw_ostream::Colors Color = raw_ostream::BLUE;
5661 OS.changeColor(Color);
5665 OS << '(' << B.pred_size() << "):";
5669 OS.changeColor(Color);
5671 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
5677 bool Reachable = true;
5680 B = I->getPossiblyUnreachableBlock();
5683 OS << " B" << B->getBlockID();
5685 OS << "(Unreachable)";
5694 // Print the successors of this block.
5695 if (!B.succ_empty()) {
5696 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
5698 OS.changeColor(Color);
5702 OS << '(' << B.succ_size() << "):";
5706 OS.changeColor(Color);
5708 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
5715 bool Reachable = true;
5718 B = I->getPossiblyUnreachableBlock();
5722 OS << " B" << B->getBlockID();
5724 OS << "(Unreachable)";
5738 /// dump - A simple pretty printer of a CFG that outputs to stderr.
5739 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
5740 print(llvm::errs(), LO, ShowColors);
5743 /// print - A simple pretty printer of a CFG that outputs to an ostream.
5744 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
5745 StmtPrinterHelper Helper(this, LO);
5747 // Print the entry block.
5748 print_block(OS, this, getEntry(), Helper, true, ShowColors);
5750 // Iterate through the CFGBlocks and print them one by one.
5751 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5752 // Skip the entry block, because we already printed it.
5753 if (&(**I) == &getEntry() || &(**I) == &getExit())
5756 print_block(OS, this, **I, Helper, true, ShowColors);
5759 // Print the exit block.
5760 print_block(OS, this, getExit(), Helper, true, ShowColors);
5765 size_t CFGBlock::getIndexInCFG() const {
5766 return llvm::find(*getParent(), this) - getParent()->begin();
5769 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
5770 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5771 bool ShowColors) const {
5772 print(llvm::errs(), cfg, LO, ShowColors);
5775 LLVM_DUMP_METHOD void CFGBlock::dump() const {
5776 dump(getParent(), LangOptions(), false);
5779 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5780 /// Generally this will only be called from CFG::print.
5781 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
5782 const LangOptions &LO, bool ShowColors) const {
5783 StmtPrinterHelper Helper(cfg, LO);
5784 print_block(OS, cfg, *this, Helper, true, ShowColors);
5788 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
5789 void CFGBlock::printTerminator(raw_ostream &OS,
5790 const LangOptions &LO) const {
5791 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
5792 TPrinter.print(getTerminator());
5795 /// printTerminatorJson - Pretty-prints the terminator in JSON format.
5796 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
5797 bool AddQuotes) const {
5799 llvm::raw_string_ostream TempOut(Buf);
5801 printTerminator(TempOut, LO);
5803 Out << JsonFormat(TempOut.str(), AddQuotes);
5806 // Returns true if by simply looking at the block, we can be sure that it
5807 // results in a sink during analysis. This is useful to know when the analysis
5808 // was interrupted, and we try to figure out if it would sink eventually.
5809 // There may be many more reasons why a sink would appear during analysis
5810 // (eg. checkers may generate sinks arbitrarily), but here we only consider
5811 // sinks that would be obvious by looking at the CFG.
5812 static bool isImmediateSinkBlock(const CFGBlock *Blk) {
5813 if (Blk->hasNoReturnElement())
5816 // FIXME: Throw-expressions are currently generating sinks during analysis:
5817 // they're not supported yet, and also often used for actually terminating
5818 // the program. So we should treat them as sinks in this analysis as well,
5819 // at least for now, but once we have better support for exceptions,
5820 // we'd need to carefully handle the case when the throw is being
5821 // immediately caught.
5822 if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
5823 if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
5824 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
5833 bool CFGBlock::isInevitablySinking() const {
5834 const CFG &Cfg = *getParent();
5836 const CFGBlock *StartBlk = this;
5837 if (isImmediateSinkBlock(StartBlk))
5840 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
5841 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
5843 DFSWorkList.push_back(StartBlk);
5844 while (!DFSWorkList.empty()) {
5845 const CFGBlock *Blk = DFSWorkList.back();
5846 DFSWorkList.pop_back();
5847 Visited.insert(Blk);
5849 // If at least one path reaches the CFG exit, it means that control is
5850 // returned to the caller. For now, say that we are not sure what
5851 // happens next. If necessary, this can be improved to analyze
5852 // the parent StackFrameContext's call site in a similar manner.
5853 if (Blk == &Cfg.getExit())
5856 for (const auto &Succ : Blk->succs()) {
5857 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
5858 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
5859 // If the block has reachable child blocks that aren't no-return,
5860 // add them to the worklist.
5861 DFSWorkList.push_back(SuccBlk);
5867 // Nothing reached the exit. It can only mean one thing: there's no return.
5871 const Expr *CFGBlock::getLastCondition() const {
5872 // If the terminator is a temporary dtor or a virtual base, etc, we can't
5873 // retrieve a meaningful condition, bail out.
5874 if (Terminator.getKind() != CFGTerminator::StmtBranch)
5877 // Also, if this method was called on a block that doesn't have 2 successors,
5878 // this block doesn't have retrievable condition.
5879 if (succ_size() < 2)
5882 auto StmtElem = rbegin()->getAs<CFGStmt>();
5886 const Stmt *Cond = StmtElem->getStmt();
5887 if (isa<ObjCForCollectionStmt>(Cond))
5890 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
5892 return cast<Expr>(Cond)->IgnoreParens();
5895 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
5896 Stmt *Terminator = getTerminatorStmt();
5902 switch (Terminator->getStmtClass()) {
5906 case Stmt::CXXForRangeStmtClass:
5907 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5910 case Stmt::ForStmtClass:
5911 E = cast<ForStmt>(Terminator)->getCond();
5914 case Stmt::WhileStmtClass:
5915 E = cast<WhileStmt>(Terminator)->getCond();
5918 case Stmt::DoStmtClass:
5919 E = cast<DoStmt>(Terminator)->getCond();
5922 case Stmt::IfStmtClass:
5923 E = cast<IfStmt>(Terminator)->getCond();
5926 case Stmt::ChooseExprClass:
5927 E = cast<ChooseExpr>(Terminator)->getCond();
5930 case Stmt::IndirectGotoStmtClass:
5931 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5934 case Stmt::SwitchStmtClass:
5935 E = cast<SwitchStmt>(Terminator)->getCond();
5938 case Stmt::BinaryConditionalOperatorClass:
5939 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5942 case Stmt::ConditionalOperatorClass:
5943 E = cast<ConditionalOperator>(Terminator)->getCond();
5946 case Stmt::BinaryOperatorClass: // '&&' and '||'
5947 E = cast<BinaryOperator>(Terminator)->getLHS();
5950 case Stmt::ObjCForCollectionStmtClass:
5957 return E ? E->IgnoreParens() : nullptr;
5960 //===----------------------------------------------------------------------===//
5961 // CFG Graphviz Visualization
5962 //===----------------------------------------------------------------------===//
5965 static StmtPrinterHelper* GraphHelper;
5968 void CFG::viewCFG(const LangOptions &LO) const {
5970 StmtPrinterHelper H(this, LO);
5972 llvm::ViewGraph(this,"CFG");
5973 GraphHelper = nullptr;
5980 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
5981 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
5983 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
5985 std::string OutSStr;
5986 llvm::raw_string_ostream Out(OutSStr);
5987 print_block(Out,Graph, *Node, *GraphHelper, false, false);
5988 std::string& OutStr = Out.str();
5990 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5992 // Process string output to make it nicer...
5993 for (unsigned i = 0; i != OutStr.length(); ++i)
5994 if (OutStr[i] == '\n') { // Left justify
5996 OutStr.insert(OutStr.begin()+i+1, 'l');