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/STLExtras.h"
44 #include "llvm/ADT/SetVector.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/Support/Allocator.h"
48 #include "llvm/Support/Casting.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/DOTGraphTraits.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/Format.h"
53 #include "llvm/Support/GraphWriter.h"
54 #include "llvm/Support/SaveAndRestore.h"
55 #include "llvm/Support/raw_ostream.h"
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 /// FIXME: it would be good to unify this function with
76 /// getIntegerLiteralSubexpressionValue at some point given the similarity
77 /// between the functions.
79 static bool IsIntegerLiteralConstantExpr(const Expr
*E
) {
81 E
= E
->IgnoreParens();
83 // Allow conversions to different integer kind.
84 if (const auto *CE
= dyn_cast
<CastExpr
>(E
)) {
85 if (CE
->getCastKind() != CK_IntegralCast
)
90 // Allow negative numbers.
91 if (const auto *UO
= dyn_cast
<UnaryOperator
>(E
)) {
92 if (UO
->getOpcode() != UO_Minus
)
97 return isa
<IntegerLiteral
>(E
);
100 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
101 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
103 static const Expr
*tryTransformToIntOrEnumConstant(const Expr
*E
) {
104 E
= E
->IgnoreParens();
105 if (IsIntegerLiteralConstantExpr(E
))
107 if (auto *DR
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts()))
108 return isa
<EnumConstantDecl
>(DR
->getDecl()) ? DR
: nullptr;
112 /// Tries to interpret a binary operator into `Expr Op NumExpr` form, if
113 /// NumExpr is an integer literal or an enum constant.
115 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
117 static std::tuple
<const Expr
*, BinaryOperatorKind
, const Expr
*>
118 tryNormalizeBinaryOperator(const BinaryOperator
*B
) {
119 BinaryOperatorKind Op
= B
->getOpcode();
121 const Expr
*MaybeDecl
= B
->getLHS();
122 const Expr
*Constant
= tryTransformToIntOrEnumConstant(B
->getRHS());
123 // Expr looked like `0 == Foo` instead of `Foo == 0`
124 if (Constant
== nullptr) {
128 else if (Op
== BO_GE
)
130 else if (Op
== BO_LT
)
132 else if (Op
== BO_LE
)
135 MaybeDecl
= B
->getRHS();
136 Constant
= tryTransformToIntOrEnumConstant(B
->getLHS());
139 return std::make_tuple(MaybeDecl
, Op
, Constant
);
142 /// For an expression `x == Foo && x == Bar`, this determines whether the
143 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
146 /// It's an error to pass this arguments that are not either IntegerLiterals
147 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
148 static bool areExprTypesCompatible(const Expr
*E1
, const Expr
*E2
) {
149 // User intent isn't clear if they're mixing int literals with enum
151 if (isa
<DeclRefExpr
>(E1
) != isa
<DeclRefExpr
>(E2
))
154 // Integer literal comparisons, regardless of literal type, are acceptable.
155 if (!isa
<DeclRefExpr
>(E1
))
158 // IntegerLiterals are handled above and only EnumConstantDecls are expected
160 assert(isa
<DeclRefExpr
>(E1
) && isa
<DeclRefExpr
>(E2
));
161 auto *Decl1
= cast
<DeclRefExpr
>(E1
)->getDecl();
162 auto *Decl2
= cast
<DeclRefExpr
>(E2
)->getDecl();
164 assert(isa
<EnumConstantDecl
>(Decl1
) && isa
<EnumConstantDecl
>(Decl2
));
165 const DeclContext
*DC1
= Decl1
->getDeclContext();
166 const DeclContext
*DC2
= Decl2
->getDeclContext();
168 assert(isa
<EnumDecl
>(DC1
) && isa
<EnumDecl
>(DC2
));
176 /// The CFG builder uses a recursive algorithm to build the CFG. When
177 /// we process an expression, sometimes we know that we must add the
178 /// subexpressions as block-level expressions. For example:
182 /// When processing the '||' expression, we know that exp1 and exp2
183 /// need to be added as block-level expressions, even though they
184 /// might not normally need to be. AddStmtChoice records this
185 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
186 /// the builder has an option not to add a subexpression as a
187 /// block-level expression.
188 class AddStmtChoice
{
190 enum Kind
{ NotAlwaysAdd
= 0, AlwaysAdd
= 1 };
192 AddStmtChoice(Kind a_kind
= NotAlwaysAdd
) : kind(a_kind
) {}
194 bool alwaysAdd(CFGBuilder
&builder
,
195 const Stmt
*stmt
) const;
197 /// Return a copy of this object, except with the 'always-add' bit
198 /// set as specified.
199 AddStmtChoice
withAlwaysAdd(bool alwaysAdd
) const {
200 return AddStmtChoice(alwaysAdd
? AlwaysAdd
: NotAlwaysAdd
);
207 /// LocalScope - Node in tree of local scopes created for C++ implicit
208 /// destructor calls generation. It contains list of automatic variables
209 /// declared in the scope and link to position in previous scope this scope
212 /// The process of creating local scopes is as follows:
213 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
214 /// - Before processing statements in scope (e.g. CompoundStmt) create
215 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
216 /// and set CFGBuilder::ScopePos to the end of new scope,
217 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
219 /// - For every normal (without jump) end of scope add to CFGBlock destructors
220 /// for objects in the current scope,
221 /// - For every jump add to CFGBlock destructors for objects
222 /// between CFGBuilder::ScopePos and local scope position saved for jump
223 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
224 /// jump target position will be on the path to root from CFGBuilder::ScopePos
225 /// (adding any variable that doesn't need constructor to be called to
226 /// LocalScope can break this assumption),
230 using AutomaticVarsTy
= BumpVector
<VarDecl
*>;
232 /// const_iterator - Iterates local scope backwards and jumps to previous
233 /// scope on reaching the beginning of currently iterated scope.
234 class const_iterator
{
235 const LocalScope
* Scope
= nullptr;
237 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
238 /// Invalid iterator (with null Scope) has VarIter equal to 0.
239 unsigned VarIter
= 0;
242 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
243 /// Incrementing invalid iterator is allowed and will result in invalid
245 const_iterator() = default;
247 /// Create valid iterator. In case when S.Prev is an invalid iterator and
248 /// I is equal to 0, this will create invalid iterator.
249 const_iterator(const LocalScope
& S
, unsigned I
)
250 : Scope(&S
), VarIter(I
) {
251 // Iterator to "end" of scope is not allowed. Handle it by going up
252 // in scopes tree possibly up to invalid iterator in the root.
253 if (VarIter
== 0 && Scope
)
257 VarDecl
*const* operator->() const {
258 assert(Scope
&& "Dereferencing invalid iterator is not allowed");
259 assert(VarIter
!= 0 && "Iterator has invalid value of VarIter member");
260 return &Scope
->Vars
[VarIter
- 1];
263 const VarDecl
*getFirstVarInScope() const {
264 assert(Scope
&& "Dereferencing invalid iterator is not allowed");
265 assert(VarIter
!= 0 && "Iterator has invalid value of VarIter member");
266 return Scope
->Vars
[0];
269 VarDecl
*operator*() const {
270 return *this->operator->();
273 const_iterator
&operator++() {
277 assert(VarIter
!= 0 && "Iterator has invalid value of VarIter member");
283 const_iterator
operator++(int) {
284 const_iterator P
= *this;
289 bool operator==(const const_iterator
&rhs
) const {
290 return Scope
== rhs
.Scope
&& VarIter
== rhs
.VarIter
;
292 bool operator!=(const const_iterator
&rhs
) const {
293 return !(*this == rhs
);
296 explicit operator bool() const {
297 return *this != const_iterator();
300 int distance(const_iterator L
);
301 const_iterator
shared_parent(const_iterator L
);
302 bool pointsToFirstDeclaredVar() { return VarIter
== 1; }
303 bool inSameLocalScope(const_iterator rhs
) { return Scope
== rhs
.Scope
; }
307 BumpVectorContext ctx
;
309 /// Automatic variables in order of declaration.
310 AutomaticVarsTy Vars
;
312 /// Iterator to variable in previous scope that was declared just before
313 /// begin of this scope.
317 /// Constructs empty scope linked to previous scope in specified place.
318 LocalScope(BumpVectorContext ctx
, const_iterator P
)
319 : ctx(std::move(ctx
)), Vars(this->ctx
, 4), Prev(P
) {}
321 /// Begin of scope in direction of CFG building (backwards).
322 const_iterator
begin() const { return const_iterator(*this, Vars
.size()); }
324 void addVar(VarDecl
*VD
) {
325 Vars
.push_back(VD
, ctx
);
331 /// distance - Calculates distance from this to L. L must be reachable from this
332 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
333 /// number of scopes between this and L.
334 int LocalScope::const_iterator::distance(LocalScope::const_iterator L
) {
336 const_iterator F
= *this;
337 while (F
.Scope
!= L
.Scope
) {
338 assert(F
!= const_iterator() &&
339 "L iterator is not reachable from F iterator.");
343 D
+= F
.VarIter
- L
.VarIter
;
347 /// Calculates the closest parent of this iterator
348 /// that is in a scope reachable through the parents of L.
349 /// I.e. when using 'goto' from this to L, the lifetime of all variables
350 /// between this and shared_parent(L) end.
351 LocalScope::const_iterator
352 LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L
) {
353 // one of iterators is not valid (we are not in scope), so common
354 // parent is const_iterator() (i.e. sentinel).
355 if ((*this == const_iterator()) || (L
== const_iterator())) {
356 return const_iterator();
359 const_iterator F
= *this;
360 if (F
.inSameLocalScope(L
)) {
361 // Iterators are in the same scope, get common subset of variables.
362 F
.VarIter
= std::min(F
.VarIter
, L
.VarIter
);
366 llvm::SmallDenseMap
<const LocalScope
*, unsigned, 4> ScopesOfL
;
368 ScopesOfL
.try_emplace(L
.Scope
, L
.VarIter
);
369 if (L
== const_iterator())
375 if (auto LIt
= ScopesOfL
.find(F
.Scope
); LIt
!= ScopesOfL
.end()) {
376 // Get common subset of variables in given scope
377 F
.VarIter
= std::min(F
.VarIter
, LIt
->getSecond());
380 assert(F
!= const_iterator() &&
381 "L iterator is not reachable from F iterator.");
388 /// Structure for specifying position in CFG during its build process. It
389 /// consists of CFGBlock that specifies position in CFG and
390 /// LocalScope::const_iterator that specifies position in LocalScope graph.
391 struct BlockScopePosPair
{
392 CFGBlock
*block
= nullptr;
393 LocalScope::const_iterator scopePosition
;
395 BlockScopePosPair() = default;
396 BlockScopePosPair(CFGBlock
*b
, LocalScope::const_iterator scopePos
)
397 : block(b
), scopePosition(scopePos
) {}
400 /// TryResult - a class representing a variant over the values
401 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
402 /// and is used by the CFGBuilder to decide if a branch condition
403 /// can be decided up front during CFG construction.
408 TryResult() = default;
409 TryResult(bool b
) : X(b
? 1 : 0) {}
411 bool isTrue() const { return X
== 1; }
412 bool isFalse() const { return X
== 0; }
413 bool isKnown() const { return X
>= 0; }
423 static TryResult
bothKnownTrue(TryResult R1
, TryResult R2
) {
424 if (!R1
.isKnown() || !R2
.isKnown())
426 return TryResult(R1
.isTrue() && R2
.isTrue());
431 class reverse_children
{
432 llvm::SmallVector
<Stmt
*, 12> childrenBuf
;
433 ArrayRef
<Stmt
*> children
;
436 reverse_children(Stmt
*S
);
438 using iterator
= ArrayRef
<Stmt
*>::reverse_iterator
;
440 iterator
begin() const { return children
.rbegin(); }
441 iterator
end() const { return children
.rend(); }
446 reverse_children::reverse_children(Stmt
*S
) {
447 if (CallExpr
*CE
= dyn_cast
<CallExpr
>(S
)) {
448 children
= CE
->getRawSubExprs();
451 switch (S
->getStmtClass()) {
452 // Note: Fill in this switch with more cases we want to optimize.
453 case Stmt::InitListExprClass
: {
454 InitListExpr
*IE
= cast
<InitListExpr
>(S
);
455 children
= llvm::ArrayRef(reinterpret_cast<Stmt
**>(IE
->getInits()),
463 // Default case for all other statements.
464 llvm::append_range(childrenBuf
, S
->children());
466 // This needs to be done *after* childrenBuf has been populated.
467 children
= childrenBuf
;
472 /// CFGBuilder - This class implements CFG construction from an AST.
473 /// The builder is stateful: an instance of the builder should be used to only
474 /// construct a single CFG.
478 /// CFGBuilder builder;
479 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
481 /// CFG construction is done via a recursive walk of an AST. We actually parse
482 /// the AST in reverse order so that the successor of a basic block is
483 /// constructed prior to its predecessor. This allows us to nicely capture
484 /// implicit fall-throughs without extra basic blocks.
486 using JumpTarget
= BlockScopePosPair
;
487 using JumpSource
= BlockScopePosPair
;
490 std::unique_ptr
<CFG
> cfg
;
493 CFGBlock
*Block
= nullptr;
495 // Block after the current block.
496 CFGBlock
*Succ
= nullptr;
498 JumpTarget ContinueJumpTarget
;
499 JumpTarget BreakJumpTarget
;
500 JumpTarget SEHLeaveJumpTarget
;
501 CFGBlock
*SwitchTerminatedBlock
= nullptr;
502 CFGBlock
*DefaultCaseBlock
= nullptr;
504 // This can point to either a C++ try, an Objective-C @try, or an SEH __try.
505 // try and @try can be mixed and generally work the same.
506 // The frontend forbids mixing SEH __try with either try or @try.
507 // So having one for all three is enough.
508 CFGBlock
*TryTerminatedBlock
= nullptr;
510 // Current position in local scope.
511 LocalScope::const_iterator ScopePos
;
513 // LabelMap records the mapping from Label expressions to their jump targets.
514 using LabelMapTy
= llvm::DenseMap
<LabelDecl
*, JumpTarget
>;
517 // A list of blocks that end with a "goto" that must be backpatched to their
518 // resolved targets upon completion of CFG construction.
519 using BackpatchBlocksTy
= std::vector
<JumpSource
>;
520 BackpatchBlocksTy BackpatchBlocks
;
522 // A list of labels whose address has been taken (for indirect gotos).
523 using LabelSetTy
= llvm::SmallSetVector
<LabelDecl
*, 8>;
524 LabelSetTy AddressTakenLabels
;
526 // Information about the currently visited C++ object construction site.
527 // This is set in the construction trigger and read when the constructor
528 // or a function that returns an object by value is being visited.
529 llvm::DenseMap
<Expr
*, const ConstructionContextLayer
*>
530 ConstructionContextMap
;
533 const CFG::BuildOptions
&BuildOpts
;
535 // State to track for building switch statements.
536 bool switchExclusivelyCovered
= false;
537 Expr::EvalResult
*switchCond
= nullptr;
539 CFG::BuildOptions::ForcedBlkExprs::value_type
*cachedEntry
= nullptr;
540 const Stmt
*lastLookup
= nullptr;
542 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
543 // during construction of branches for chained logical operators.
544 using CachedBoolEvalsTy
= llvm::DenseMap
<Expr
*, TryResult
>;
545 CachedBoolEvalsTy CachedBoolEvals
;
548 explicit CFGBuilder(ASTContext
*astContext
,
549 const CFG::BuildOptions
&buildOpts
)
550 : Context(astContext
), cfg(new CFG()), BuildOpts(buildOpts
) {}
552 // buildCFG - Used by external clients to construct the CFG.
553 std::unique_ptr
<CFG
> buildCFG(const Decl
*D
, Stmt
*Statement
);
555 bool alwaysAdd(const Stmt
*stmt
);
558 // Visitors to walk an AST and construct the CFG.
559 CFGBlock
*VisitInitListExpr(InitListExpr
*ILE
, AddStmtChoice asc
);
560 CFGBlock
*VisitAddrLabelExpr(AddrLabelExpr
*A
, AddStmtChoice asc
);
561 CFGBlock
*VisitAttributedStmt(AttributedStmt
*A
, AddStmtChoice asc
);
562 CFGBlock
*VisitBinaryOperator(BinaryOperator
*B
, AddStmtChoice asc
);
563 CFGBlock
*VisitBreakStmt(BreakStmt
*B
);
564 CFGBlock
*VisitCallExpr(CallExpr
*C
, AddStmtChoice asc
);
565 CFGBlock
*VisitCaseStmt(CaseStmt
*C
);
566 CFGBlock
*VisitChooseExpr(ChooseExpr
*C
, AddStmtChoice asc
);
567 CFGBlock
*VisitCompoundStmt(CompoundStmt
*C
, bool ExternallyDestructed
);
568 CFGBlock
*VisitConditionalOperator(AbstractConditionalOperator
*C
,
570 CFGBlock
*VisitContinueStmt(ContinueStmt
*C
);
571 CFGBlock
*VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr
*E
,
573 CFGBlock
*VisitCXXCatchStmt(CXXCatchStmt
*S
);
574 CFGBlock
*VisitCXXConstructExpr(CXXConstructExpr
*C
, AddStmtChoice asc
);
575 CFGBlock
*VisitCXXNewExpr(CXXNewExpr
*DE
, AddStmtChoice asc
);
576 CFGBlock
*VisitCXXDeleteExpr(CXXDeleteExpr
*DE
, AddStmtChoice asc
);
577 CFGBlock
*VisitCXXForRangeStmt(CXXForRangeStmt
*S
);
578 CFGBlock
*VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr
*E
,
580 CFGBlock
*VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr
*C
,
582 CFGBlock
*VisitCXXThrowExpr(CXXThrowExpr
*T
);
583 CFGBlock
*VisitCXXTryStmt(CXXTryStmt
*S
);
584 CFGBlock
*VisitCXXTypeidExpr(CXXTypeidExpr
*S
, AddStmtChoice asc
);
585 CFGBlock
*VisitDeclStmt(DeclStmt
*DS
);
586 CFGBlock
*VisitDeclSubExpr(DeclStmt
*DS
);
587 CFGBlock
*VisitDefaultStmt(DefaultStmt
*D
);
588 CFGBlock
*VisitDoStmt(DoStmt
*D
);
589 CFGBlock
*VisitExprWithCleanups(ExprWithCleanups
*E
,
590 AddStmtChoice asc
, bool ExternallyDestructed
);
591 CFGBlock
*VisitForStmt(ForStmt
*F
);
592 CFGBlock
*VisitGotoStmt(GotoStmt
*G
);
593 CFGBlock
*VisitGCCAsmStmt(GCCAsmStmt
*G
, AddStmtChoice asc
);
594 CFGBlock
*VisitIfStmt(IfStmt
*I
);
595 CFGBlock
*VisitImplicitCastExpr(ImplicitCastExpr
*E
, AddStmtChoice asc
);
596 CFGBlock
*VisitConstantExpr(ConstantExpr
*E
, AddStmtChoice asc
);
597 CFGBlock
*VisitIndirectGotoStmt(IndirectGotoStmt
*I
);
598 CFGBlock
*VisitLabelStmt(LabelStmt
*L
);
599 CFGBlock
*VisitBlockExpr(BlockExpr
*E
, AddStmtChoice asc
);
600 CFGBlock
*VisitLambdaExpr(LambdaExpr
*E
, AddStmtChoice asc
);
601 CFGBlock
*VisitLogicalOperator(BinaryOperator
*B
);
602 std::pair
<CFGBlock
*, CFGBlock
*> VisitLogicalOperator(BinaryOperator
*B
,
605 CFGBlock
*FalseBlock
);
606 CFGBlock
*VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr
*MTE
,
608 CFGBlock
*VisitMemberExpr(MemberExpr
*M
, AddStmtChoice asc
);
609 CFGBlock
*VisitObjCAtCatchStmt(ObjCAtCatchStmt
*S
);
610 CFGBlock
*VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt
*S
);
611 CFGBlock
*VisitObjCAtThrowStmt(ObjCAtThrowStmt
*S
);
612 CFGBlock
*VisitObjCAtTryStmt(ObjCAtTryStmt
*S
);
613 CFGBlock
*VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt
*S
);
614 CFGBlock
*VisitObjCForCollectionStmt(ObjCForCollectionStmt
*S
);
615 CFGBlock
*VisitObjCMessageExpr(ObjCMessageExpr
*E
, AddStmtChoice asc
);
616 CFGBlock
*VisitPseudoObjectExpr(PseudoObjectExpr
*E
);
617 CFGBlock
*VisitReturnStmt(Stmt
*S
);
618 CFGBlock
*VisitCoroutineSuspendExpr(CoroutineSuspendExpr
*S
,
620 CFGBlock
*VisitSEHExceptStmt(SEHExceptStmt
*S
);
621 CFGBlock
*VisitSEHFinallyStmt(SEHFinallyStmt
*S
);
622 CFGBlock
*VisitSEHLeaveStmt(SEHLeaveStmt
*S
);
623 CFGBlock
*VisitSEHTryStmt(SEHTryStmt
*S
);
624 CFGBlock
*VisitStmtExpr(StmtExpr
*S
, AddStmtChoice asc
);
625 CFGBlock
*VisitSwitchStmt(SwitchStmt
*S
);
626 CFGBlock
*VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr
*E
,
628 CFGBlock
*VisitUnaryOperator(UnaryOperator
*U
, AddStmtChoice asc
);
629 CFGBlock
*VisitWhileStmt(WhileStmt
*W
);
630 CFGBlock
*VisitArrayInitLoopExpr(ArrayInitLoopExpr
*A
, AddStmtChoice asc
);
632 CFGBlock
*Visit(Stmt
*S
, AddStmtChoice asc
= AddStmtChoice::NotAlwaysAdd
,
633 bool ExternallyDestructed
= false);
634 CFGBlock
*VisitStmt(Stmt
*S
, AddStmtChoice asc
);
635 CFGBlock
*VisitChildren(Stmt
*S
);
636 CFGBlock
*VisitNoRecurse(Expr
*E
, AddStmtChoice asc
);
637 CFGBlock
*VisitOMPExecutableDirective(OMPExecutableDirective
*D
,
640 void maybeAddScopeBeginForVarDecl(CFGBlock
*B
, const VarDecl
*VD
,
642 if (ScopePos
&& (VD
== ScopePos
.getFirstVarInScope()))
643 appendScopeBegin(B
, VD
, S
);
646 /// When creating the CFG for temporary destructors, we want to mirror the
647 /// branch structure of the corresponding constructor calls.
648 /// Thus, while visiting a statement for temporary destructors, we keep a
649 /// context to keep track of the following information:
650 /// - whether a subexpression is executed unconditionally
651 /// - if a subexpression is executed conditionally, the first
652 /// CXXBindTemporaryExpr we encounter in that subexpression (which
653 /// corresponds to the last temporary destructor we have to call for this
654 /// subexpression) and the CFG block at that point (which will become the
655 /// successor block when inserting the decision point).
657 /// That way, we can build the branch structure for temporary destructors as
659 /// 1. If a subexpression is executed unconditionally, we add the temporary
660 /// destructor calls to the current block.
661 /// 2. If a subexpression is executed conditionally, when we encounter a
662 /// CXXBindTemporaryExpr:
663 /// a) If it is the first temporary destructor call in the subexpression,
664 /// we remember the CXXBindTemporaryExpr and the current block in the
665 /// TempDtorContext; we start a new block, and insert the temporary
667 /// b) Otherwise, add the temporary destructor call to the current block.
668 /// 3. When we finished visiting a conditionally executed subexpression,
669 /// and we found at least one temporary constructor during the visitation
670 /// (2.a has executed), we insert a decision block that uses the
671 /// CXXBindTemporaryExpr as terminator, and branches to the current block
672 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
673 /// branches to the stored successor.
674 struct TempDtorContext
{
675 TempDtorContext() = default;
676 TempDtorContext(TryResult KnownExecuted
)
677 : IsConditional(true), KnownExecuted(KnownExecuted
) {}
679 /// Returns whether we need to start a new branch for a temporary destructor
680 /// call. This is the case when the temporary destructor is
681 /// conditionally executed, and it is the first one we encounter while
682 /// visiting a subexpression - other temporary destructors at the same level
683 /// will be added to the same block and are executed under the same
685 bool needsTempDtorBranch() const {
686 return IsConditional
&& !TerminatorExpr
;
689 /// Remember the successor S of a temporary destructor decision branch for
690 /// the corresponding CXXBindTemporaryExpr E.
691 void setDecisionPoint(CFGBlock
*S
, CXXBindTemporaryExpr
*E
) {
696 const bool IsConditional
= false;
697 const TryResult KnownExecuted
= true;
698 CFGBlock
*Succ
= nullptr;
699 CXXBindTemporaryExpr
*TerminatorExpr
= nullptr;
702 // Visitors to walk an AST and generate destructors of temporaries in
704 CFGBlock
*VisitForTemporaryDtors(Stmt
*E
, bool ExternallyDestructed
,
705 TempDtorContext
&Context
);
706 CFGBlock
*VisitChildrenForTemporaryDtors(Stmt
*E
, bool ExternallyDestructed
,
707 TempDtorContext
&Context
);
708 CFGBlock
*VisitBinaryOperatorForTemporaryDtors(BinaryOperator
*E
,
709 bool ExternallyDestructed
,
710 TempDtorContext
&Context
);
711 CFGBlock
*VisitCXXBindTemporaryExprForTemporaryDtors(
712 CXXBindTemporaryExpr
*E
, bool ExternallyDestructed
, TempDtorContext
&Context
);
713 CFGBlock
*VisitConditionalOperatorForTemporaryDtors(
714 AbstractConditionalOperator
*E
, bool ExternallyDestructed
,
715 TempDtorContext
&Context
);
716 void InsertTempDtorDecisionBlock(const TempDtorContext
&Context
,
717 CFGBlock
*FalseSucc
= nullptr);
719 // NYS == Not Yet Supported
725 // Remember to apply the construction context based on the current \p Layer
726 // when constructing the CFG element for \p CE.
727 void consumeConstructionContext(const ConstructionContextLayer
*Layer
,
730 // Scan \p Child statement to find constructors in it, while keeping in mind
731 // that its parent statement is providing a partial construction context
732 // described by \p Layer. If a constructor is found, it would be assigned
733 // the context based on the layer. If an additional construction context layer
734 // is found, the function recurses into that.
735 void findConstructionContexts(const ConstructionContextLayer
*Layer
,
738 // Scan all arguments of a call expression for a construction context.
739 // These sorts of call expressions don't have a common superclass,
740 // hence strict duck-typing.
741 template <typename CallLikeExpr
,
742 typename
= std::enable_if_t
<
743 std::is_base_of_v
<CallExpr
, CallLikeExpr
> ||
744 std::is_base_of_v
<CXXConstructExpr
, CallLikeExpr
> ||
745 std::is_base_of_v
<ObjCMessageExpr
, CallLikeExpr
>>>
746 void findConstructionContextsForArguments(CallLikeExpr
*E
) {
747 for (unsigned i
= 0, e
= E
->getNumArgs(); i
!= e
; ++i
) {
748 Expr
*Arg
= E
->getArg(i
);
749 if (Arg
->getType()->getAsCXXRecordDecl() && !Arg
->isGLValue())
750 findConstructionContexts(
751 ConstructionContextLayer::create(cfg
->getBumpVectorContext(),
752 ConstructionContextItem(E
, i
)),
757 // Unset the construction context after consuming it. This is done immediately
758 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
759 // there's no need to do this manually in every Visit... function.
760 void cleanupConstructionContext(Expr
*E
);
762 void autoCreateBlock() { if (!Block
) Block
= createBlock(); }
764 CFGBlock
*createBlock(bool add_successor
= true);
765 CFGBlock
*createNoReturnBlock();
767 CFGBlock
*addStmt(Stmt
*S
) {
768 return Visit(S
, AddStmtChoice::AlwaysAdd
);
771 CFGBlock
*addInitializer(CXXCtorInitializer
*I
);
772 void addLoopExit(const Stmt
*LoopStmt
);
773 void addAutomaticObjHandling(LocalScope::const_iterator B
,
774 LocalScope::const_iterator E
, Stmt
*S
);
775 void addAutomaticObjDestruction(LocalScope::const_iterator B
,
776 LocalScope::const_iterator E
, Stmt
*S
);
777 void addScopeExitHandling(LocalScope::const_iterator B
,
778 LocalScope::const_iterator E
, Stmt
*S
);
779 void addImplicitDtorsForDestructor(const CXXDestructorDecl
*DD
);
780 void addScopeChangesHandling(LocalScope::const_iterator SrcPos
,
781 LocalScope::const_iterator DstPos
,
783 CFGBlock
*createScopeChangesHandlingBlock(LocalScope::const_iterator SrcPos
,
785 LocalScope::const_iterator DstPost
,
788 // Local scopes creation.
789 LocalScope
* createOrReuseLocalScope(LocalScope
* Scope
);
791 void addLocalScopeForStmt(Stmt
*S
);
792 LocalScope
* addLocalScopeForDeclStmt(DeclStmt
*DS
,
793 LocalScope
* Scope
= nullptr);
794 LocalScope
* addLocalScopeForVarDecl(VarDecl
*VD
, LocalScope
* Scope
= nullptr);
796 void addLocalScopeAndDtors(Stmt
*S
);
798 const ConstructionContext
*retrieveAndCleanupConstructionContext(Expr
*E
) {
799 if (!BuildOpts
.AddRichCXXConstructors
)
802 const ConstructionContextLayer
*Layer
= ConstructionContextMap
.lookup(E
);
806 cleanupConstructionContext(E
);
807 return ConstructionContext::createFromLayers(cfg
->getBumpVectorContext(),
811 // Interface to CFGBlock - adding CFGElements.
813 void appendStmt(CFGBlock
*B
, const Stmt
*S
) {
814 if (alwaysAdd(S
) && cachedEntry
)
815 cachedEntry
->second
= B
;
817 // All block-level expressions should have already been IgnoreParens()ed.
818 assert(!isa
<Expr
>(S
) || cast
<Expr
>(S
)->IgnoreParens() == S
);
819 B
->appendStmt(const_cast<Stmt
*>(S
), cfg
->getBumpVectorContext());
822 void appendConstructor(CXXConstructExpr
*CE
) {
823 CXXConstructorDecl
*C
= CE
->getConstructor();
824 if (C
&& C
->isNoReturn())
825 Block
= createNoReturnBlock();
829 if (const ConstructionContext
*CC
=
830 retrieveAndCleanupConstructionContext(CE
)) {
831 Block
->appendConstructor(CE
, CC
, cfg
->getBumpVectorContext());
835 // No valid construction context found. Fall back to statement.
836 Block
->appendStmt(CE
, cfg
->getBumpVectorContext());
839 void appendCall(CFGBlock
*B
, CallExpr
*CE
) {
840 if (alwaysAdd(CE
) && cachedEntry
)
841 cachedEntry
->second
= B
;
843 if (const ConstructionContext
*CC
=
844 retrieveAndCleanupConstructionContext(CE
)) {
845 B
->appendCXXRecordTypedCall(CE
, CC
, cfg
->getBumpVectorContext());
849 // No valid construction context found. Fall back to statement.
850 B
->appendStmt(CE
, cfg
->getBumpVectorContext());
853 void appendInitializer(CFGBlock
*B
, CXXCtorInitializer
*I
) {
854 B
->appendInitializer(I
, cfg
->getBumpVectorContext());
857 void appendNewAllocator(CFGBlock
*B
, CXXNewExpr
*NE
) {
858 B
->appendNewAllocator(NE
, cfg
->getBumpVectorContext());
861 void appendBaseDtor(CFGBlock
*B
, const CXXBaseSpecifier
*BS
) {
862 B
->appendBaseDtor(BS
, cfg
->getBumpVectorContext());
865 void appendMemberDtor(CFGBlock
*B
, FieldDecl
*FD
) {
866 B
->appendMemberDtor(FD
, cfg
->getBumpVectorContext());
869 void appendObjCMessage(CFGBlock
*B
, ObjCMessageExpr
*ME
) {
870 if (alwaysAdd(ME
) && cachedEntry
)
871 cachedEntry
->second
= B
;
873 if (const ConstructionContext
*CC
=
874 retrieveAndCleanupConstructionContext(ME
)) {
875 B
->appendCXXRecordTypedCall(ME
, CC
, cfg
->getBumpVectorContext());
879 B
->appendStmt(const_cast<ObjCMessageExpr
*>(ME
),
880 cfg
->getBumpVectorContext());
883 void appendTemporaryDtor(CFGBlock
*B
, CXXBindTemporaryExpr
*E
) {
884 B
->appendTemporaryDtor(E
, cfg
->getBumpVectorContext());
887 void appendAutomaticObjDtor(CFGBlock
*B
, VarDecl
*VD
, Stmt
*S
) {
888 B
->appendAutomaticObjDtor(VD
, S
, cfg
->getBumpVectorContext());
891 void appendCleanupFunction(CFGBlock
*B
, VarDecl
*VD
) {
892 B
->appendCleanupFunction(VD
, cfg
->getBumpVectorContext());
895 void appendLifetimeEnds(CFGBlock
*B
, VarDecl
*VD
, Stmt
*S
) {
896 B
->appendLifetimeEnds(VD
, S
, cfg
->getBumpVectorContext());
899 void appendLoopExit(CFGBlock
*B
, const Stmt
*LoopStmt
) {
900 B
->appendLoopExit(LoopStmt
, cfg
->getBumpVectorContext());
903 void appendDeleteDtor(CFGBlock
*B
, CXXRecordDecl
*RD
, CXXDeleteExpr
*DE
) {
904 B
->appendDeleteDtor(RD
, DE
, cfg
->getBumpVectorContext());
907 void addSuccessor(CFGBlock
*B
, CFGBlock
*S
, bool IsReachable
= true) {
908 B
->addSuccessor(CFGBlock::AdjacentBlock(S
, IsReachable
),
909 cfg
->getBumpVectorContext());
912 /// Add a reachable successor to a block, with the alternate variant that is
914 void addSuccessor(CFGBlock
*B
, CFGBlock
*ReachableBlock
, CFGBlock
*AltBlock
) {
915 B
->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock
, AltBlock
),
916 cfg
->getBumpVectorContext());
919 void appendScopeBegin(CFGBlock
*B
, const VarDecl
*VD
, const Stmt
*S
) {
920 if (BuildOpts
.AddScopes
)
921 B
->appendScopeBegin(VD
, S
, cfg
->getBumpVectorContext());
924 void appendScopeEnd(CFGBlock
*B
, const VarDecl
*VD
, const Stmt
*S
) {
925 if (BuildOpts
.AddScopes
)
926 B
->appendScopeEnd(VD
, S
, cfg
->getBumpVectorContext());
929 /// Find a relational comparison with an expression evaluating to a
930 /// boolean and a constant other than 0 and 1.
931 /// e.g. if ((x < y) == 10)
932 TryResult
checkIncorrectRelationalOperator(const BinaryOperator
*B
) {
933 const Expr
*LHSExpr
= B
->getLHS()->IgnoreParens();
934 const Expr
*RHSExpr
= B
->getRHS()->IgnoreParens();
936 const IntegerLiteral
*IntLiteral
= dyn_cast
<IntegerLiteral
>(LHSExpr
);
937 const Expr
*BoolExpr
= RHSExpr
;
938 bool IntFirst
= true;
940 IntLiteral
= dyn_cast
<IntegerLiteral
>(RHSExpr
);
945 if (!IntLiteral
|| !BoolExpr
->isKnownToHaveBooleanValue())
948 llvm::APInt IntValue
= IntLiteral
->getValue();
949 if ((IntValue
== 1) || (IntValue
== 0))
952 bool IntLarger
= IntLiteral
->getType()->isUnsignedIntegerType() ||
953 !IntValue
.isNegative();
955 BinaryOperatorKind Bok
= B
->getOpcode();
956 if (Bok
== BO_GT
|| Bok
== BO_GE
) {
957 // Always true for 10 > bool and bool > -1
958 // Always false for -1 > bool and bool > 10
959 return TryResult(IntFirst
== IntLarger
);
961 // Always true for -1 < bool and bool < 10
962 // Always false for 10 < bool and bool < -1
963 return TryResult(IntFirst
!= IntLarger
);
967 /// Find an incorrect equality comparison. Either with an expression
968 /// evaluating to a boolean and a constant other than 0 and 1.
969 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
970 /// true/false e.q. (x & 8) == 4.
971 TryResult
checkIncorrectEqualityOperator(const BinaryOperator
*B
) {
972 const Expr
*LHSExpr
= B
->getLHS()->IgnoreParens();
973 const Expr
*RHSExpr
= B
->getRHS()->IgnoreParens();
975 std::optional
<llvm::APInt
> IntLiteral1
=
976 getIntegerLiteralSubexpressionValue(LHSExpr
);
977 const Expr
*BoolExpr
= RHSExpr
;
980 IntLiteral1
= getIntegerLiteralSubexpressionValue(RHSExpr
);
987 const BinaryOperator
*BitOp
= dyn_cast
<BinaryOperator
>(BoolExpr
);
988 if (BitOp
&& (BitOp
->getOpcode() == BO_And
||
989 BitOp
->getOpcode() == BO_Or
)) {
990 const Expr
*LHSExpr2
= BitOp
->getLHS()->IgnoreParens();
991 const Expr
*RHSExpr2
= BitOp
->getRHS()->IgnoreParens();
993 std::optional
<llvm::APInt
> IntLiteral2
=
994 getIntegerLiteralSubexpressionValue(LHSExpr2
);
997 IntLiteral2
= getIntegerLiteralSubexpressionValue(RHSExpr2
);
1002 if ((BitOp
->getOpcode() == BO_And
&&
1003 (*IntLiteral2
& *IntLiteral1
) != *IntLiteral1
) ||
1004 (BitOp
->getOpcode() == BO_Or
&&
1005 (*IntLiteral2
| *IntLiteral1
) != *IntLiteral1
)) {
1006 if (BuildOpts
.Observer
)
1007 BuildOpts
.Observer
->compareBitwiseEquality(B
,
1008 B
->getOpcode() != BO_EQ
);
1009 return TryResult(B
->getOpcode() != BO_EQ
);
1011 } else if (BoolExpr
->isKnownToHaveBooleanValue()) {
1012 if ((*IntLiteral1
== 1) || (*IntLiteral1
== 0)) {
1015 return TryResult(B
->getOpcode() != BO_EQ
);
1021 // Helper function to get an APInt from an expression. Supports expressions
1022 // which are an IntegerLiteral or a UnaryOperator and returns the value with
1023 // all operations performed on it.
1024 // FIXME: it would be good to unify this function with
1025 // IsIntegerLiteralConstantExpr at some point given the similarity between the
1027 std::optional
<llvm::APInt
>
1028 getIntegerLiteralSubexpressionValue(const Expr
*E
) {
1031 if (const auto *UnOp
= dyn_cast
<UnaryOperator
>(E
->IgnoreParens())) {
1032 // Get the sub expression of the unary expression and get the Integer
1034 const Expr
*SubExpr
= UnOp
->getSubExpr()->IgnoreParens();
1036 if (const auto *IntLiteral
= dyn_cast
<IntegerLiteral
>(SubExpr
)) {
1038 llvm::APInt Value
= IntLiteral
->getValue();
1040 // Perform the operation manually.
1041 switch (UnOp
->getOpcode()) {
1049 return llvm::APInt(Context
->getTypeSize(Context
->IntTy
), !Value
);
1051 assert(false && "Unexpected unary operator!");
1052 return std::nullopt
;
1055 } else if (const auto *IntLiteral
=
1056 dyn_cast
<IntegerLiteral
>(E
->IgnoreParens()))
1057 return IntLiteral
->getValue();
1059 return std::nullopt
;
1062 TryResult
analyzeLogicOperatorCondition(BinaryOperatorKind Relation
,
1063 const llvm::APSInt
&Value1
,
1064 const llvm::APSInt
&Value2
) {
1065 assert(Value1
.isSigned() == Value2
.isSigned());
1070 return TryResult(Value1
== Value2
);
1072 return TryResult(Value1
!= Value2
);
1074 return TryResult(Value1
< Value2
);
1076 return TryResult(Value1
<= Value2
);
1078 return TryResult(Value1
> Value2
);
1080 return TryResult(Value1
>= Value2
);
1084 /// There are two checks handled by this function:
1085 /// 1. Find a law-of-excluded-middle or law-of-noncontradiction expression
1086 /// e.g. if (x || !x), if (x && !x)
1087 /// 2. Find a pair of comparison expressions with or without parentheses
1088 /// with a shared variable and constants and a logical operator between them
1089 /// that always evaluates to either true or false.
1090 /// e.g. if (x != 3 || x != 4)
1091 TryResult
checkIncorrectLogicOperator(const BinaryOperator
*B
) {
1092 assert(B
->isLogicalOp());
1093 const Expr
*LHSExpr
= B
->getLHS()->IgnoreParens();
1094 const Expr
*RHSExpr
= B
->getRHS()->IgnoreParens();
1096 auto CheckLogicalOpWithNegatedVariable
= [this, B
](const Expr
*E1
,
1098 if (const auto *Negate
= dyn_cast
<UnaryOperator
>(E1
)) {
1099 if (Negate
->getOpcode() == UO_LNot
&&
1100 Expr::isSameComparisonOperand(Negate
->getSubExpr(), E2
)) {
1101 bool AlwaysTrue
= B
->getOpcode() == BO_LOr
;
1102 if (BuildOpts
.Observer
)
1103 BuildOpts
.Observer
->logicAlwaysTrue(B
, AlwaysTrue
);
1104 return TryResult(AlwaysTrue
);
1110 TryResult Result
= CheckLogicalOpWithNegatedVariable(LHSExpr
, RHSExpr
);
1111 if (Result
.isKnown())
1113 Result
= CheckLogicalOpWithNegatedVariable(RHSExpr
, LHSExpr
);
1114 if (Result
.isKnown())
1117 const auto *LHS
= dyn_cast
<BinaryOperator
>(LHSExpr
);
1118 const auto *RHS
= dyn_cast
<BinaryOperator
>(RHSExpr
);
1122 if (!LHS
->isComparisonOp() || !RHS
->isComparisonOp())
1125 const Expr
*DeclExpr1
;
1126 const Expr
*NumExpr1
;
1127 BinaryOperatorKind BO1
;
1128 std::tie(DeclExpr1
, BO1
, NumExpr1
) = tryNormalizeBinaryOperator(LHS
);
1130 if (!DeclExpr1
|| !NumExpr1
)
1133 const Expr
*DeclExpr2
;
1134 const Expr
*NumExpr2
;
1135 BinaryOperatorKind BO2
;
1136 std::tie(DeclExpr2
, BO2
, NumExpr2
) = tryNormalizeBinaryOperator(RHS
);
1138 if (!DeclExpr2
|| !NumExpr2
)
1141 // Check that it is the same variable on both sides.
1142 if (!Expr::isSameComparisonOperand(DeclExpr1
, DeclExpr2
))
1145 // Make sure the user's intent is clear (e.g. they're comparing against two
1146 // int literals, or two things from the same enum)
1147 if (!areExprTypesCompatible(NumExpr1
, NumExpr2
))
1150 Expr::EvalResult L1Result
, L2Result
;
1151 if (!NumExpr1
->EvaluateAsInt(L1Result
, *Context
) ||
1152 !NumExpr2
->EvaluateAsInt(L2Result
, *Context
))
1155 llvm::APSInt L1
= L1Result
.Val
.getInt();
1156 llvm::APSInt L2
= L2Result
.Val
.getInt();
1158 // Can't compare signed with unsigned or with different bit width.
1159 if (L1
.isSigned() != L2
.isSigned() || L1
.getBitWidth() != L2
.getBitWidth())
1162 // Values that will be used to determine if result of logical
1163 // operator is always true/false
1164 const llvm::APSInt Values
[] = {
1165 // Value less than both Value1 and Value2
1166 llvm::APSInt::getMinValue(L1
.getBitWidth(), L1
.isUnsigned()),
1169 // Value between Value1 and Value2
1170 ((L1
< L2
) ? L1
: L2
) + llvm::APSInt(llvm::APInt(L1
.getBitWidth(), 1),
1174 // Value greater than both Value1 and Value2
1175 llvm::APSInt::getMaxValue(L1
.getBitWidth(), L1
.isUnsigned()),
1178 // Check whether expression is always true/false by evaluating the following
1179 // * variable x is less than the smallest literal.
1180 // * variable x is equal to the smallest literal.
1181 // * Variable x is between smallest and largest literal.
1182 // * Variable x is equal to the largest literal.
1183 // * Variable x is greater than largest literal.
1184 bool AlwaysTrue
= true, AlwaysFalse
= true;
1185 // Track value of both subexpressions. If either side is always
1186 // true/false, another warning should have already been emitted.
1187 bool LHSAlwaysTrue
= true, LHSAlwaysFalse
= true;
1188 bool RHSAlwaysTrue
= true, RHSAlwaysFalse
= true;
1189 for (const llvm::APSInt
&Value
: Values
) {
1190 TryResult Res1
, Res2
;
1191 Res1
= analyzeLogicOperatorCondition(BO1
, Value
, L1
);
1192 Res2
= analyzeLogicOperatorCondition(BO2
, Value
, L2
);
1194 if (!Res1
.isKnown() || !Res2
.isKnown())
1197 if (B
->getOpcode() == BO_LAnd
) {
1198 AlwaysTrue
&= (Res1
.isTrue() && Res2
.isTrue());
1199 AlwaysFalse
&= !(Res1
.isTrue() && Res2
.isTrue());
1201 AlwaysTrue
&= (Res1
.isTrue() || Res2
.isTrue());
1202 AlwaysFalse
&= !(Res1
.isTrue() || Res2
.isTrue());
1205 LHSAlwaysTrue
&= Res1
.isTrue();
1206 LHSAlwaysFalse
&= Res1
.isFalse();
1207 RHSAlwaysTrue
&= Res2
.isTrue();
1208 RHSAlwaysFalse
&= Res2
.isFalse();
1211 if (AlwaysTrue
|| AlwaysFalse
) {
1212 if (!LHSAlwaysTrue
&& !LHSAlwaysFalse
&& !RHSAlwaysTrue
&&
1213 !RHSAlwaysFalse
&& BuildOpts
.Observer
)
1214 BuildOpts
.Observer
->compareAlwaysTrue(B
, AlwaysTrue
);
1215 return TryResult(AlwaysTrue
);
1220 /// A bitwise-or with a non-zero constant always evaluates to true.
1221 TryResult
checkIncorrectBitwiseOrOperator(const BinaryOperator
*B
) {
1222 const Expr
*LHSConstant
=
1223 tryTransformToIntOrEnumConstant(B
->getLHS()->IgnoreParenImpCasts());
1224 const Expr
*RHSConstant
=
1225 tryTransformToIntOrEnumConstant(B
->getRHS()->IgnoreParenImpCasts());
1227 if ((LHSConstant
&& RHSConstant
) || (!LHSConstant
&& !RHSConstant
))
1230 const Expr
*Constant
= LHSConstant
? LHSConstant
: RHSConstant
;
1232 Expr::EvalResult Result
;
1233 if (!Constant
->EvaluateAsInt(Result
, *Context
))
1236 if (Result
.Val
.getInt() == 0)
1239 if (BuildOpts
.Observer
)
1240 BuildOpts
.Observer
->compareBitwiseOr(B
);
1242 return TryResult(true);
1245 /// Try and evaluate an expression to an integer constant.
1246 bool tryEvaluate(Expr
*S
, Expr::EvalResult
&outResult
) {
1247 if (!BuildOpts
.PruneTriviallyFalseEdges
)
1249 return !S
->isTypeDependent() &&
1250 !S
->isValueDependent() &&
1251 S
->EvaluateAsRValue(outResult
, *Context
);
1254 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1255 /// if we can evaluate to a known value, otherwise return -1.
1256 TryResult
tryEvaluateBool(Expr
*S
) {
1257 if (!BuildOpts
.PruneTriviallyFalseEdges
||
1258 S
->isTypeDependent() || S
->isValueDependent())
1261 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(S
)) {
1262 if (Bop
->isLogicalOp() || Bop
->isEqualityOp()) {
1263 // Check the cache first.
1264 CachedBoolEvalsTy::iterator I
= CachedBoolEvals
.find(S
);
1265 if (I
!= CachedBoolEvals
.end())
1266 return I
->second
; // already in map;
1268 // Retrieve result at first, or the map might be updated.
1269 TryResult Result
= evaluateAsBooleanConditionNoCache(S
);
1270 CachedBoolEvals
[S
] = Result
; // update or insert
1274 switch (Bop
->getOpcode()) {
1276 // For 'x & 0' and 'x * 0', we can determine that
1277 // the value is always false.
1280 // If either operand is zero, we know the value
1282 Expr::EvalResult LHSResult
;
1283 if (Bop
->getLHS()->EvaluateAsInt(LHSResult
, *Context
)) {
1284 llvm::APSInt IntVal
= LHSResult
.Val
.getInt();
1285 if (!IntVal
.getBoolValue()) {
1286 return TryResult(false);
1289 Expr::EvalResult RHSResult
;
1290 if (Bop
->getRHS()->EvaluateAsInt(RHSResult
, *Context
)) {
1291 llvm::APSInt IntVal
= RHSResult
.Val
.getInt();
1292 if (!IntVal
.getBoolValue()) {
1293 return TryResult(false);
1302 return evaluateAsBooleanConditionNoCache(S
);
1305 /// Evaluate as boolean \param E without using the cache.
1306 TryResult
evaluateAsBooleanConditionNoCache(Expr
*E
) {
1307 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(E
)) {
1308 if (Bop
->isLogicalOp()) {
1309 TryResult LHS
= tryEvaluateBool(Bop
->getLHS());
1310 if (LHS
.isKnown()) {
1311 // We were able to evaluate the LHS, see if we can get away with not
1312 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1313 if (LHS
.isTrue() == (Bop
->getOpcode() == BO_LOr
))
1314 return LHS
.isTrue();
1316 TryResult RHS
= tryEvaluateBool(Bop
->getRHS());
1317 if (RHS
.isKnown()) {
1318 if (Bop
->getOpcode() == BO_LOr
)
1319 return LHS
.isTrue() || RHS
.isTrue();
1321 return LHS
.isTrue() && RHS
.isTrue();
1324 TryResult RHS
= tryEvaluateBool(Bop
->getRHS());
1325 if (RHS
.isKnown()) {
1326 // We can't evaluate the LHS; however, sometimes the result
1327 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1328 if (RHS
.isTrue() == (Bop
->getOpcode() == BO_LOr
))
1329 return RHS
.isTrue();
1331 TryResult BopRes
= checkIncorrectLogicOperator(Bop
);
1332 if (BopRes
.isKnown())
1333 return BopRes
.isTrue();
1338 } else if (Bop
->isEqualityOp()) {
1339 TryResult BopRes
= checkIncorrectEqualityOperator(Bop
);
1340 if (BopRes
.isKnown())
1341 return BopRes
.isTrue();
1342 } else if (Bop
->isRelationalOp()) {
1343 TryResult BopRes
= checkIncorrectRelationalOperator(Bop
);
1344 if (BopRes
.isKnown())
1345 return BopRes
.isTrue();
1346 } else if (Bop
->getOpcode() == BO_Or
) {
1347 TryResult BopRes
= checkIncorrectBitwiseOrOperator(Bop
);
1348 if (BopRes
.isKnown())
1349 return BopRes
.isTrue();
1354 if (E
->EvaluateAsBooleanCondition(Result
, *Context
))
1360 bool hasTrivialDestructor(const VarDecl
*VD
) const;
1361 bool needsAutomaticDestruction(const VarDecl
*VD
) const;
1367 clang::extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr
*AILE
) {
1371 Expr
*AILEInit
= AILE
->getSubExpr();
1372 while (const auto *E
= dyn_cast
<ArrayInitLoopExpr
>(AILEInit
))
1373 AILEInit
= E
->getSubExpr();
1378 inline bool AddStmtChoice::alwaysAdd(CFGBuilder
&builder
,
1379 const Stmt
*stmt
) const {
1380 return builder
.alwaysAdd(stmt
) || kind
== AlwaysAdd
;
1383 bool CFGBuilder::alwaysAdd(const Stmt
*stmt
) {
1384 bool shouldAdd
= BuildOpts
.alwaysAdd(stmt
);
1386 if (!BuildOpts
.forcedBlkExprs
)
1389 if (lastLookup
== stmt
) {
1391 assert(cachedEntry
->first
== stmt
);
1399 // Perform the lookup!
1400 CFG::BuildOptions::ForcedBlkExprs
*fb
= *BuildOpts
.forcedBlkExprs
;
1403 // No need to update 'cachedEntry', since it will always be null.
1404 assert(!cachedEntry
);
1408 CFG::BuildOptions::ForcedBlkExprs::iterator itr
= fb
->find(stmt
);
1409 if (itr
== fb
->end()) {
1410 cachedEntry
= nullptr;
1414 cachedEntry
= &*itr
;
1418 // FIXME: Add support for dependent-sized array types in C++?
1419 // Does it even make sense to build a CFG for an uninstantiated template?
1420 static const VariableArrayType
*FindVA(const Type
*t
) {
1421 while (const ArrayType
*vt
= dyn_cast
<ArrayType
>(t
)) {
1422 if (const VariableArrayType
*vat
= dyn_cast
<VariableArrayType
>(vt
))
1423 if (vat
->getSizeExpr())
1426 t
= vt
->getElementType().getTypePtr();
1432 void CFGBuilder::consumeConstructionContext(
1433 const ConstructionContextLayer
*Layer
, Expr
*E
) {
1434 assert((isa
<CXXConstructExpr
>(E
) || isa
<CallExpr
>(E
) ||
1435 isa
<ObjCMessageExpr
>(E
)) && "Expression cannot construct an object!");
1436 if (const ConstructionContextLayer
*PreviouslyStoredLayer
=
1437 ConstructionContextMap
.lookup(E
)) {
1438 (void)PreviouslyStoredLayer
;
1439 // We might have visited this child when we were finding construction
1440 // contexts within its parents.
1441 assert(PreviouslyStoredLayer
->isStrictlyMoreSpecificThan(Layer
) &&
1442 "Already within a different construction context!");
1444 ConstructionContextMap
[E
] = Layer
;
1448 void CFGBuilder::findConstructionContexts(
1449 const ConstructionContextLayer
*Layer
, Stmt
*Child
) {
1450 if (!BuildOpts
.AddRichCXXConstructors
)
1456 auto withExtraLayer
= [this, Layer
](const ConstructionContextItem
&Item
) {
1457 return ConstructionContextLayer::create(cfg
->getBumpVectorContext(), Item
,
1461 switch(Child
->getStmtClass()) {
1462 case Stmt::CXXConstructExprClass
:
1463 case Stmt::CXXTemporaryObjectExprClass
: {
1464 // Support pre-C++17 copy elision AST.
1465 auto *CE
= cast
<CXXConstructExpr
>(Child
);
1466 if (BuildOpts
.MarkElidedCXXConstructors
&& CE
->isElidable()) {
1467 findConstructionContexts(withExtraLayer(CE
), CE
->getArg(0));
1470 consumeConstructionContext(Layer
, CE
);
1473 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1474 // FIXME: An isa<> would look much better but this whole switch is a
1475 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1476 case Stmt::CallExprClass
:
1477 case Stmt::CXXMemberCallExprClass
:
1478 case Stmt::CXXOperatorCallExprClass
:
1479 case Stmt::UserDefinedLiteralClass
:
1480 case Stmt::ObjCMessageExprClass
: {
1481 auto *E
= cast
<Expr
>(Child
);
1482 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E
))
1483 consumeConstructionContext(Layer
, E
);
1486 case Stmt::ExprWithCleanupsClass
: {
1487 auto *Cleanups
= cast
<ExprWithCleanups
>(Child
);
1488 findConstructionContexts(Layer
, Cleanups
->getSubExpr());
1491 case Stmt::CXXFunctionalCastExprClass
: {
1492 auto *Cast
= cast
<CXXFunctionalCastExpr
>(Child
);
1493 findConstructionContexts(Layer
, Cast
->getSubExpr());
1496 case Stmt::ImplicitCastExprClass
: {
1497 auto *Cast
= cast
<ImplicitCastExpr
>(Child
);
1498 // Should we support other implicit cast kinds?
1499 switch (Cast
->getCastKind()) {
1501 case CK_ConstructorConversion
:
1502 findConstructionContexts(Layer
, Cast
->getSubExpr());
1509 case Stmt::CXXBindTemporaryExprClass
: {
1510 auto *BTE
= cast
<CXXBindTemporaryExpr
>(Child
);
1511 findConstructionContexts(withExtraLayer(BTE
), BTE
->getSubExpr());
1514 case Stmt::MaterializeTemporaryExprClass
: {
1515 // Normally we don't want to search in MaterializeTemporaryExpr because
1516 // it indicates the beginning of a temporary object construction context,
1517 // so it shouldn't be found in the middle. However, if it is the beginning
1518 // of an elidable copy or move construction context, we need to include it.
1519 if (Layer
->getItem().getKind() ==
1520 ConstructionContextItem::ElidableConstructorKind
) {
1521 auto *MTE
= cast
<MaterializeTemporaryExpr
>(Child
);
1522 findConstructionContexts(withExtraLayer(MTE
), MTE
->getSubExpr());
1526 case Stmt::ConditionalOperatorClass
: {
1527 auto *CO
= cast
<ConditionalOperator
>(Child
);
1528 if (Layer
->getItem().getKind() !=
1529 ConstructionContextItem::MaterializationKind
) {
1530 // If the object returned by the conditional operator is not going to be a
1531 // temporary object that needs to be immediately materialized, then
1532 // it must be C++17 with its mandatory copy elision. Do not yet promise
1533 // to support this case.
1534 assert(!CO
->getType()->getAsCXXRecordDecl() || CO
->isGLValue() ||
1535 Context
->getLangOpts().CPlusPlus17
);
1538 findConstructionContexts(Layer
, CO
->getLHS());
1539 findConstructionContexts(Layer
, CO
->getRHS());
1542 case Stmt::InitListExprClass
: {
1543 auto *ILE
= cast
<InitListExpr
>(Child
);
1544 if (ILE
->isTransparent()) {
1545 findConstructionContexts(Layer
, ILE
->getInit(0));
1548 // TODO: Handle other cases. For now, fail to find construction contexts.
1551 case Stmt::ParenExprClass
: {
1552 // If expression is placed into parenthesis we should propagate the parent
1553 // construction context to subexpressions.
1554 auto *PE
= cast
<ParenExpr
>(Child
);
1555 findConstructionContexts(Layer
, PE
->getSubExpr());
1563 void CFGBuilder::cleanupConstructionContext(Expr
*E
) {
1564 assert(BuildOpts
.AddRichCXXConstructors
&&
1565 "We should not be managing construction contexts!");
1566 assert(ConstructionContextMap
.count(E
) &&
1567 "Cannot exit construction context without the context!");
1568 ConstructionContextMap
.erase(E
);
1571 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1572 /// arbitrary statement. Examples include a single expression or a function
1573 /// body (compound statement). The ownership of the returned CFG is
1574 /// transferred to the caller. If CFG construction fails, this method returns
1576 std::unique_ptr
<CFG
> CFGBuilder::buildCFG(const Decl
*D
, Stmt
*Statement
) {
1581 // Create an empty block that will serve as the exit block for the CFG. Since
1582 // this is the first block added to the CFG, it will be implicitly registered
1583 // as the exit block.
1584 Succ
= createBlock();
1585 assert(Succ
== &cfg
->getExit());
1586 Block
= nullptr; // the EXIT block is empty. Create all other blocks lazily.
1588 if (BuildOpts
.AddImplicitDtors
)
1589 if (const CXXDestructorDecl
*DD
= dyn_cast_or_null
<CXXDestructorDecl
>(D
))
1590 addImplicitDtorsForDestructor(DD
);
1592 // Visit the statements and create the CFG.
1593 CFGBlock
*B
= addStmt(Statement
);
1598 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1599 // are ignored unless the object is of the most derived class.
1600 // class VBase { VBase() = default; VBase(int) {} };
1601 // class A : virtual public VBase { A() : VBase(0) {} };
1602 // class B : public A {};
1603 // B b; // Constructor calls in order: VBase(), A(), B().
1604 // // VBase(0) is ignored because A isn't the most derived class.
1605 // This may result in the virtual base(s) being already initialized at this
1606 // point, in which case we should jump right onto non-virtual bases and
1607 // fields. To handle this, make a CFG branch. We only need to add one such
1608 // branch per constructor, since the Standard states that all virtual bases
1609 // shall be initialized before non-virtual bases and direct data members.
1610 if (const auto *CD
= dyn_cast_or_null
<CXXConstructorDecl
>(D
)) {
1611 CFGBlock
*VBaseSucc
= nullptr;
1612 for (auto *I
: llvm::reverse(CD
->inits())) {
1613 if (BuildOpts
.AddVirtualBaseBranches
&& !VBaseSucc
&&
1614 I
->isBaseInitializer() && I
->isBaseVirtual()) {
1615 // We've reached the first virtual base init while iterating in reverse
1616 // order. Make a new block for virtual base initializers so that we
1618 VBaseSucc
= Succ
= B
? B
: &cfg
->getExit();
1619 Block
= createBlock();
1621 B
= addInitializer(I
);
1626 // Make a branch block for potentially skipping virtual base initializers.
1630 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch
));
1631 addSuccessor(B
, Block
, true);
1638 // Backpatch the gotos whose label -> block mappings we didn't know when we
1639 // encountered them.
1640 for (BackpatchBlocksTy::iterator I
= BackpatchBlocks
.begin(),
1641 E
= BackpatchBlocks
.end(); I
!= E
; ++I
) {
1643 CFGBlock
*B
= I
->block
;
1644 if (auto *G
= dyn_cast
<GotoStmt
>(B
->getTerminator())) {
1645 LabelMapTy::iterator LI
= LabelMap
.find(G
->getLabel());
1646 // If there is no target for the goto, then we are looking at an
1647 // incomplete AST. Handle this by not registering a successor.
1648 if (LI
== LabelMap
.end())
1650 JumpTarget JT
= LI
->second
;
1652 CFGBlock
*SuccBlk
= createScopeChangesHandlingBlock(
1653 I
->scopePosition
, B
, JT
.scopePosition
, JT
.block
);
1654 addSuccessor(B
, SuccBlk
);
1655 } else if (auto *G
= dyn_cast
<GCCAsmStmt
>(B
->getTerminator())) {
1656 CFGBlock
*Successor
= (I
+1)->block
;
1657 for (auto *L
: G
->labels()) {
1658 LabelMapTy::iterator LI
= LabelMap
.find(L
->getLabel());
1659 // If there is no target for the goto, then we are looking at an
1660 // incomplete AST. Handle this by not registering a successor.
1661 if (LI
== LabelMap
.end())
1663 JumpTarget JT
= LI
->second
;
1664 // Successor has been added, so skip it.
1665 if (JT
.block
== Successor
)
1667 addSuccessor(B
, JT
.block
);
1673 // Add successors to the Indirect Goto Dispatch block (if we have one).
1674 if (CFGBlock
*B
= cfg
->getIndirectGotoBlock())
1675 for (LabelSetTy::iterator I
= AddressTakenLabels
.begin(),
1676 E
= AddressTakenLabels
.end(); I
!= E
; ++I
) {
1677 // Lookup the target block.
1678 LabelMapTy::iterator LI
= LabelMap
.find(*I
);
1680 // If there is no target block that contains label, then we are looking
1681 // at an incomplete AST. Handle this by not registering a successor.
1682 if (LI
== LabelMap
.end()) continue;
1684 addSuccessor(B
, LI
->second
.block
);
1687 // Create an empty entry block that has no predecessors.
1688 cfg
->setEntry(createBlock());
1690 if (BuildOpts
.AddRichCXXConstructors
)
1691 assert(ConstructionContextMap
.empty() &&
1692 "Not all construction contexts were cleaned up!");
1694 return std::move(cfg
);
1697 /// createBlock - Used to lazily create blocks that are connected
1698 /// to the current (global) successor.
1699 CFGBlock
*CFGBuilder::createBlock(bool add_successor
) {
1700 CFGBlock
*B
= cfg
->createBlock();
1701 if (add_successor
&& Succ
)
1702 addSuccessor(B
, Succ
);
1706 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1707 /// CFG. It is *not* connected to the current (global) successor, and instead
1708 /// directly tied to the exit block in order to be reachable.
1709 CFGBlock
*CFGBuilder::createNoReturnBlock() {
1710 CFGBlock
*B
= createBlock(false);
1711 B
->setHasNoReturnElement();
1712 addSuccessor(B
, &cfg
->getExit(), Succ
);
1716 /// addInitializer - Add C++ base or member initializer element to CFG.
1717 CFGBlock
*CFGBuilder::addInitializer(CXXCtorInitializer
*I
) {
1718 if (!BuildOpts
.AddInitializers
)
1721 bool HasTemporaries
= false;
1723 // Destructors of temporaries in initialization expression should be called
1724 // after initialization finishes.
1725 Expr
*Init
= I
->getInit();
1727 HasTemporaries
= isa
<ExprWithCleanups
>(Init
);
1729 if (BuildOpts
.AddTemporaryDtors
&& HasTemporaries
) {
1730 // Generate destructors for temporaries in initialization expression.
1731 TempDtorContext Context
;
1732 VisitForTemporaryDtors(cast
<ExprWithCleanups
>(Init
)->getSubExpr(),
1733 /*ExternallyDestructed=*/false, Context
);
1738 appendInitializer(Block
, I
);
1741 // If the initializer is an ArrayInitLoopExpr, we want to extract the
1742 // initializer, that's used for each element.
1743 auto *AILEInit
= extractElementInitializerFromNestedAILE(
1744 dyn_cast
<ArrayInitLoopExpr
>(Init
));
1746 findConstructionContexts(
1747 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), I
),
1748 AILEInit
? AILEInit
: Init
);
1750 if (HasTemporaries
) {
1751 // For expression with temporaries go directly to subexpression to omit
1752 // generating destructors for the second time.
1753 return Visit(cast
<ExprWithCleanups
>(Init
)->getSubExpr());
1755 if (BuildOpts
.AddCXXDefaultInitExprInCtors
) {
1756 if (CXXDefaultInitExpr
*Default
= dyn_cast
<CXXDefaultInitExpr
>(Init
)) {
1757 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1758 // may cause the same Expr to appear more than once in the CFG. Doing it
1759 // here is safe because there's only one initializer per field.
1761 appendStmt(Block
, Default
);
1762 if (Stmt
*Child
= Default
->getExpr())
1763 if (CFGBlock
*R
= Visit(Child
))
1774 /// Retrieve the type of the temporary object whose lifetime was
1775 /// extended by a local reference with the given initializer.
1776 static QualType
getReferenceInitTemporaryType(const Expr
*Init
,
1777 bool *FoundMTE
= nullptr) {
1779 // Skip parentheses.
1780 Init
= Init
->IgnoreParens();
1782 // Skip through cleanups.
1783 if (const ExprWithCleanups
*EWC
= dyn_cast
<ExprWithCleanups
>(Init
)) {
1784 Init
= EWC
->getSubExpr();
1788 // Skip through the temporary-materialization expression.
1789 if (const MaterializeTemporaryExpr
*MTE
1790 = dyn_cast
<MaterializeTemporaryExpr
>(Init
)) {
1791 Init
= MTE
->getSubExpr();
1797 // Skip sub-object accesses into rvalues.
1798 const Expr
*SkippedInit
= Init
->skipRValueSubobjectAdjustments();
1799 if (SkippedInit
!= Init
) {
1807 return Init
->getType();
1810 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1811 // ended by ReturnStmt, GotoStmt or ThrowExpr.
1812 void CFGBuilder::addLoopExit(const Stmt
*LoopStmt
){
1813 if(!BuildOpts
.AddLoopExit
)
1816 appendLoopExit(Block
, LoopStmt
);
1819 /// Adds the CFG elements for leaving the scope of automatic objects in
1820 /// range [B, E). This include following:
1821 /// * AutomaticObjectDtor for variables with non-trivial destructor
1822 /// * LifetimeEnds for all variables
1823 /// * ScopeEnd for each scope left
1824 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B
,
1825 LocalScope::const_iterator E
,
1827 if (!BuildOpts
.AddScopes
&& !BuildOpts
.AddImplicitDtors
&&
1828 !BuildOpts
.AddLifetime
)
1834 // Not leaving the scope, only need to handle destruction and lifetime
1835 if (B
.inSameLocalScope(E
)) {
1836 addAutomaticObjDestruction(B
, E
, S
);
1840 // Extract information about all local scopes that are left
1841 SmallVector
<LocalScope::const_iterator
, 10> LocalScopeEndMarkers
;
1842 LocalScopeEndMarkers
.push_back(B
);
1843 for (LocalScope::const_iterator I
= B
; I
!= E
; ++I
) {
1844 if (!I
.inSameLocalScope(LocalScopeEndMarkers
.back()))
1845 LocalScopeEndMarkers
.push_back(I
);
1847 LocalScopeEndMarkers
.push_back(E
);
1849 // We need to leave the scope in reverse order, so we reverse the end
1851 std::reverse(LocalScopeEndMarkers
.begin(), LocalScopeEndMarkers
.end());
1853 llvm::zip(LocalScopeEndMarkers
, llvm::drop_begin(LocalScopeEndMarkers
));
1854 for (auto [E
, B
] : Pairwise
) {
1855 if (!B
.inSameLocalScope(E
))
1856 addScopeExitHandling(B
, E
, S
);
1857 addAutomaticObjDestruction(B
, E
, S
);
1861 /// Add CFG elements corresponding to call destructor and end of lifetime
1862 /// of all automatic variables with non-trivial destructor in range [B, E).
1863 /// This include AutomaticObjectDtor and LifetimeEnds elements.
1864 void CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B
,
1865 LocalScope::const_iterator E
,
1867 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
)
1873 SmallVector
<VarDecl
*, 10> DeclsNeedDestruction
;
1874 DeclsNeedDestruction
.reserve(B
.distance(E
));
1876 for (VarDecl
* D
: llvm::make_range(B
, E
))
1877 if (needsAutomaticDestruction(D
))
1878 DeclsNeedDestruction
.push_back(D
);
1880 for (VarDecl
*VD
: llvm::reverse(DeclsNeedDestruction
)) {
1881 if (BuildOpts
.AddImplicitDtors
) {
1882 // If this destructor is marked as a no-return destructor, we need to
1883 // create a new block for the destructor which does not have as a
1884 // successor anything built thus far: control won't flow out of this
1886 QualType Ty
= VD
->getType();
1887 if (Ty
->isReferenceType())
1888 Ty
= getReferenceInitTemporaryType(VD
->getInit());
1889 Ty
= Context
->getBaseElementType(Ty
);
1891 const CXXRecordDecl
*CRD
= Ty
->getAsCXXRecordDecl();
1892 if (CRD
&& CRD
->isAnyDestructorNoReturn())
1893 Block
= createNoReturnBlock();
1898 // Add LifetimeEnd after automatic obj with non-trivial destructors,
1899 // as they end their lifetime when the destructor returns. For trivial
1900 // objects, we end lifetime with scope end.
1901 if (BuildOpts
.AddLifetime
)
1902 appendLifetimeEnds(Block
, VD
, S
);
1903 if (BuildOpts
.AddImplicitDtors
&& !hasTrivialDestructor(VD
))
1904 appendAutomaticObjDtor(Block
, VD
, S
);
1905 if (VD
->hasAttr
<CleanupAttr
>())
1906 appendCleanupFunction(Block
, VD
);
1910 /// Add CFG elements corresponding to leaving a scope.
1911 /// Assumes that range [B, E) corresponds to single scope.
1912 /// This add following elements:
1913 /// * LifetimeEnds for all variables with non-trivial destructor
1914 /// * ScopeEnd for each scope left
1915 void CFGBuilder::addScopeExitHandling(LocalScope::const_iterator B
,
1916 LocalScope::const_iterator E
, Stmt
*S
) {
1917 assert(!B
.inSameLocalScope(E
));
1918 if (!BuildOpts
.AddLifetime
&& !BuildOpts
.AddScopes
)
1921 if (BuildOpts
.AddScopes
) {
1923 appendScopeEnd(Block
, B
.getFirstVarInScope(), S
);
1926 if (!BuildOpts
.AddLifetime
)
1929 // We need to perform the scope leaving in reverse order
1930 SmallVector
<VarDecl
*, 10> DeclsTrivial
;
1931 DeclsTrivial
.reserve(B
.distance(E
));
1933 // Objects with trivial destructor ends their lifetime when their storage
1934 // is destroyed, for automatic variables, this happens when the end of the
1936 for (VarDecl
* D
: llvm::make_range(B
, E
))
1937 if (!needsAutomaticDestruction(D
))
1938 DeclsTrivial
.push_back(D
);
1940 if (DeclsTrivial
.empty())
1944 for (VarDecl
*VD
: llvm::reverse(DeclsTrivial
))
1945 appendLifetimeEnds(Block
, VD
, S
);
1948 /// addScopeChangesHandling - appends information about destruction, lifetime
1949 /// and cfgScopeEnd for variables in the scope that was left by the jump, and
1950 /// appends cfgScopeBegin for all scopes that where entered.
1951 /// We insert the cfgScopeBegin at the end of the jump node, as depending on
1952 /// the sourceBlock, each goto, may enter different amount of scopes.
1953 void CFGBuilder::addScopeChangesHandling(LocalScope::const_iterator SrcPos
,
1954 LocalScope::const_iterator DstPos
,
1956 assert(Block
&& "Source block should be always crated");
1957 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
&&
1958 !BuildOpts
.AddScopes
) {
1962 if (SrcPos
== DstPos
)
1965 // Get common scope, the jump leaves all scopes [SrcPos, BasePos), and
1966 // enter all scopes between [DstPos, BasePos)
1967 LocalScope::const_iterator BasePos
= SrcPos
.shared_parent(DstPos
);
1969 // Append scope begins for scopes entered by goto
1970 if (BuildOpts
.AddScopes
&& !DstPos
.inSameLocalScope(BasePos
)) {
1971 for (LocalScope::const_iterator I
= DstPos
; I
!= BasePos
; ++I
)
1972 if (I
.pointsToFirstDeclaredVar())
1973 appendScopeBegin(Block
, *I
, S
);
1976 // Append scopeEnds, destructor and lifetime with the terminator for
1977 // block left by goto.
1978 addAutomaticObjHandling(SrcPos
, BasePos
, S
);
1981 /// createScopeChangesHandlingBlock - Creates a block with cfgElements
1982 /// corresponding to changing the scope from the source scope of the GotoStmt,
1983 /// to destination scope. Add destructor, lifetime and cfgScopeEnd
1984 /// CFGElements to newly created CFGBlock, that will have the CFG terminator
1986 CFGBlock
*CFGBuilder::createScopeChangesHandlingBlock(
1987 LocalScope::const_iterator SrcPos
, CFGBlock
*SrcBlk
,
1988 LocalScope::const_iterator DstPos
, CFGBlock
*DstBlk
) {
1989 if (SrcPos
== DstPos
)
1992 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
&&
1993 (!BuildOpts
.AddScopes
|| SrcPos
.inSameLocalScope(DstPos
)))
1996 // We will update CFBBuilder when creating new block, restore the
1997 // previous state at exit.
1998 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
2000 // Create a new block, and transfer terminator
2001 Block
= createBlock(false);
2002 Block
->setTerminator(SrcBlk
->getTerminator());
2003 SrcBlk
->setTerminator(CFGTerminator());
2004 addSuccessor(Block
, DstBlk
);
2006 // Fill the created Block with the required elements.
2007 addScopeChangesHandling(SrcPos
, DstPos
, Block
->getTerminatorStmt());
2009 assert(Block
&& "There should be at least one scope changing Block");
2013 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
2014 /// base and member objects in destructor.
2015 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl
*DD
) {
2016 assert(BuildOpts
.AddImplicitDtors
&&
2017 "Can be called only when dtors should be added");
2018 const CXXRecordDecl
*RD
= DD
->getParent();
2020 // At the end destroy virtual base objects.
2021 for (const auto &VI
: RD
->vbases()) {
2022 // TODO: Add a VirtualBaseBranch to see if the most derived class
2023 // (which is different from the current class) is responsible for
2025 const CXXRecordDecl
*CD
= VI
.getType()->getAsCXXRecordDecl();
2026 if (CD
&& !CD
->hasTrivialDestructor()) {
2028 appendBaseDtor(Block
, &VI
);
2032 // Before virtual bases destroy direct base objects.
2033 for (const auto &BI
: RD
->bases()) {
2034 if (!BI
.isVirtual()) {
2035 const CXXRecordDecl
*CD
= BI
.getType()->getAsCXXRecordDecl();
2036 if (CD
&& !CD
->hasTrivialDestructor()) {
2038 appendBaseDtor(Block
, &BI
);
2043 // First destroy member objects.
2044 for (auto *FI
: RD
->fields()) {
2045 // Check for constant size array. Set type to array element type.
2046 QualType QT
= FI
->getType();
2047 // It may be a multidimensional array.
2048 while (const ConstantArrayType
*AT
= Context
->getAsConstantArrayType(QT
)) {
2049 if (AT
->isZeroSize())
2051 QT
= AT
->getElementType();
2054 if (const CXXRecordDecl
*CD
= QT
->getAsCXXRecordDecl())
2055 if (!CD
->hasTrivialDestructor()) {
2057 appendMemberDtor(Block
, FI
);
2062 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
2063 /// way return valid LocalScope object.
2064 LocalScope
* CFGBuilder::createOrReuseLocalScope(LocalScope
* Scope
) {
2067 llvm::BumpPtrAllocator
&alloc
= cfg
->getAllocator();
2068 return new (alloc
) LocalScope(BumpVectorContext(alloc
), ScopePos
);
2071 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
2072 /// that should create implicit scope (e.g. if/else substatements).
2073 void CFGBuilder::addLocalScopeForStmt(Stmt
*S
) {
2074 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
&&
2075 !BuildOpts
.AddScopes
)
2078 LocalScope
*Scope
= nullptr;
2080 // For compound statement we will be creating explicit scope.
2081 if (CompoundStmt
*CS
= dyn_cast
<CompoundStmt
>(S
)) {
2082 for (auto *BI
: CS
->body()) {
2083 Stmt
*SI
= BI
->stripLabelLikeStatements();
2084 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(SI
))
2085 Scope
= addLocalScopeForDeclStmt(DS
, Scope
);
2090 // For any other statement scope will be implicit and as such will be
2091 // interesting only for DeclStmt.
2092 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(S
->stripLabelLikeStatements()))
2093 addLocalScopeForDeclStmt(DS
);
2096 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
2097 /// reuse Scope if not NULL.
2098 LocalScope
* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt
*DS
,
2099 LocalScope
* Scope
) {
2100 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
&&
2101 !BuildOpts
.AddScopes
)
2104 for (auto *DI
: DS
->decls())
2105 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(DI
))
2106 Scope
= addLocalScopeForVarDecl(VD
, Scope
);
2110 bool CFGBuilder::needsAutomaticDestruction(const VarDecl
*VD
) const {
2111 return !hasTrivialDestructor(VD
) || VD
->hasAttr
<CleanupAttr
>();
2114 bool CFGBuilder::hasTrivialDestructor(const VarDecl
*VD
) const {
2115 // Check for const references bound to temporary. Set type to pointee.
2116 QualType QT
= VD
->getType();
2117 if (QT
->isReferenceType()) {
2118 // Attempt to determine whether this declaration lifetime-extends a
2121 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
2122 // temporaries, and a single declaration can extend multiple temporaries.
2123 // We should look at the storage duration on each nested
2124 // MaterializeTemporaryExpr instead.
2126 const Expr
*Init
= VD
->getInit();
2128 // Probably an exception catch-by-reference variable.
2129 // FIXME: It doesn't really mean that the object has a trivial destructor.
2130 // Also are there other cases?
2134 // Lifetime-extending a temporary?
2135 bool FoundMTE
= false;
2136 QT
= getReferenceInitTemporaryType(Init
, &FoundMTE
);
2141 // Check for constant size array. Set type to array element type.
2142 while (const ConstantArrayType
*AT
= Context
->getAsConstantArrayType(QT
)) {
2143 if (AT
->isZeroSize())
2145 QT
= AT
->getElementType();
2148 // Check if type is a C++ class with non-trivial destructor.
2149 if (const CXXRecordDecl
*CD
= QT
->getAsCXXRecordDecl())
2150 return !CD
->hasDefinition() || CD
->hasTrivialDestructor();
2154 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2155 /// create add scope for automatic objects and temporary objects bound to
2156 /// const reference. Will reuse Scope if not NULL.
2157 LocalScope
* CFGBuilder::addLocalScopeForVarDecl(VarDecl
*VD
,
2158 LocalScope
* Scope
) {
2159 if (!BuildOpts
.AddImplicitDtors
&& !BuildOpts
.AddLifetime
&&
2160 !BuildOpts
.AddScopes
)
2163 // Check if variable is local.
2164 if (!VD
->hasLocalStorage())
2167 if (!BuildOpts
.AddLifetime
&& !BuildOpts
.AddScopes
&&
2168 !needsAutomaticDestruction(VD
)) {
2169 assert(BuildOpts
.AddImplicitDtors
);
2173 // Add the variable to scope
2174 Scope
= createOrReuseLocalScope(Scope
);
2176 ScopePos
= Scope
->begin();
2180 /// addLocalScopeAndDtors - For given statement add local scope for it and
2181 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
2182 void CFGBuilder::addLocalScopeAndDtors(Stmt
*S
) {
2183 LocalScope::const_iterator scopeBeginPos
= ScopePos
;
2184 addLocalScopeForStmt(S
);
2185 addAutomaticObjHandling(ScopePos
, scopeBeginPos
, S
);
2188 /// Visit - Walk the subtree of a statement and add extra
2189 /// blocks for ternary operators, &&, and ||. We also process "," and
2190 /// DeclStmts (which may contain nested control-flow).
2191 CFGBlock
*CFGBuilder::Visit(Stmt
* S
, AddStmtChoice asc
,
2192 bool ExternallyDestructed
) {
2198 if (Expr
*E
= dyn_cast
<Expr
>(S
))
2199 S
= E
->IgnoreParens();
2201 if (Context
->getLangOpts().OpenMP
)
2202 if (auto *D
= dyn_cast
<OMPExecutableDirective
>(S
))
2203 return VisitOMPExecutableDirective(D
, asc
);
2205 switch (S
->getStmtClass()) {
2207 return VisitStmt(S
, asc
);
2209 case Stmt::ImplicitValueInitExprClass
:
2210 if (BuildOpts
.OmitImplicitValueInitializers
)
2212 return VisitStmt(S
, asc
);
2214 case Stmt::InitListExprClass
:
2215 return VisitInitListExpr(cast
<InitListExpr
>(S
), asc
);
2217 case Stmt::AttributedStmtClass
:
2218 return VisitAttributedStmt(cast
<AttributedStmt
>(S
), asc
);
2220 case Stmt::AddrLabelExprClass
:
2221 return VisitAddrLabelExpr(cast
<AddrLabelExpr
>(S
), asc
);
2223 case Stmt::BinaryConditionalOperatorClass
:
2224 return VisitConditionalOperator(cast
<BinaryConditionalOperator
>(S
), asc
);
2226 case Stmt::BinaryOperatorClass
:
2227 return VisitBinaryOperator(cast
<BinaryOperator
>(S
), asc
);
2229 case Stmt::BlockExprClass
:
2230 return VisitBlockExpr(cast
<BlockExpr
>(S
), asc
);
2232 case Stmt::BreakStmtClass
:
2233 return VisitBreakStmt(cast
<BreakStmt
>(S
));
2235 case Stmt::CallExprClass
:
2236 case Stmt::CXXOperatorCallExprClass
:
2237 case Stmt::CXXMemberCallExprClass
:
2238 case Stmt::UserDefinedLiteralClass
:
2239 return VisitCallExpr(cast
<CallExpr
>(S
), asc
);
2241 case Stmt::CaseStmtClass
:
2242 return VisitCaseStmt(cast
<CaseStmt
>(S
));
2244 case Stmt::ChooseExprClass
:
2245 return VisitChooseExpr(cast
<ChooseExpr
>(S
), asc
);
2247 case Stmt::CompoundStmtClass
:
2248 return VisitCompoundStmt(cast
<CompoundStmt
>(S
), ExternallyDestructed
);
2250 case Stmt::ConditionalOperatorClass
:
2251 return VisitConditionalOperator(cast
<ConditionalOperator
>(S
), asc
);
2253 case Stmt::ContinueStmtClass
:
2254 return VisitContinueStmt(cast
<ContinueStmt
>(S
));
2256 case Stmt::CXXCatchStmtClass
:
2257 return VisitCXXCatchStmt(cast
<CXXCatchStmt
>(S
));
2259 case Stmt::ExprWithCleanupsClass
:
2260 return VisitExprWithCleanups(cast
<ExprWithCleanups
>(S
),
2261 asc
, ExternallyDestructed
);
2263 case Stmt::CXXDefaultArgExprClass
:
2264 case Stmt::CXXDefaultInitExprClass
:
2265 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2266 // called function's declaration, not by the caller. If we simply add
2267 // this expression to the CFG, we could end up with the same Expr
2268 // appearing multiple times (PR13385).
2270 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2271 // expression to be used in the same function (through aggregate
2273 return VisitStmt(S
, asc
);
2275 case Stmt::CXXBindTemporaryExprClass
:
2276 return VisitCXXBindTemporaryExpr(cast
<CXXBindTemporaryExpr
>(S
), asc
);
2278 case Stmt::CXXConstructExprClass
:
2279 return VisitCXXConstructExpr(cast
<CXXConstructExpr
>(S
), asc
);
2281 case Stmt::CXXNewExprClass
:
2282 return VisitCXXNewExpr(cast
<CXXNewExpr
>(S
), asc
);
2284 case Stmt::CXXDeleteExprClass
:
2285 return VisitCXXDeleteExpr(cast
<CXXDeleteExpr
>(S
), asc
);
2287 case Stmt::CXXFunctionalCastExprClass
:
2288 return VisitCXXFunctionalCastExpr(cast
<CXXFunctionalCastExpr
>(S
), asc
);
2290 case Stmt::CXXTemporaryObjectExprClass
:
2291 return VisitCXXTemporaryObjectExpr(cast
<CXXTemporaryObjectExpr
>(S
), asc
);
2293 case Stmt::CXXThrowExprClass
:
2294 return VisitCXXThrowExpr(cast
<CXXThrowExpr
>(S
));
2296 case Stmt::CXXTryStmtClass
:
2297 return VisitCXXTryStmt(cast
<CXXTryStmt
>(S
));
2299 case Stmt::CXXTypeidExprClass
:
2300 return VisitCXXTypeidExpr(cast
<CXXTypeidExpr
>(S
), asc
);
2302 case Stmt::CXXForRangeStmtClass
:
2303 return VisitCXXForRangeStmt(cast
<CXXForRangeStmt
>(S
));
2305 case Stmt::DeclStmtClass
:
2306 return VisitDeclStmt(cast
<DeclStmt
>(S
));
2308 case Stmt::DefaultStmtClass
:
2309 return VisitDefaultStmt(cast
<DefaultStmt
>(S
));
2311 case Stmt::DoStmtClass
:
2312 return VisitDoStmt(cast
<DoStmt
>(S
));
2314 case Stmt::ForStmtClass
:
2315 return VisitForStmt(cast
<ForStmt
>(S
));
2317 case Stmt::GotoStmtClass
:
2318 return VisitGotoStmt(cast
<GotoStmt
>(S
));
2320 case Stmt::GCCAsmStmtClass
:
2321 return VisitGCCAsmStmt(cast
<GCCAsmStmt
>(S
), asc
);
2323 case Stmt::IfStmtClass
:
2324 return VisitIfStmt(cast
<IfStmt
>(S
));
2326 case Stmt::ImplicitCastExprClass
:
2327 return VisitImplicitCastExpr(cast
<ImplicitCastExpr
>(S
), asc
);
2329 case Stmt::ConstantExprClass
:
2330 return VisitConstantExpr(cast
<ConstantExpr
>(S
), asc
);
2332 case Stmt::IndirectGotoStmtClass
:
2333 return VisitIndirectGotoStmt(cast
<IndirectGotoStmt
>(S
));
2335 case Stmt::LabelStmtClass
:
2336 return VisitLabelStmt(cast
<LabelStmt
>(S
));
2338 case Stmt::LambdaExprClass
:
2339 return VisitLambdaExpr(cast
<LambdaExpr
>(S
), asc
);
2341 case Stmt::MaterializeTemporaryExprClass
:
2342 return VisitMaterializeTemporaryExpr(cast
<MaterializeTemporaryExpr
>(S
),
2345 case Stmt::MemberExprClass
:
2346 return VisitMemberExpr(cast
<MemberExpr
>(S
), asc
);
2348 case Stmt::NullStmtClass
:
2351 case Stmt::ObjCAtCatchStmtClass
:
2352 return VisitObjCAtCatchStmt(cast
<ObjCAtCatchStmt
>(S
));
2354 case Stmt::ObjCAutoreleasePoolStmtClass
:
2355 return VisitObjCAutoreleasePoolStmt(cast
<ObjCAutoreleasePoolStmt
>(S
));
2357 case Stmt::ObjCAtSynchronizedStmtClass
:
2358 return VisitObjCAtSynchronizedStmt(cast
<ObjCAtSynchronizedStmt
>(S
));
2360 case Stmt::ObjCAtThrowStmtClass
:
2361 return VisitObjCAtThrowStmt(cast
<ObjCAtThrowStmt
>(S
));
2363 case Stmt::ObjCAtTryStmtClass
:
2364 return VisitObjCAtTryStmt(cast
<ObjCAtTryStmt
>(S
));
2366 case Stmt::ObjCForCollectionStmtClass
:
2367 return VisitObjCForCollectionStmt(cast
<ObjCForCollectionStmt
>(S
));
2369 case Stmt::ObjCMessageExprClass
:
2370 return VisitObjCMessageExpr(cast
<ObjCMessageExpr
>(S
), asc
);
2372 case Stmt::OpaqueValueExprClass
:
2375 case Stmt::PseudoObjectExprClass
:
2376 return VisitPseudoObjectExpr(cast
<PseudoObjectExpr
>(S
));
2378 case Stmt::ReturnStmtClass
:
2379 case Stmt::CoreturnStmtClass
:
2380 return VisitReturnStmt(S
);
2382 case Stmt::CoyieldExprClass
:
2383 case Stmt::CoawaitExprClass
:
2384 return VisitCoroutineSuspendExpr(cast
<CoroutineSuspendExpr
>(S
), asc
);
2386 case Stmt::SEHExceptStmtClass
:
2387 return VisitSEHExceptStmt(cast
<SEHExceptStmt
>(S
));
2389 case Stmt::SEHFinallyStmtClass
:
2390 return VisitSEHFinallyStmt(cast
<SEHFinallyStmt
>(S
));
2392 case Stmt::SEHLeaveStmtClass
:
2393 return VisitSEHLeaveStmt(cast
<SEHLeaveStmt
>(S
));
2395 case Stmt::SEHTryStmtClass
:
2396 return VisitSEHTryStmt(cast
<SEHTryStmt
>(S
));
2398 case Stmt::UnaryExprOrTypeTraitExprClass
:
2399 return VisitUnaryExprOrTypeTraitExpr(cast
<UnaryExprOrTypeTraitExpr
>(S
),
2402 case Stmt::StmtExprClass
:
2403 return VisitStmtExpr(cast
<StmtExpr
>(S
), asc
);
2405 case Stmt::SwitchStmtClass
:
2406 return VisitSwitchStmt(cast
<SwitchStmt
>(S
));
2408 case Stmt::UnaryOperatorClass
:
2409 return VisitUnaryOperator(cast
<UnaryOperator
>(S
), asc
);
2411 case Stmt::WhileStmtClass
:
2412 return VisitWhileStmt(cast
<WhileStmt
>(S
));
2414 case Stmt::ArrayInitLoopExprClass
:
2415 return VisitArrayInitLoopExpr(cast
<ArrayInitLoopExpr
>(S
), asc
);
2419 CFGBlock
*CFGBuilder::VisitStmt(Stmt
*S
, AddStmtChoice asc
) {
2420 if (asc
.alwaysAdd(*this, S
)) {
2422 appendStmt(Block
, S
);
2425 return VisitChildren(S
);
2428 /// VisitChildren - Visit the children of a Stmt.
2429 CFGBlock
*CFGBuilder::VisitChildren(Stmt
*S
) {
2430 CFGBlock
*B
= Block
;
2432 // Visit the children in their reverse order so that they appear in
2433 // left-to-right (natural) order in the CFG.
2434 reverse_children
RChildren(S
);
2435 for (Stmt
*Child
: RChildren
) {
2437 if (CFGBlock
*R
= Visit(Child
))
2443 CFGBlock
*CFGBuilder::VisitInitListExpr(InitListExpr
*ILE
, AddStmtChoice asc
) {
2444 if (asc
.alwaysAdd(*this, ILE
)) {
2446 appendStmt(Block
, ILE
);
2448 CFGBlock
*B
= Block
;
2450 reverse_children
RChildren(ILE
);
2451 for (Stmt
*Child
: RChildren
) {
2454 if (CFGBlock
*R
= Visit(Child
))
2456 if (BuildOpts
.AddCXXDefaultInitExprInAggregates
) {
2457 if (auto *DIE
= dyn_cast
<CXXDefaultInitExpr
>(Child
))
2458 if (Stmt
*Child
= DIE
->getExpr())
2459 if (CFGBlock
*R
= Visit(Child
))
2466 CFGBlock
*CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr
*A
,
2467 AddStmtChoice asc
) {
2468 AddressTakenLabels
.insert(A
->getLabel());
2470 if (asc
.alwaysAdd(*this, A
)) {
2472 appendStmt(Block
, A
);
2478 static bool isFallthroughStatement(const AttributedStmt
*A
) {
2479 bool isFallthrough
= hasSpecificAttr
<FallThroughAttr
>(A
->getAttrs());
2480 assert((!isFallthrough
|| isa
<NullStmt
>(A
->getSubStmt())) &&
2481 "expected fallthrough not to have children");
2482 return isFallthrough
;
2485 CFGBlock
*CFGBuilder::VisitAttributedStmt(AttributedStmt
*A
,
2486 AddStmtChoice asc
) {
2487 // AttributedStmts for [[likely]] can have arbitrary statements as children,
2488 // and the current visitation order here would add the AttributedStmts
2489 // for [[likely]] after the child nodes, which is undesirable: For example,
2490 // if the child contains an unconditional return, the [[likely]] would be
2491 // considered unreachable.
2492 // So only add the AttributedStmt for FallThrough, which has CFG effects and
2493 // also no children, and omit the others. None of the other current StmtAttrs
2494 // have semantic meaning for the CFG.
2495 if (isFallthroughStatement(A
) && asc
.alwaysAdd(*this, A
)) {
2497 appendStmt(Block
, A
);
2500 return VisitChildren(A
);
2503 CFGBlock
*CFGBuilder::VisitUnaryOperator(UnaryOperator
*U
, AddStmtChoice asc
) {
2504 if (asc
.alwaysAdd(*this, U
)) {
2506 appendStmt(Block
, U
);
2509 if (U
->getOpcode() == UO_LNot
)
2510 tryEvaluateBool(U
->getSubExpr()->IgnoreParens());
2512 return Visit(U
->getSubExpr(), AddStmtChoice());
2515 CFGBlock
*CFGBuilder::VisitLogicalOperator(BinaryOperator
*B
) {
2516 CFGBlock
*ConfluenceBlock
= Block
? Block
: createBlock();
2517 appendStmt(ConfluenceBlock
, B
);
2522 return VisitLogicalOperator(B
, nullptr, ConfluenceBlock
,
2523 ConfluenceBlock
).first
;
2526 std::pair
<CFGBlock
*, CFGBlock
*>
2527 CFGBuilder::VisitLogicalOperator(BinaryOperator
*B
,
2529 CFGBlock
*TrueBlock
,
2530 CFGBlock
*FalseBlock
) {
2531 // Introspect the RHS. If it is a nested logical operation, we recursively
2532 // build the CFG using this function. Otherwise, resort to default
2533 // CFG construction behavior.
2534 Expr
*RHS
= B
->getRHS()->IgnoreParens();
2535 CFGBlock
*RHSBlock
, *ExitBlock
;
2538 if (BinaryOperator
*B_RHS
= dyn_cast
<BinaryOperator
>(RHS
))
2539 if (B_RHS
->isLogicalOp()) {
2540 std::tie(RHSBlock
, ExitBlock
) =
2541 VisitLogicalOperator(B_RHS
, Term
, TrueBlock
, FalseBlock
);
2545 // The RHS is not a nested logical operation. Don't push the terminator
2546 // down further, but instead visit RHS and construct the respective
2547 // pieces of the CFG, and link up the RHSBlock with the terminator
2548 // we have been provided.
2549 ExitBlock
= RHSBlock
= createBlock(false);
2551 // Even though KnownVal is only used in the else branch of the next
2552 // conditional, tryEvaluateBool performs additional checking on the
2553 // Expr, so it should be called unconditionally.
2554 TryResult KnownVal
= tryEvaluateBool(RHS
);
2555 if (!KnownVal
.isKnown())
2556 KnownVal
= tryEvaluateBool(B
);
2559 assert(TrueBlock
== FalseBlock
);
2560 addSuccessor(RHSBlock
, TrueBlock
);
2563 RHSBlock
->setTerminator(Term
);
2564 addSuccessor(RHSBlock
, TrueBlock
, !KnownVal
.isFalse());
2565 addSuccessor(RHSBlock
, FalseBlock
, !KnownVal
.isTrue());
2569 RHSBlock
= addStmt(RHS
);
2574 return std::make_pair(nullptr, nullptr);
2576 // Generate the blocks for evaluating the LHS.
2577 Expr
*LHS
= B
->getLHS()->IgnoreParens();
2579 if (BinaryOperator
*B_LHS
= dyn_cast
<BinaryOperator
>(LHS
))
2580 if (B_LHS
->isLogicalOp()) {
2581 if (B
->getOpcode() == BO_LOr
)
2582 FalseBlock
= RHSBlock
;
2584 TrueBlock
= RHSBlock
;
2586 // For the LHS, treat 'B' as the terminator that we want to sink
2587 // into the nested branch. The RHS always gets the top-most
2589 return VisitLogicalOperator(B_LHS
, B
, TrueBlock
, FalseBlock
);
2592 // Create the block evaluating the LHS.
2593 // This contains the '&&' or '||' as the terminator.
2594 CFGBlock
*LHSBlock
= createBlock(false);
2595 LHSBlock
->setTerminator(B
);
2598 CFGBlock
*EntryLHSBlock
= addStmt(LHS
);
2601 return std::make_pair(nullptr, nullptr);
2603 // See if this is a known constant.
2604 TryResult KnownVal
= tryEvaluateBool(LHS
);
2606 // Now link the LHSBlock with RHSBlock.
2607 if (B
->getOpcode() == BO_LOr
) {
2608 addSuccessor(LHSBlock
, TrueBlock
, !KnownVal
.isFalse());
2609 addSuccessor(LHSBlock
, RHSBlock
, !KnownVal
.isTrue());
2611 assert(B
->getOpcode() == BO_LAnd
);
2612 addSuccessor(LHSBlock
, RHSBlock
, !KnownVal
.isFalse());
2613 addSuccessor(LHSBlock
, FalseBlock
, !KnownVal
.isTrue());
2616 return std::make_pair(EntryLHSBlock
, ExitBlock
);
2619 CFGBlock
*CFGBuilder::VisitBinaryOperator(BinaryOperator
*B
,
2620 AddStmtChoice asc
) {
2622 if (B
->isLogicalOp())
2623 return VisitLogicalOperator(B
);
2625 if (B
->getOpcode() == BO_Comma
) { // ,
2627 appendStmt(Block
, B
);
2628 addStmt(B
->getRHS());
2629 return addStmt(B
->getLHS());
2632 if (B
->isAssignmentOp()) {
2633 if (asc
.alwaysAdd(*this, B
)) {
2635 appendStmt(Block
, B
);
2638 return Visit(B
->getRHS());
2641 if (asc
.alwaysAdd(*this, B
)) {
2643 appendStmt(Block
, B
);
2646 if (B
->isEqualityOp() || B
->isRelationalOp())
2649 CFGBlock
*RBlock
= Visit(B
->getRHS());
2650 CFGBlock
*LBlock
= Visit(B
->getLHS());
2651 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2652 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2653 // return RBlock. Otherwise we'll incorrectly return NULL.
2654 return (LBlock
? LBlock
: RBlock
);
2657 CFGBlock
*CFGBuilder::VisitNoRecurse(Expr
*E
, AddStmtChoice asc
) {
2658 if (asc
.alwaysAdd(*this, E
)) {
2660 appendStmt(Block
, E
);
2665 CFGBlock
*CFGBuilder::VisitBreakStmt(BreakStmt
*B
) {
2666 // "break" is a control-flow statement. Thus we stop processing the current
2671 // Now create a new block that ends with the break statement.
2672 Block
= createBlock(false);
2673 Block
->setTerminator(B
);
2675 // If there is no target for the break, then we are looking at an incomplete
2676 // AST. This means that the CFG cannot be constructed.
2677 if (BreakJumpTarget
.block
) {
2678 addAutomaticObjHandling(ScopePos
, BreakJumpTarget
.scopePosition
, B
);
2679 addSuccessor(Block
, BreakJumpTarget
.block
);
2686 static bool CanThrow(Expr
*E
, ASTContext
&Ctx
) {
2687 QualType Ty
= E
->getType();
2688 if (Ty
->isFunctionPointerType() || Ty
->isBlockPointerType())
2689 Ty
= Ty
->getPointeeType();
2691 const FunctionType
*FT
= Ty
->getAs
<FunctionType
>();
2693 if (const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FT
))
2694 if (!isUnresolvedExceptionSpec(Proto
->getExceptionSpecType()) &&
2701 CFGBlock
*CFGBuilder::VisitCallExpr(CallExpr
*C
, AddStmtChoice asc
) {
2702 // Compute the callee type.
2703 QualType calleeType
= C
->getCallee()->getType();
2704 if (calleeType
== Context
->BoundMemberTy
) {
2705 QualType boundType
= Expr::findBoundMemberType(C
->getCallee());
2707 // We should only get a null bound type if processing a dependent
2708 // CFG. Recover by assuming nothing.
2709 if (!boundType
.isNull()) calleeType
= boundType
;
2712 // If this is a call to a no-return function, this stops the block here.
2713 bool NoReturn
= getFunctionExtInfo(*calleeType
).getNoReturn();
2715 bool AddEHEdge
= false;
2717 // Languages without exceptions are assumed to not throw.
2718 if (Context
->getLangOpts().Exceptions
) {
2719 if (BuildOpts
.AddEHEdges
)
2723 // If this is a call to a builtin function, it might not actually evaluate
2724 // its arguments. Don't add them to the CFG if this is the case.
2725 bool OmitArguments
= false;
2727 if (FunctionDecl
*FD
= C
->getDirectCallee()) {
2728 // TODO: Support construction contexts for variadic function arguments.
2729 // These are a bit problematic and not very useful because passing
2730 // C++ objects as C-style variadic arguments doesn't work in general
2731 // (see [expr.call]).
2732 if (!FD
->isVariadic())
2733 findConstructionContextsForArguments(C
);
2735 if (FD
->isNoReturn() || C
->isBuiltinAssumeFalse(*Context
))
2737 if (FD
->hasAttr
<NoThrowAttr
>())
2739 if (FD
->getBuiltinID() == Builtin::BI__builtin_object_size
||
2740 FD
->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size
)
2741 OmitArguments
= true;
2744 if (!CanThrow(C
->getCallee(), *Context
))
2747 if (OmitArguments
) {
2748 assert(!NoReturn
&& "noreturn calls with unevaluated args not implemented");
2749 assert(!AddEHEdge
&& "EH calls with unevaluated args not implemented");
2751 appendStmt(Block
, C
);
2752 return Visit(C
->getCallee());
2755 if (!NoReturn
&& !AddEHEdge
) {
2757 appendCall(Block
, C
);
2759 return VisitChildren(C
);
2769 Block
= createNoReturnBlock();
2771 Block
= createBlock();
2773 appendCall(Block
, C
);
2776 // Add exceptional edges.
2777 if (TryTerminatedBlock
)
2778 addSuccessor(Block
, TryTerminatedBlock
);
2780 addSuccessor(Block
, &cfg
->getExit());
2783 return VisitChildren(C
);
2786 CFGBlock
*CFGBuilder::VisitChooseExpr(ChooseExpr
*C
,
2787 AddStmtChoice asc
) {
2788 CFGBlock
*ConfluenceBlock
= Block
? Block
: createBlock();
2789 appendStmt(ConfluenceBlock
, C
);
2793 AddStmtChoice alwaysAdd
= asc
.withAlwaysAdd(true);
2794 Succ
= ConfluenceBlock
;
2796 CFGBlock
*LHSBlock
= Visit(C
->getLHS(), alwaysAdd
);
2800 Succ
= ConfluenceBlock
;
2802 CFGBlock
*RHSBlock
= Visit(C
->getRHS(), alwaysAdd
);
2806 Block
= createBlock(false);
2807 // See if this is a known constant.
2808 const TryResult
& KnownVal
= tryEvaluateBool(C
->getCond());
2809 addSuccessor(Block
, KnownVal
.isFalse() ? nullptr : LHSBlock
);
2810 addSuccessor(Block
, KnownVal
.isTrue() ? nullptr : RHSBlock
);
2811 Block
->setTerminator(C
);
2812 return addStmt(C
->getCond());
2815 CFGBlock
*CFGBuilder::VisitCompoundStmt(CompoundStmt
*C
,
2816 bool ExternallyDestructed
) {
2817 LocalScope::const_iterator scopeBeginPos
= ScopePos
;
2818 addLocalScopeForStmt(C
);
2820 if (!C
->body_empty() && !isa
<ReturnStmt
>(*C
->body_rbegin())) {
2821 // If the body ends with a ReturnStmt, the dtors will be added in
2823 addAutomaticObjHandling(ScopePos
, scopeBeginPos
, C
);
2826 CFGBlock
*LastBlock
= Block
;
2828 for (Stmt
*S
: llvm::reverse(C
->body())) {
2829 // If we hit a segment of code just containing ';' (NullStmts), we can
2830 // get a null block back. In such cases, just use the LastBlock
2831 CFGBlock
*newBlock
= Visit(S
, AddStmtChoice::AlwaysAdd
,
2832 ExternallyDestructed
);
2835 LastBlock
= newBlock
;
2840 ExternallyDestructed
= false;
2846 CFGBlock
*CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator
*C
,
2847 AddStmtChoice asc
) {
2848 const BinaryConditionalOperator
*BCO
= dyn_cast
<BinaryConditionalOperator
>(C
);
2849 const OpaqueValueExpr
*opaqueValue
= (BCO
? BCO
->getOpaqueValue() : nullptr);
2851 // Create the confluence block that will "merge" the results of the ternary
2853 CFGBlock
*ConfluenceBlock
= Block
? Block
: createBlock();
2854 appendStmt(ConfluenceBlock
, C
);
2858 AddStmtChoice alwaysAdd
= asc
.withAlwaysAdd(true);
2860 // Create a block for the LHS expression if there is an LHS expression. A
2861 // GCC extension allows LHS to be NULL, causing the condition to be the
2862 // value that is returned instead.
2863 // e.g: x ?: y is shorthand for: x ? x : y;
2864 Succ
= ConfluenceBlock
;
2866 CFGBlock
*LHSBlock
= nullptr;
2867 const Expr
*trueExpr
= C
->getTrueExpr();
2868 if (trueExpr
!= opaqueValue
) {
2869 LHSBlock
= Visit(C
->getTrueExpr(), alwaysAdd
);
2875 LHSBlock
= ConfluenceBlock
;
2877 // Create the block for the RHS expression.
2878 Succ
= ConfluenceBlock
;
2879 CFGBlock
*RHSBlock
= Visit(C
->getFalseExpr(), alwaysAdd
);
2883 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2884 if (BinaryOperator
*Cond
=
2885 dyn_cast
<BinaryOperator
>(C
->getCond()->IgnoreParens()))
2886 if (Cond
->isLogicalOp())
2887 return VisitLogicalOperator(Cond
, C
, LHSBlock
, RHSBlock
).first
;
2889 // Create the block that will contain the condition.
2890 Block
= createBlock(false);
2892 // See if this is a known constant.
2893 const TryResult
& KnownVal
= tryEvaluateBool(C
->getCond());
2894 addSuccessor(Block
, LHSBlock
, !KnownVal
.isFalse());
2895 addSuccessor(Block
, RHSBlock
, !KnownVal
.isTrue());
2896 Block
->setTerminator(C
);
2897 Expr
*condExpr
= C
->getCond();
2900 // Run the condition expression if it's not trivially expressed in
2901 // terms of the opaque value (or if there is no opaque value).
2902 if (condExpr
!= opaqueValue
)
2905 // Before that, run the common subexpression if there was one.
2906 // At least one of this or the above will be run.
2907 return addStmt(BCO
->getCommon());
2910 return addStmt(condExpr
);
2913 CFGBlock
*CFGBuilder::VisitDeclStmt(DeclStmt
*DS
) {
2914 // Check if the Decl is for an __label__. If so, elide it from the
2916 if (isa
<LabelDecl
>(*DS
->decl_begin()))
2919 // This case also handles static_asserts.
2920 if (DS
->isSingleDecl())
2921 return VisitDeclSubExpr(DS
);
2923 CFGBlock
*B
= nullptr;
2925 // Build an individual DeclStmt for each decl.
2926 for (DeclStmt::reverse_decl_iterator I
= DS
->decl_rbegin(),
2927 E
= DS
->decl_rend();
2930 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2931 // automatically freed with the CFG.
2932 DeclGroupRef
DG(*I
);
2934 DeclStmt
*DSNew
= new (Context
) DeclStmt(DG
, D
->getLocation(), GetEndLoc(D
));
2935 cfg
->addSyntheticDeclStmt(DSNew
, DS
);
2937 // Append the fake DeclStmt to block.
2938 B
= VisitDeclSubExpr(DSNew
);
2944 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2945 /// DeclStmts and initializers in them.
2946 CFGBlock
*CFGBuilder::VisitDeclSubExpr(DeclStmt
*DS
) {
2947 assert(DS
->isSingleDecl() && "Can handle single declarations only.");
2949 if (const auto *TND
= dyn_cast
<TypedefNameDecl
>(DS
->getSingleDecl())) {
2950 // If we encounter a VLA, process its size expressions.
2951 const Type
*T
= TND
->getUnderlyingType().getTypePtr();
2952 if (!T
->isVariablyModifiedType())
2956 appendStmt(Block
, DS
);
2958 CFGBlock
*LastBlock
= Block
;
2959 for (const VariableArrayType
*VA
= FindVA(T
); VA
!= nullptr;
2960 VA
= FindVA(VA
->getElementType().getTypePtr())) {
2961 if (CFGBlock
*NewBlock
= addStmt(VA
->getSizeExpr()))
2962 LastBlock
= NewBlock
;
2967 VarDecl
*VD
= dyn_cast
<VarDecl
>(DS
->getSingleDecl());
2970 // Of everything that can be declared in a DeclStmt, only VarDecls and the
2971 // exceptions above impact runtime semantics.
2975 bool HasTemporaries
= false;
2977 // Guard static initializers under a branch.
2978 CFGBlock
*blockAfterStaticInit
= nullptr;
2980 if (BuildOpts
.AddStaticInitBranches
&& VD
->isStaticLocal()) {
2981 // For static variables, we need to create a branch to track
2982 // whether or not they are initialized.
2989 blockAfterStaticInit
= Succ
;
2992 // Destructors of temporaries in initialization expression should be called
2993 // after initialization finishes.
2994 Expr
*Init
= VD
->getInit();
2996 HasTemporaries
= isa
<ExprWithCleanups
>(Init
);
2998 if (BuildOpts
.AddTemporaryDtors
&& HasTemporaries
) {
2999 // Generate destructors for temporaries in initialization expression.
3000 TempDtorContext Context
;
3001 VisitForTemporaryDtors(cast
<ExprWithCleanups
>(Init
)->getSubExpr(),
3002 /*ExternallyDestructed=*/true, Context
);
3006 // If we bind to a tuple-like type, we iterate over the HoldingVars, and
3007 // create a DeclStmt for each of them.
3008 if (const auto *DD
= dyn_cast
<DecompositionDecl
>(VD
)) {
3009 for (auto *BD
: llvm::reverse(DD
->bindings())) {
3010 if (auto *VD
= BD
->getHoldingVar()) {
3011 DeclGroupRef
DG(VD
);
3013 new (Context
) DeclStmt(DG
, VD
->getLocation(), GetEndLoc(VD
));
3014 cfg
->addSyntheticDeclStmt(DSNew
, DS
);
3015 Block
= VisitDeclSubExpr(DSNew
);
3021 appendStmt(Block
, DS
);
3023 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3024 // initializer, that's used for each element.
3025 const auto *AILE
= dyn_cast_or_null
<ArrayInitLoopExpr
>(Init
);
3027 findConstructionContexts(
3028 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), DS
),
3029 AILE
? AILE
->getSubExpr() : Init
);
3031 // Keep track of the last non-null block, as 'Block' can be nulled out
3032 // if the initializer expression is something like a 'while' in a
3033 // statement-expression.
3034 CFGBlock
*LastBlock
= Block
;
3037 if (HasTemporaries
) {
3038 // For expression with temporaries go directly to subexpression to omit
3039 // generating destructors for the second time.
3040 ExprWithCleanups
*EC
= cast
<ExprWithCleanups
>(Init
);
3041 if (CFGBlock
*newBlock
= Visit(EC
->getSubExpr()))
3042 LastBlock
= newBlock
;
3045 if (CFGBlock
*newBlock
= Visit(Init
))
3046 LastBlock
= newBlock
;
3050 // If the type of VD is a VLA, then we must process its size expressions.
3051 // FIXME: This does not find the VLA if it is embedded in other types,
3052 // like here: `int (*p_vla)[x];`
3053 for (const VariableArrayType
* VA
= FindVA(VD
->getType().getTypePtr());
3054 VA
!= nullptr; VA
= FindVA(VA
->getElementType().getTypePtr())) {
3055 if (CFGBlock
*newBlock
= addStmt(VA
->getSizeExpr()))
3056 LastBlock
= newBlock
;
3059 maybeAddScopeBeginForVarDecl(Block
, VD
, DS
);
3061 // Remove variable from local scope.
3062 if (ScopePos
&& VD
== *ScopePos
)
3065 CFGBlock
*B
= LastBlock
;
3066 if (blockAfterStaticInit
) {
3068 Block
= createBlock(false);
3069 Block
->setTerminator(DS
);
3070 addSuccessor(Block
, blockAfterStaticInit
);
3071 addSuccessor(Block
, B
);
3078 CFGBlock
*CFGBuilder::VisitIfStmt(IfStmt
*I
) {
3079 // We may see an if statement in the middle of a basic block, or it may be the
3080 // first statement we are processing. In either case, we create a new basic
3081 // block. First, we create the blocks for the then...else statements, and
3082 // then we create the block containing the if statement. If we were in the
3083 // middle of a block, we stop processing that block. That block is then the
3084 // implicit successor for the "then" and "else" clauses.
3086 // Save local scope position because in case of condition variable ScopePos
3087 // won't be restored when traversing AST.
3088 SaveAndRestore
save_scope_pos(ScopePos
);
3090 // Create local scope for C++17 if init-stmt if one exists.
3091 if (Stmt
*Init
= I
->getInit())
3092 addLocalScopeForStmt(Init
);
3094 // Create local scope for possible condition variable.
3095 // Store scope position. Add implicit destructor.
3096 if (VarDecl
*VD
= I
->getConditionVariable())
3097 addLocalScopeForVarDecl(VD
);
3099 addAutomaticObjHandling(ScopePos
, save_scope_pos
.get(), I
);
3101 // The block we were processing is now finished. Make it the successor
3109 // Process the false branch.
3110 CFGBlock
*ElseBlock
= Succ
;
3112 if (Stmt
*Else
= I
->getElse()) {
3113 SaveAndRestore
sv(Succ
);
3115 // NULL out Block so that the recursive call to Visit will
3116 // create a new basic block.
3119 // If branch is not a compound statement create implicit scope
3120 // and add destructors.
3121 if (!isa
<CompoundStmt
>(Else
))
3122 addLocalScopeAndDtors(Else
);
3124 ElseBlock
= addStmt(Else
);
3126 if (!ElseBlock
) // Can occur when the Else body has all NullStmts.
3127 ElseBlock
= sv
.get();
3134 // Process the true branch.
3135 CFGBlock
*ThenBlock
;
3137 Stmt
*Then
= I
->getThen();
3139 SaveAndRestore
sv(Succ
);
3142 // If branch is not a compound statement create implicit scope
3143 // and add destructors.
3144 if (!isa
<CompoundStmt
>(Then
))
3145 addLocalScopeAndDtors(Then
);
3147 ThenBlock
= addStmt(Then
);
3150 // We can reach here if the "then" body has all NullStmts.
3151 // Create an empty block so we can distinguish between true and false
3152 // branches in path-sensitive analyses.
3153 ThenBlock
= createBlock(false);
3154 addSuccessor(ThenBlock
, sv
.get());
3161 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
3162 // having these handle the actual control-flow jump. Note that
3163 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
3164 // we resort to the old control-flow behavior. This special handling
3165 // removes infeasible paths from the control-flow graph by having the
3166 // control-flow transfer of '&&' or '||' go directly into the then/else
3168 BinaryOperator
*Cond
=
3169 (I
->isConsteval() || I
->getConditionVariable())
3171 : dyn_cast
<BinaryOperator
>(I
->getCond()->IgnoreParens());
3172 CFGBlock
*LastBlock
;
3173 if (Cond
&& Cond
->isLogicalOp())
3174 LastBlock
= VisitLogicalOperator(Cond
, I
, ThenBlock
, ElseBlock
).first
;
3176 // Now create a new block containing the if statement.
3177 Block
= createBlock(false);
3179 // Set the terminator of the new block to the If statement.
3180 Block
->setTerminator(I
);
3182 // See if this is a known constant.
3184 if (!I
->isConsteval())
3185 KnownVal
= tryEvaluateBool(I
->getCond());
3187 // Add the successors. If we know that specific branches are
3188 // unreachable, inform addSuccessor() of that knowledge.
3189 addSuccessor(Block
, ThenBlock
, /* IsReachable = */ !KnownVal
.isFalse());
3190 addSuccessor(Block
, ElseBlock
, /* IsReachable = */ !KnownVal
.isTrue());
3192 if (I
->isConsteval())
3195 // Add the condition as the last statement in the new block. This may
3196 // create new blocks as the condition may contain control-flow. Any newly
3197 // created blocks will be pointed to be "Block".
3198 LastBlock
= addStmt(I
->getCond());
3200 // If the IfStmt contains a condition variable, add it and its
3201 // initializer to the CFG.
3202 if (const DeclStmt
* DS
= I
->getConditionVariableDeclStmt()) {
3204 LastBlock
= addStmt(const_cast<DeclStmt
*>(DS
));
3208 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3209 if (Stmt
*Init
= I
->getInit()) {
3211 LastBlock
= addStmt(Init
);
3217 CFGBlock
*CFGBuilder::VisitReturnStmt(Stmt
*S
) {
3218 // If we were in the middle of a block we stop processing that block.
3220 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3221 // means that the code afterwards is DEAD (unreachable). We still keep
3222 // a basic block for that code; a simple "mark-and-sweep" from the entry
3223 // block will be able to report such dead blocks.
3224 assert(isa
<ReturnStmt
>(S
) || isa
<CoreturnStmt
>(S
));
3226 // Create the new block.
3227 Block
= createBlock(false);
3229 addAutomaticObjHandling(ScopePos
, LocalScope::const_iterator(), S
);
3231 if (auto *R
= dyn_cast
<ReturnStmt
>(S
))
3232 findConstructionContexts(
3233 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), R
),
3236 // If the one of the destructors does not return, we already have the Exit
3237 // block as a successor.
3238 if (!Block
->hasNoReturnElement())
3239 addSuccessor(Block
, &cfg
->getExit());
3241 // Add the return statement to the block.
3242 appendStmt(Block
, S
);
3245 if (ReturnStmt
*RS
= dyn_cast
<ReturnStmt
>(S
)) {
3246 if (Expr
*O
= RS
->getRetValue())
3247 return Visit(O
, AddStmtChoice::AlwaysAdd
, /*ExternallyDestructed=*/true);
3251 CoreturnStmt
*CRS
= cast
<CoreturnStmt
>(S
);
3253 if (CFGBlock
*R
= Visit(CRS
->getPromiseCall()))
3256 if (Expr
*RV
= CRS
->getOperand())
3257 if (RV
->getType()->isVoidType() && !isa
<InitListExpr
>(RV
))
3258 // A non-initlist void expression.
3259 if (CFGBlock
*R
= Visit(RV
))
3265 CFGBlock
*CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr
*E
,
3266 AddStmtChoice asc
) {
3267 // We're modelling the pre-coro-xform CFG. Thus just evalate the various
3268 // active components of the co_await or co_yield. Note we do not model the
3269 // edge from the builtin_suspend to the exit node.
3270 if (asc
.alwaysAdd(*this, E
)) {
3272 appendStmt(Block
, E
);
3274 CFGBlock
*B
= Block
;
3275 if (auto *R
= Visit(E
->getResumeExpr()))
3277 if (auto *R
= Visit(E
->getSuspendExpr()))
3279 if (auto *R
= Visit(E
->getReadyExpr()))
3281 if (auto *R
= Visit(E
->getCommonExpr()))
3286 CFGBlock
*CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt
*ES
) {
3287 // SEHExceptStmt are treated like labels, so they are the first statement in a
3290 // Save local scope position because in case of exception variable ScopePos
3291 // won't be restored when traversing AST.
3292 SaveAndRestore
save_scope_pos(ScopePos
);
3294 addStmt(ES
->getBlock());
3295 CFGBlock
*SEHExceptBlock
= Block
;
3296 if (!SEHExceptBlock
)
3297 SEHExceptBlock
= createBlock();
3299 appendStmt(SEHExceptBlock
, ES
);
3301 // Also add the SEHExceptBlock as a label, like with regular labels.
3302 SEHExceptBlock
->setLabel(ES
);
3304 // Bail out if the CFG is bad.
3308 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3311 return SEHExceptBlock
;
3314 CFGBlock
*CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt
*FS
) {
3315 return VisitCompoundStmt(FS
->getBlock(), /*ExternallyDestructed=*/false);
3318 CFGBlock
*CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt
*LS
) {
3319 // "__leave" is a control-flow statement. Thus we stop processing the current
3324 // Now create a new block that ends with the __leave statement.
3325 Block
= createBlock(false);
3326 Block
->setTerminator(LS
);
3328 // If there is no target for the __leave, then we are looking at an incomplete
3329 // AST. This means that the CFG cannot be constructed.
3330 if (SEHLeaveJumpTarget
.block
) {
3331 addAutomaticObjHandling(ScopePos
, SEHLeaveJumpTarget
.scopePosition
, LS
);
3332 addSuccessor(Block
, SEHLeaveJumpTarget
.block
);
3339 CFGBlock
*CFGBuilder::VisitSEHTryStmt(SEHTryStmt
*Terminator
) {
3340 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3341 // processing the current block.
3342 CFGBlock
*SEHTrySuccessor
= nullptr;
3347 SEHTrySuccessor
= Block
;
3348 } else SEHTrySuccessor
= Succ
;
3350 // FIXME: Implement __finally support.
3351 if (Terminator
->getFinallyHandler())
3354 CFGBlock
*PrevSEHTryTerminatedBlock
= TryTerminatedBlock
;
3356 // Create a new block that will contain the __try statement.
3357 CFGBlock
*NewTryTerminatedBlock
= createBlock(false);
3359 // Add the terminator in the __try block.
3360 NewTryTerminatedBlock
->setTerminator(Terminator
);
3362 if (SEHExceptStmt
*Except
= Terminator
->getExceptHandler()) {
3363 // The code after the try is the implicit successor if there's an __except.
3364 Succ
= SEHTrySuccessor
;
3366 CFGBlock
*ExceptBlock
= VisitSEHExceptStmt(Except
);
3369 // Add this block to the list of successors for the block with the try
3371 addSuccessor(NewTryTerminatedBlock
, ExceptBlock
);
3373 if (PrevSEHTryTerminatedBlock
)
3374 addSuccessor(NewTryTerminatedBlock
, PrevSEHTryTerminatedBlock
);
3376 addSuccessor(NewTryTerminatedBlock
, &cfg
->getExit());
3378 // The code after the try is the implicit successor.
3379 Succ
= SEHTrySuccessor
;
3381 // Save the current "__try" context.
3382 SaveAndRestore
SaveTry(TryTerminatedBlock
, NewTryTerminatedBlock
);
3383 cfg
->addTryDispatchBlock(TryTerminatedBlock
);
3385 // Save the current value for the __leave target.
3386 // All __leaves should go to the code following the __try
3387 // (FIXME: or if the __try has a __finally, to the __finally.)
3388 SaveAndRestore
save_break(SEHLeaveJumpTarget
);
3389 SEHLeaveJumpTarget
= JumpTarget(SEHTrySuccessor
, ScopePos
);
3391 assert(Terminator
->getTryBlock() && "__try must contain a non-NULL body");
3393 return addStmt(Terminator
->getTryBlock());
3396 CFGBlock
*CFGBuilder::VisitLabelStmt(LabelStmt
*L
) {
3397 // Get the block of the labeled statement. Add it to our map.
3398 addStmt(L
->getSubStmt());
3399 CFGBlock
*LabelBlock
= Block
;
3401 if (!LabelBlock
) // This can happen when the body is empty, i.e.
3402 LabelBlock
= createBlock(); // scopes that only contains NullStmts.
3404 assert(!LabelMap
.contains(L
->getDecl()) && "label already in map");
3405 LabelMap
[L
->getDecl()] = JumpTarget(LabelBlock
, ScopePos
);
3407 // Labels partition blocks, so this is the end of the basic block we were
3408 // processing (L is the block's label). Because this is label (and we have
3409 // already processed the substatement) there is no extra control-flow to worry
3411 LabelBlock
->setLabel(L
);
3415 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3418 // This block is now the implicit successor of other blocks.
3424 CFGBlock
*CFGBuilder::VisitBlockExpr(BlockExpr
*E
, AddStmtChoice asc
) {
3425 CFGBlock
*LastBlock
= VisitNoRecurse(E
, asc
);
3426 for (const BlockDecl::Capture
&CI
: E
->getBlockDecl()->captures()) {
3427 if (Expr
*CopyExpr
= CI
.getCopyExpr()) {
3428 CFGBlock
*Tmp
= Visit(CopyExpr
);
3436 CFGBlock
*CFGBuilder::VisitLambdaExpr(LambdaExpr
*E
, AddStmtChoice asc
) {
3437 CFGBlock
*LastBlock
= VisitNoRecurse(E
, asc
);
3440 for (LambdaExpr::capture_init_iterator it
= E
->capture_init_begin(),
3441 et
= E
->capture_init_end();
3442 it
!= et
; ++it
, ++Idx
) {
3443 if (Expr
*Init
= *it
) {
3444 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3445 // initializer, that's used for each element.
3446 auto *AILEInit
= extractElementInitializerFromNestedAILE(
3447 dyn_cast
<ArrayInitLoopExpr
>(Init
));
3449 findConstructionContexts(ConstructionContextLayer::create(
3450 cfg
->getBumpVectorContext(), {E
, Idx
}),
3451 AILEInit
? AILEInit
: Init
);
3453 CFGBlock
*Tmp
= Visit(Init
);
3461 CFGBlock
*CFGBuilder::VisitGotoStmt(GotoStmt
*G
) {
3462 // Goto is a control-flow statement. Thus we stop processing the current
3463 // block and create a new one.
3465 Block
= createBlock(false);
3466 Block
->setTerminator(G
);
3468 // If we already know the mapping to the label block add the successor now.
3469 LabelMapTy::iterator I
= LabelMap
.find(G
->getLabel());
3471 if (I
== LabelMap
.end())
3472 // We will need to backpatch this block later.
3473 BackpatchBlocks
.push_back(JumpSource(Block
, ScopePos
));
3475 JumpTarget JT
= I
->second
;
3476 addSuccessor(Block
, JT
.block
);
3477 addScopeChangesHandling(ScopePos
, JT
.scopePosition
, G
);
3483 CFGBlock
*CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt
*G
, AddStmtChoice asc
) {
3484 // Goto is a control-flow statement. Thus we stop processing the current
3485 // block and create a new one.
3487 if (!G
->isAsmGoto())
3488 return VisitStmt(G
, asc
);
3495 Block
= createBlock();
3496 Block
->setTerminator(G
);
3497 // We will backpatch this block later for all the labels.
3498 BackpatchBlocks
.push_back(JumpSource(Block
, ScopePos
));
3499 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3500 // used to avoid adding "Succ" again.
3501 BackpatchBlocks
.push_back(JumpSource(Succ
, ScopePos
));
3502 return VisitChildren(G
);
3505 CFGBlock
*CFGBuilder::VisitForStmt(ForStmt
*F
) {
3506 CFGBlock
*LoopSuccessor
= nullptr;
3508 // Save local scope position because in case of condition variable ScopePos
3509 // won't be restored when traversing AST.
3510 SaveAndRestore
save_scope_pos(ScopePos
);
3512 // Create local scope for init statement and possible condition variable.
3513 // Add destructor for init statement and condition variable.
3514 // Store scope position for continue statement.
3515 if (Stmt
*Init
= F
->getInit())
3516 addLocalScopeForStmt(Init
);
3517 LocalScope::const_iterator LoopBeginScopePos
= ScopePos
;
3519 if (VarDecl
*VD
= F
->getConditionVariable())
3520 addLocalScopeForVarDecl(VD
);
3521 LocalScope::const_iterator ContinueScopePos
= ScopePos
;
3523 addAutomaticObjHandling(ScopePos
, save_scope_pos
.get(), F
);
3527 // "for" is a control-flow statement. Thus we stop processing the current
3532 LoopSuccessor
= Block
;
3534 LoopSuccessor
= Succ
;
3536 // Save the current value for the break targets.
3537 // All breaks should go to the code following the loop.
3538 SaveAndRestore
save_break(BreakJumpTarget
);
3539 BreakJumpTarget
= JumpTarget(LoopSuccessor
, ScopePos
);
3541 CFGBlock
*BodyBlock
= nullptr, *TransitionBlock
= nullptr;
3543 // Now create the loop body.
3545 assert(F
->getBody());
3547 // Save the current values for Block, Succ, continue and break targets.
3548 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
3549 SaveAndRestore
save_continue(ContinueJumpTarget
);
3551 // Create an empty block to represent the transition block for looping back
3552 // to the head of the loop. If we have increment code, it will
3553 // go in this block as well.
3554 Block
= Succ
= TransitionBlock
= createBlock(false);
3555 TransitionBlock
->setLoopTarget(F
);
3558 // Loop iteration (after increment) should end with destructor of Condition
3559 // variable (if any).
3560 addAutomaticObjHandling(ScopePos
, LoopBeginScopePos
, F
);
3562 if (Stmt
*I
= F
->getInc()) {
3563 // Generate increment code in its own basic block. This is the target of
3564 // continue statements.
3568 // Finish up the increment (or empty) block if it hasn't been already.
3570 assert(Block
== Succ
);
3576 // The starting block for the loop increment is the block that should
3577 // represent the 'loop target' for looping back to the start of the loop.
3578 ContinueJumpTarget
= JumpTarget(Succ
, ContinueScopePos
);
3579 ContinueJumpTarget
.block
->setLoopTarget(F
);
3582 // If body is not a compound statement create implicit scope
3583 // and add destructors.
3584 if (!isa
<CompoundStmt
>(F
->getBody()))
3585 addLocalScopeAndDtors(F
->getBody());
3587 // Now populate the body block, and in the process create new blocks as we
3588 // walk the body of the loop.
3589 BodyBlock
= addStmt(F
->getBody());
3592 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3593 // Use the continue jump target as the proxy for the body.
3594 BodyBlock
= ContinueJumpTarget
.block
;
3600 // Because of short-circuit evaluation, the condition of the loop can span
3601 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3602 // evaluate the condition.
3603 CFGBlock
*EntryConditionBlock
= nullptr, *ExitConditionBlock
= nullptr;
3606 Expr
*C
= F
->getCond();
3607 SaveAndRestore
save_scope_pos(ScopePos
);
3609 // Specially handle logical operators, which have a slightly
3610 // more optimal CFG representation.
3611 if (BinaryOperator
*Cond
=
3612 dyn_cast_or_null
<BinaryOperator
>(C
? C
->IgnoreParens() : nullptr))
3613 if (Cond
->isLogicalOp()) {
3614 std::tie(EntryConditionBlock
, ExitConditionBlock
) =
3615 VisitLogicalOperator(Cond
, F
, BodyBlock
, LoopSuccessor
);
3619 // The default case when not handling logical operators.
3620 EntryConditionBlock
= ExitConditionBlock
= createBlock(false);
3621 ExitConditionBlock
->setTerminator(F
);
3623 // See if this is a known constant.
3624 TryResult
KnownVal(true);
3627 // Now add the actual condition to the condition block.
3628 // Because the condition itself may contain control-flow, new blocks may
3629 // be created. Thus we update "Succ" after adding the condition.
3630 Block
= ExitConditionBlock
;
3631 EntryConditionBlock
= addStmt(C
);
3633 // If this block contains a condition variable, add both the condition
3634 // variable and initializer to the CFG.
3635 if (VarDecl
*VD
= F
->getConditionVariable()) {
3636 if (Expr
*Init
= VD
->getInit()) {
3638 const DeclStmt
*DS
= F
->getConditionVariableDeclStmt();
3639 assert(DS
->isSingleDecl());
3640 findConstructionContexts(
3641 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), DS
),
3643 appendStmt(Block
, DS
);
3644 EntryConditionBlock
= addStmt(Init
);
3645 assert(Block
== EntryConditionBlock
);
3646 maybeAddScopeBeginForVarDecl(EntryConditionBlock
, VD
, C
);
3650 if (Block
&& badCFG
)
3653 KnownVal
= tryEvaluateBool(C
);
3656 // Add the loop body entry as a successor to the condition.
3657 addSuccessor(ExitConditionBlock
, KnownVal
.isFalse() ? nullptr : BodyBlock
);
3658 // Link up the condition block with the code that follows the loop. (the
3660 addSuccessor(ExitConditionBlock
,
3661 KnownVal
.isTrue() ? nullptr : LoopSuccessor
);
3664 // Link up the loop-back block to the entry condition block.
3665 addSuccessor(TransitionBlock
, EntryConditionBlock
);
3667 // The condition block is the implicit successor for any code above the loop.
3668 Succ
= EntryConditionBlock
;
3670 // If the loop contains initialization, create a new block for those
3671 // statements. This block can also contain statements that precede the loop.
3672 if (Stmt
*I
= F
->getInit()) {
3673 SaveAndRestore
save_scope_pos(ScopePos
);
3674 ScopePos
= LoopBeginScopePos
;
3675 Block
= createBlock();
3679 // There is no loop initialization. We are thus basically a while loop.
3680 // NULL out Block to force lazy block construction.
3682 Succ
= EntryConditionBlock
;
3683 return EntryConditionBlock
;
3687 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr
*MTE
,
3688 AddStmtChoice asc
) {
3689 findConstructionContexts(
3690 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), MTE
),
3693 return VisitStmt(MTE
, asc
);
3696 CFGBlock
*CFGBuilder::VisitMemberExpr(MemberExpr
*M
, AddStmtChoice asc
) {
3697 if (asc
.alwaysAdd(*this, M
)) {
3699 appendStmt(Block
, M
);
3701 return Visit(M
->getBase());
3704 CFGBlock
*CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt
*S
) {
3705 // Objective-C fast enumeration 'for' statements:
3706 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3708 // for ( Type newVariable in collection_expression ) { statements }
3713 // 1. collection_expression
3714 // T. jump to loop_entry
3716 // 1. side-effects of element expression
3717 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3718 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3721 // T. jump to loop_entry
3727 // Type existingItem;
3728 // for ( existingItem in expression ) { statements }
3732 // the same with newVariable replaced with existingItem; the binding works
3733 // the same except that for one ObjCForCollectionStmt::getElement() returns
3734 // a DeclStmt and the other returns a DeclRefExpr.
3736 CFGBlock
*LoopSuccessor
= nullptr;
3741 LoopSuccessor
= Block
;
3744 LoopSuccessor
= Succ
;
3746 // Build the condition blocks.
3747 CFGBlock
*ExitConditionBlock
= createBlock(false);
3749 // Set the terminator for the "exit" condition block.
3750 ExitConditionBlock
->setTerminator(S
);
3752 // The last statement in the block should be the ObjCForCollectionStmt, which
3753 // performs the actual binding to 'element' and determines if there are any
3754 // more items in the collection.
3755 appendStmt(ExitConditionBlock
, S
);
3756 Block
= ExitConditionBlock
;
3758 // Walk the 'element' expression to see if there are any side-effects. We
3759 // generate new blocks as necessary. We DON'T add the statement by default to
3760 // the CFG unless it contains control-flow.
3761 CFGBlock
*EntryConditionBlock
= Visit(S
->getElement(),
3762 AddStmtChoice::NotAlwaysAdd
);
3769 // The condition block is the implicit successor for the loop body as well as
3770 // any code above the loop.
3771 Succ
= EntryConditionBlock
;
3773 // Now create the true branch.
3775 // Save the current values for Succ, continue and break targets.
3776 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
3777 SaveAndRestore
save_continue(ContinueJumpTarget
),
3778 save_break(BreakJumpTarget
);
3780 // Add an intermediate block between the BodyBlock and the
3781 // EntryConditionBlock to represent the "loop back" transition, for looping
3782 // back to the head of the loop.
3783 CFGBlock
*LoopBackBlock
= nullptr;
3784 Succ
= LoopBackBlock
= createBlock();
3785 LoopBackBlock
->setLoopTarget(S
);
3787 BreakJumpTarget
= JumpTarget(LoopSuccessor
, ScopePos
);
3788 ContinueJumpTarget
= JumpTarget(Succ
, ScopePos
);
3790 CFGBlock
*BodyBlock
= addStmt(S
->getBody());
3793 BodyBlock
= ContinueJumpTarget
.block
; // can happen for "for (X in Y) ;"
3799 // This new body block is a successor to our "exit" condition block.
3800 addSuccessor(ExitConditionBlock
, BodyBlock
);
3803 // Link up the condition block with the code that follows the loop.
3804 // (the false branch).
3805 addSuccessor(ExitConditionBlock
, LoopSuccessor
);
3807 // Now create a prologue block to contain the collection expression.
3808 Block
= createBlock();
3809 return addStmt(S
->getCollection());
3812 CFGBlock
*CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt
*S
) {
3814 return addStmt(S
->getSubStmt());
3815 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3818 CFGBlock
*CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt
*S
) {
3819 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3822 CFGBlock
*SyncBlock
= addStmt(S
->getSynchBody());
3824 // The sync body starts its own basic block. This makes it a little easier
3825 // for diagnostic clients.
3834 // Add the @synchronized to the CFG.
3836 appendStmt(Block
, S
);
3838 // Inline the sync expression.
3839 return addStmt(S
->getSynchExpr());
3842 CFGBlock
*CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr
*E
) {
3845 // Add the PseudoObject as the last thing.
3846 appendStmt(Block
, E
);
3848 CFGBlock
*lastBlock
= Block
;
3850 // Before that, evaluate all of the semantics in order. In
3851 // CFG-land, that means appending them in reverse order.
3852 for (unsigned i
= E
->getNumSemanticExprs(); i
!= 0; ) {
3853 Expr
*Semantic
= E
->getSemanticExpr(--i
);
3855 // If the semantic is an opaque value, we're being asked to bind
3856 // it to its source expression.
3857 if (OpaqueValueExpr
*OVE
= dyn_cast
<OpaqueValueExpr
>(Semantic
))
3858 Semantic
= OVE
->getSourceExpr();
3860 if (CFGBlock
*B
= Visit(Semantic
))
3867 CFGBlock
*CFGBuilder::VisitWhileStmt(WhileStmt
*W
) {
3868 CFGBlock
*LoopSuccessor
= nullptr;
3870 // Save local scope position because in case of condition variable ScopePos
3871 // won't be restored when traversing AST.
3872 SaveAndRestore
save_scope_pos(ScopePos
);
3874 // Create local scope for possible condition variable.
3875 // Store scope position for continue statement.
3876 LocalScope::const_iterator LoopBeginScopePos
= ScopePos
;
3877 if (VarDecl
*VD
= W
->getConditionVariable()) {
3878 addLocalScopeForVarDecl(VD
);
3879 addAutomaticObjHandling(ScopePos
, LoopBeginScopePos
, W
);
3883 // "while" is a control-flow statement. Thus we stop processing the current
3888 LoopSuccessor
= Block
;
3891 LoopSuccessor
= Succ
;
3894 CFGBlock
*BodyBlock
= nullptr, *TransitionBlock
= nullptr;
3896 // Process the loop body.
3898 assert(W
->getBody());
3900 // Save the current values for Block, Succ, continue and break targets.
3901 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
3902 SaveAndRestore
save_continue(ContinueJumpTarget
),
3903 save_break(BreakJumpTarget
);
3905 // Create an empty block to represent the transition block for looping back
3906 // to the head of the loop.
3907 Succ
= TransitionBlock
= createBlock(false);
3908 TransitionBlock
->setLoopTarget(W
);
3909 ContinueJumpTarget
= JumpTarget(Succ
, LoopBeginScopePos
);
3911 // All breaks should go to the code following the loop.
3912 BreakJumpTarget
= JumpTarget(LoopSuccessor
, ScopePos
);
3914 // Loop body should end with destructor of Condition variable (if any).
3915 addAutomaticObjHandling(ScopePos
, LoopBeginScopePos
, W
);
3917 // If body is not a compound statement create implicit scope
3918 // and add destructors.
3919 if (!isa
<CompoundStmt
>(W
->getBody()))
3920 addLocalScopeAndDtors(W
->getBody());
3922 // Create the body. The returned block is the entry to the loop body.
3923 BodyBlock
= addStmt(W
->getBody());
3926 BodyBlock
= ContinueJumpTarget
.block
; // can happen for "while(...) ;"
3927 else if (Block
&& badCFG
)
3931 // Because of short-circuit evaluation, the condition of the loop can span
3932 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3933 // evaluate the condition.
3934 CFGBlock
*EntryConditionBlock
= nullptr, *ExitConditionBlock
= nullptr;
3937 Expr
*C
= W
->getCond();
3939 // Specially handle logical operators, which have a slightly
3940 // more optimal CFG representation.
3941 if (BinaryOperator
*Cond
= dyn_cast
<BinaryOperator
>(C
->IgnoreParens()))
3942 if (Cond
->isLogicalOp()) {
3943 std::tie(EntryConditionBlock
, ExitConditionBlock
) =
3944 VisitLogicalOperator(Cond
, W
, BodyBlock
, LoopSuccessor
);
3948 // The default case when not handling logical operators.
3949 ExitConditionBlock
= createBlock(false);
3950 ExitConditionBlock
->setTerminator(W
);
3952 // Now add the actual condition to the condition block.
3953 // Because the condition itself may contain control-flow, new blocks may
3954 // be created. Thus we update "Succ" after adding the condition.
3955 Block
= ExitConditionBlock
;
3956 Block
= EntryConditionBlock
= addStmt(C
);
3958 // If this block contains a condition variable, add both the condition
3959 // variable and initializer to the CFG.
3960 if (VarDecl
*VD
= W
->getConditionVariable()) {
3961 if (Expr
*Init
= VD
->getInit()) {
3963 const DeclStmt
*DS
= W
->getConditionVariableDeclStmt();
3964 assert(DS
->isSingleDecl());
3965 findConstructionContexts(
3966 ConstructionContextLayer::create(cfg
->getBumpVectorContext(),
3967 const_cast<DeclStmt
*>(DS
)),
3969 appendStmt(Block
, DS
);
3970 EntryConditionBlock
= addStmt(Init
);
3971 assert(Block
== EntryConditionBlock
);
3972 maybeAddScopeBeginForVarDecl(EntryConditionBlock
, VD
, C
);
3976 if (Block
&& badCFG
)
3979 // See if this is a known constant.
3980 const TryResult
& KnownVal
= tryEvaluateBool(C
);
3982 // Add the loop body entry as a successor to the condition.
3983 addSuccessor(ExitConditionBlock
, KnownVal
.isFalse() ? nullptr : BodyBlock
);
3984 // Link up the condition block with the code that follows the loop. (the
3986 addSuccessor(ExitConditionBlock
,
3987 KnownVal
.isTrue() ? nullptr : LoopSuccessor
);
3990 // Link up the loop-back block to the entry condition block.
3991 addSuccessor(TransitionBlock
, EntryConditionBlock
);
3993 // There can be no more statements in the condition block since we loop back
3994 // to this block. NULL out Block to force lazy creation of another block.
3997 // Return the condition block, which is the dominating block for the loop.
3998 Succ
= EntryConditionBlock
;
3999 return EntryConditionBlock
;
4002 CFGBlock
*CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr
*A
,
4003 AddStmtChoice asc
) {
4004 if (asc
.alwaysAdd(*this, A
)) {
4006 appendStmt(Block
, A
);
4009 CFGBlock
*B
= Block
;
4011 if (CFGBlock
*R
= Visit(A
->getSubExpr()))
4014 auto *OVE
= dyn_cast
<OpaqueValueExpr
>(A
->getCommonExpr());
4015 assert(OVE
&& "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
4016 "OpaqueValueExpr!");
4017 if (CFGBlock
*R
= Visit(OVE
->getSourceExpr()))
4023 CFGBlock
*CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt
*CS
) {
4024 // ObjCAtCatchStmt are treated like labels, so they are the first statement
4027 // Save local scope position because in case of exception variable ScopePos
4028 // won't be restored when traversing AST.
4029 SaveAndRestore
save_scope_pos(ScopePos
);
4031 if (CS
->getCatchBody())
4032 addStmt(CS
->getCatchBody());
4034 CFGBlock
*CatchBlock
= Block
;
4036 CatchBlock
= createBlock();
4038 appendStmt(CatchBlock
, CS
);
4040 // Also add the ObjCAtCatchStmt as a label, like with regular labels.
4041 CatchBlock
->setLabel(CS
);
4043 // Bail out if the CFG is bad.
4047 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4053 CFGBlock
*CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt
*S
) {
4054 // If we were in the middle of a block we stop processing that block.
4058 // Create the new block.
4059 Block
= createBlock(false);
4061 if (TryTerminatedBlock
)
4062 // The current try statement is the only successor.
4063 addSuccessor(Block
, TryTerminatedBlock
);
4065 // otherwise the Exit block is the only successor.
4066 addSuccessor(Block
, &cfg
->getExit());
4068 // Add the statement to the block. This may create new blocks if S contains
4069 // control-flow (short-circuit operations).
4070 return VisitStmt(S
, AddStmtChoice::AlwaysAdd
);
4073 CFGBlock
*CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt
*Terminator
) {
4074 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
4076 CFGBlock
*TrySuccessor
= nullptr;
4081 TrySuccessor
= Block
;
4083 TrySuccessor
= Succ
;
4085 // FIXME: Implement @finally support.
4086 if (Terminator
->getFinallyStmt())
4089 CFGBlock
*PrevTryTerminatedBlock
= TryTerminatedBlock
;
4091 // Create a new block that will contain the try statement.
4092 CFGBlock
*NewTryTerminatedBlock
= createBlock(false);
4093 // Add the terminator in the try block.
4094 NewTryTerminatedBlock
->setTerminator(Terminator
);
4096 bool HasCatchAll
= false;
4097 for (ObjCAtCatchStmt
*CS
: Terminator
->catch_stmts()) {
4098 // The code after the try is the implicit successor.
4099 Succ
= TrySuccessor
;
4100 if (CS
->hasEllipsis()) {
4104 CFGBlock
*CatchBlock
= VisitObjCAtCatchStmt(CS
);
4107 // Add this block to the list of successors for the block with the try
4109 addSuccessor(NewTryTerminatedBlock
, CatchBlock
);
4112 // FIXME: This needs updating when @finally support is added.
4114 if (PrevTryTerminatedBlock
)
4115 addSuccessor(NewTryTerminatedBlock
, PrevTryTerminatedBlock
);
4117 addSuccessor(NewTryTerminatedBlock
, &cfg
->getExit());
4120 // The code after the try is the implicit successor.
4121 Succ
= TrySuccessor
;
4123 // Save the current "try" context.
4124 SaveAndRestore
SaveTry(TryTerminatedBlock
, NewTryTerminatedBlock
);
4125 cfg
->addTryDispatchBlock(TryTerminatedBlock
);
4127 assert(Terminator
->getTryBody() && "try must contain a non-NULL body");
4129 return addStmt(Terminator
->getTryBody());
4132 CFGBlock
*CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr
*ME
,
4133 AddStmtChoice asc
) {
4134 findConstructionContextsForArguments(ME
);
4137 appendObjCMessage(Block
, ME
);
4139 return VisitChildren(ME
);
4142 CFGBlock
*CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr
*T
) {
4143 // If we were in the middle of a block we stop processing that block.
4147 // Create the new block.
4148 Block
= createBlock(false);
4150 if (TryTerminatedBlock
)
4151 // The current try statement is the only successor.
4152 addSuccessor(Block
, TryTerminatedBlock
);
4154 // otherwise the Exit block is the only successor.
4155 addSuccessor(Block
, &cfg
->getExit());
4157 // Add the statement to the block. This may create new blocks if S contains
4158 // control-flow (short-circuit operations).
4159 return VisitStmt(T
, AddStmtChoice::AlwaysAdd
);
4162 CFGBlock
*CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr
*S
, AddStmtChoice asc
) {
4163 if (asc
.alwaysAdd(*this, S
)) {
4165 appendStmt(Block
, S
);
4168 // C++ [expr.typeid]p3:
4169 // When typeid is applied to an expression other than an glvalue of a
4170 // polymorphic class type [...] [the] expression is an unevaluated
4172 // We add only potentially evaluated statements to the block to avoid
4173 // CFG generation for unevaluated operands.
4174 if (!S
->isTypeDependent() && S
->isPotentiallyEvaluated())
4175 return VisitChildren(S
);
4177 // Return block without CFG for unevaluated operands.
4181 CFGBlock
*CFGBuilder::VisitDoStmt(DoStmt
*D
) {
4182 CFGBlock
*LoopSuccessor
= nullptr;
4186 // "do...while" is a control-flow statement. Thus we stop processing the
4191 LoopSuccessor
= Block
;
4193 LoopSuccessor
= Succ
;
4195 // Because of short-circuit evaluation, the condition of the loop can span
4196 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4197 // evaluate the condition.
4198 CFGBlock
*ExitConditionBlock
= createBlock(false);
4199 CFGBlock
*EntryConditionBlock
= ExitConditionBlock
;
4201 // Set the terminator for the "exit" condition block.
4202 ExitConditionBlock
->setTerminator(D
);
4204 // Now add the actual condition to the condition block. Because the condition
4205 // itself may contain control-flow, new blocks may be created.
4206 if (Stmt
*C
= D
->getCond()) {
4207 Block
= ExitConditionBlock
;
4208 EntryConditionBlock
= addStmt(C
);
4215 // The condition block is the implicit successor for the loop body.
4216 Succ
= EntryConditionBlock
;
4218 // See if this is a known constant.
4219 const TryResult
&KnownVal
= tryEvaluateBool(D
->getCond());
4221 // Process the loop body.
4222 CFGBlock
*BodyBlock
= nullptr;
4224 assert(D
->getBody());
4226 // Save the current values for Block, Succ, and continue and break targets
4227 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
4228 SaveAndRestore
save_continue(ContinueJumpTarget
),
4229 save_break(BreakJumpTarget
);
4231 // All continues within this loop should go to the condition block
4232 ContinueJumpTarget
= JumpTarget(EntryConditionBlock
, ScopePos
);
4234 // All breaks should go to the code following the loop.
4235 BreakJumpTarget
= JumpTarget(LoopSuccessor
, ScopePos
);
4237 // NULL out Block to force lazy instantiation of blocks for the body.
4240 // If body is not a compound statement create implicit scope
4241 // and add destructors.
4242 if (!isa
<CompoundStmt
>(D
->getBody()))
4243 addLocalScopeAndDtors(D
->getBody());
4245 // Create the body. The returned block is the entry to the loop body.
4246 BodyBlock
= addStmt(D
->getBody());
4249 BodyBlock
= EntryConditionBlock
; // can happen for "do ; while(...)"
4255 // Add an intermediate block between the BodyBlock and the
4256 // ExitConditionBlock to represent the "loop back" transition. Create an
4257 // empty block to represent the transition block for looping back to the
4258 // head of the loop.
4259 // FIXME: Can we do this more efficiently without adding another block?
4262 CFGBlock
*LoopBackBlock
= createBlock();
4263 LoopBackBlock
->setLoopTarget(D
);
4265 if (!KnownVal
.isFalse())
4266 // Add the loop body entry as a successor to the condition.
4267 addSuccessor(ExitConditionBlock
, LoopBackBlock
);
4269 addSuccessor(ExitConditionBlock
, nullptr);
4272 // Link up the condition block with the code that follows the loop.
4273 // (the false branch).
4274 addSuccessor(ExitConditionBlock
, KnownVal
.isTrue() ? nullptr : LoopSuccessor
);
4276 // There can be no more statements in the body block(s) since we loop back to
4277 // the body. NULL out Block to force lazy creation of another block.
4280 // Return the loop body, which is the dominating block for the loop.
4285 CFGBlock
*CFGBuilder::VisitContinueStmt(ContinueStmt
*C
) {
4286 // "continue" is a control-flow statement. Thus we stop processing the
4291 // Now create a new block that ends with the continue statement.
4292 Block
= createBlock(false);
4293 Block
->setTerminator(C
);
4295 // If there is no target for the continue, then we are looking at an
4296 // incomplete AST. This means the CFG cannot be constructed.
4297 if (ContinueJumpTarget
.block
) {
4298 addAutomaticObjHandling(ScopePos
, ContinueJumpTarget
.scopePosition
, C
);
4299 addSuccessor(Block
, ContinueJumpTarget
.block
);
4306 CFGBlock
*CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr
*E
,
4307 AddStmtChoice asc
) {
4308 if (asc
.alwaysAdd(*this, E
)) {
4310 appendStmt(Block
, E
);
4313 // VLA types have expressions that must be evaluated.
4314 // Evaluation is done only for `sizeof`.
4316 if (E
->getKind() != UETT_SizeOf
)
4319 CFGBlock
*lastBlock
= Block
;
4321 if (E
->isArgumentType()) {
4322 for (const VariableArrayType
*VA
=FindVA(E
->getArgumentType().getTypePtr());
4323 VA
!= nullptr; VA
= FindVA(VA
->getElementType().getTypePtr()))
4324 lastBlock
= addStmt(VA
->getSizeExpr());
4329 /// VisitStmtExpr - Utility method to handle (nested) statement
4330 /// expressions (a GCC extension).
4331 CFGBlock
*CFGBuilder::VisitStmtExpr(StmtExpr
*SE
, AddStmtChoice asc
) {
4332 if (asc
.alwaysAdd(*this, SE
)) {
4334 appendStmt(Block
, SE
);
4336 return VisitCompoundStmt(SE
->getSubStmt(), /*ExternallyDestructed=*/true);
4339 CFGBlock
*CFGBuilder::VisitSwitchStmt(SwitchStmt
*Terminator
) {
4340 // "switch" is a control-flow statement. Thus we stop processing the current
4342 CFGBlock
*SwitchSuccessor
= nullptr;
4344 // Save local scope position because in case of condition variable ScopePos
4345 // won't be restored when traversing AST.
4346 SaveAndRestore
save_scope_pos(ScopePos
);
4348 // Create local scope for C++17 switch init-stmt if one exists.
4349 if (Stmt
*Init
= Terminator
->getInit())
4350 addLocalScopeForStmt(Init
);
4352 // Create local scope for possible condition variable.
4353 // Store scope position. Add implicit destructor.
4354 if (VarDecl
*VD
= Terminator
->getConditionVariable())
4355 addLocalScopeForVarDecl(VD
);
4357 addAutomaticObjHandling(ScopePos
, save_scope_pos
.get(), Terminator
);
4362 SwitchSuccessor
= Block
;
4363 } else SwitchSuccessor
= Succ
;
4365 // Save the current "switch" context.
4366 SaveAndRestore
save_switch(SwitchTerminatedBlock
),
4367 save_default(DefaultCaseBlock
);
4368 SaveAndRestore
save_break(BreakJumpTarget
);
4370 // Set the "default" case to be the block after the switch statement. If the
4371 // switch statement contains a "default:", this value will be overwritten with
4372 // the block for that code.
4373 DefaultCaseBlock
= SwitchSuccessor
;
4375 // Create a new block that will contain the switch statement.
4376 SwitchTerminatedBlock
= createBlock(false);
4378 // Now process the switch body. The code after the switch is the implicit
4380 Succ
= SwitchSuccessor
;
4381 BreakJumpTarget
= JumpTarget(SwitchSuccessor
, ScopePos
);
4383 // When visiting the body, the case statements should automatically get linked
4384 // up to the switch. We also don't keep a pointer to the body, since all
4385 // control-flow from the switch goes to case/default statements.
4386 assert(Terminator
->getBody() && "switch must contain a non-NULL body");
4389 // For pruning unreachable case statements, save the current state
4390 // for tracking the condition value.
4391 SaveAndRestore
save_switchExclusivelyCovered(switchExclusivelyCovered
, false);
4393 // Determine if the switch condition can be explicitly evaluated.
4394 assert(Terminator
->getCond() && "switch condition must be non-NULL");
4395 Expr::EvalResult result
;
4396 bool b
= tryEvaluate(Terminator
->getCond(), result
);
4397 SaveAndRestore
save_switchCond(switchCond
, b
? &result
: nullptr);
4399 // If body is not a compound statement create implicit scope
4400 // and add destructors.
4401 if (!isa
<CompoundStmt
>(Terminator
->getBody()))
4402 addLocalScopeAndDtors(Terminator
->getBody());
4404 addStmt(Terminator
->getBody());
4410 // If we have no "default:" case, the default transition is to the code
4411 // following the switch body. Moreover, take into account if all the
4412 // cases of a switch are covered (e.g., switching on an enum value).
4414 // Note: We add a successor to a switch that is considered covered yet has no
4415 // case statements if the enumeration has no enumerators.
4416 bool SwitchAlwaysHasSuccessor
= false;
4417 SwitchAlwaysHasSuccessor
|= switchExclusivelyCovered
;
4418 SwitchAlwaysHasSuccessor
|= Terminator
->isAllEnumCasesCovered() &&
4419 Terminator
->getSwitchCaseList();
4420 addSuccessor(SwitchTerminatedBlock
, DefaultCaseBlock
,
4421 !SwitchAlwaysHasSuccessor
);
4423 // Add the terminator and condition in the switch block.
4424 SwitchTerminatedBlock
->setTerminator(Terminator
);
4425 Block
= SwitchTerminatedBlock
;
4426 CFGBlock
*LastBlock
= addStmt(Terminator
->getCond());
4428 // If the SwitchStmt contains a condition variable, add both the
4429 // SwitchStmt and the condition variable initialization to the CFG.
4430 if (VarDecl
*VD
= Terminator
->getConditionVariable()) {
4431 if (Expr
*Init
= VD
->getInit()) {
4433 appendStmt(Block
, Terminator
->getConditionVariableDeclStmt());
4434 LastBlock
= addStmt(Init
);
4435 maybeAddScopeBeginForVarDecl(LastBlock
, VD
, Init
);
4439 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4440 if (Stmt
*Init
= Terminator
->getInit()) {
4442 LastBlock
= addStmt(Init
);
4448 static bool shouldAddCase(bool &switchExclusivelyCovered
,
4449 const Expr::EvalResult
*switchCond
,
4455 bool addCase
= false;
4457 if (!switchExclusivelyCovered
) {
4458 if (switchCond
->Val
.isInt()) {
4459 // Evaluate the LHS of the case value.
4460 const llvm::APSInt
&lhsInt
= CS
->getLHS()->EvaluateKnownConstInt(Ctx
);
4461 const llvm::APSInt
&condInt
= switchCond
->Val
.getInt();
4463 if (condInt
== lhsInt
) {
4465 switchExclusivelyCovered
= true;
4467 else if (condInt
> lhsInt
) {
4468 if (const Expr
*RHS
= CS
->getRHS()) {
4469 // Evaluate the RHS of the case value.
4470 const llvm::APSInt
&V2
= RHS
->EvaluateKnownConstInt(Ctx
);
4471 if (V2
>= condInt
) {
4473 switchExclusivelyCovered
= true;
4484 CFGBlock
*CFGBuilder::VisitCaseStmt(CaseStmt
*CS
) {
4485 // CaseStmts are essentially labels, so they are the first statement in a
4487 CFGBlock
*TopBlock
= nullptr, *LastBlock
= nullptr;
4489 if (Stmt
*Sub
= CS
->getSubStmt()) {
4490 // For deeply nested chains of CaseStmts, instead of doing a recursion
4491 // (which can blow out the stack), manually unroll and create blocks
4493 while (isa
<CaseStmt
>(Sub
)) {
4494 CFGBlock
*currentBlock
= createBlock(false);
4495 currentBlock
->setLabel(CS
);
4498 addSuccessor(LastBlock
, currentBlock
);
4500 TopBlock
= currentBlock
;
4502 addSuccessor(SwitchTerminatedBlock
,
4503 shouldAddCase(switchExclusivelyCovered
, switchCond
,
4505 ? currentBlock
: nullptr);
4507 LastBlock
= currentBlock
;
4508 CS
= cast
<CaseStmt
>(Sub
);
4509 Sub
= CS
->getSubStmt();
4515 CFGBlock
*CaseBlock
= Block
;
4517 CaseBlock
= createBlock();
4519 // Cases statements partition blocks, so this is the top of the basic block we
4520 // were processing (the "case XXX:" is the label).
4521 CaseBlock
->setLabel(CS
);
4526 // Add this block to the list of successors for the block with the switch
4528 assert(SwitchTerminatedBlock
);
4529 addSuccessor(SwitchTerminatedBlock
, CaseBlock
,
4530 shouldAddCase(switchExclusivelyCovered
, switchCond
,
4533 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4537 addSuccessor(LastBlock
, CaseBlock
);
4540 // This block is now the implicit successor of other blocks.
4547 CFGBlock
*CFGBuilder::VisitDefaultStmt(DefaultStmt
*Terminator
) {
4548 if (Terminator
->getSubStmt())
4549 addStmt(Terminator
->getSubStmt());
4551 DefaultCaseBlock
= Block
;
4553 if (!DefaultCaseBlock
)
4554 DefaultCaseBlock
= createBlock();
4556 // Default statements partition blocks, so this is the top of the basic block
4557 // we were processing (the "default:" is the label).
4558 DefaultCaseBlock
->setLabel(Terminator
);
4563 // Unlike case statements, we don't add the default block to the successors
4564 // for the switch statement immediately. This is done when we finish
4565 // processing the switch statement. This allows for the default case
4566 // (including a fall-through to the code after the switch statement) to always
4567 // be the last successor of a switch-terminated block.
4569 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4572 // This block is now the implicit successor of other blocks.
4573 Succ
= DefaultCaseBlock
;
4575 return DefaultCaseBlock
;
4578 CFGBlock
*CFGBuilder::VisitCXXTryStmt(CXXTryStmt
*Terminator
) {
4579 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4581 CFGBlock
*TrySuccessor
= nullptr;
4586 TrySuccessor
= Block
;
4588 TrySuccessor
= Succ
;
4590 CFGBlock
*PrevTryTerminatedBlock
= TryTerminatedBlock
;
4592 // Create a new block that will contain the try statement.
4593 CFGBlock
*NewTryTerminatedBlock
= createBlock(false);
4594 // Add the terminator in the try block.
4595 NewTryTerminatedBlock
->setTerminator(Terminator
);
4597 bool HasCatchAll
= false;
4598 for (unsigned I
= 0, E
= Terminator
->getNumHandlers(); I
!= E
; ++I
) {
4599 // The code after the try is the implicit successor.
4600 Succ
= TrySuccessor
;
4601 CXXCatchStmt
*CS
= Terminator
->getHandler(I
);
4602 if (CS
->getExceptionDecl() == nullptr) {
4606 CFGBlock
*CatchBlock
= VisitCXXCatchStmt(CS
);
4609 // Add this block to the list of successors for the block with the try
4611 addSuccessor(NewTryTerminatedBlock
, CatchBlock
);
4614 if (PrevTryTerminatedBlock
)
4615 addSuccessor(NewTryTerminatedBlock
, PrevTryTerminatedBlock
);
4617 addSuccessor(NewTryTerminatedBlock
, &cfg
->getExit());
4620 // The code after the try is the implicit successor.
4621 Succ
= TrySuccessor
;
4623 // Save the current "try" context.
4624 SaveAndRestore
SaveTry(TryTerminatedBlock
, NewTryTerminatedBlock
);
4625 cfg
->addTryDispatchBlock(TryTerminatedBlock
);
4627 assert(Terminator
->getTryBlock() && "try must contain a non-NULL body");
4629 return addStmt(Terminator
->getTryBlock());
4632 CFGBlock
*CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt
*CS
) {
4633 // CXXCatchStmt are treated like labels, so they are the first statement in a
4636 // Save local scope position because in case of exception variable ScopePos
4637 // won't be restored when traversing AST.
4638 SaveAndRestore
save_scope_pos(ScopePos
);
4640 // Create local scope for possible exception variable.
4641 // Store scope position. Add implicit destructor.
4642 if (VarDecl
*VD
= CS
->getExceptionDecl()) {
4643 LocalScope::const_iterator BeginScopePos
= ScopePos
;
4644 addLocalScopeForVarDecl(VD
);
4645 addAutomaticObjHandling(ScopePos
, BeginScopePos
, CS
);
4648 if (CS
->getHandlerBlock())
4649 addStmt(CS
->getHandlerBlock());
4651 CFGBlock
*CatchBlock
= Block
;
4653 CatchBlock
= createBlock();
4655 // CXXCatchStmt is more than just a label. They have semantic meaning
4656 // as well, as they implicitly "initialize" the catch variable. Add
4657 // it to the CFG as a CFGElement so that the control-flow of these
4658 // semantics gets captured.
4659 appendStmt(CatchBlock
, CS
);
4661 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4663 CatchBlock
->setLabel(CS
);
4665 // Bail out if the CFG is bad.
4669 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4675 CFGBlock
*CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt
*S
) {
4676 // C++0x for-range statements are specified as [stmt.ranged]:
4679 // auto && __range = range-init;
4680 // for ( auto __begin = begin-expr,
4681 // __end = end-expr;
4682 // __begin != __end;
4684 // for-range-declaration = *__begin;
4689 // Save local scope position before the addition of the implicit variables.
4690 SaveAndRestore
save_scope_pos(ScopePos
);
4692 // Create local scopes and destructors for range, begin and end variables.
4693 if (Stmt
*Range
= S
->getRangeStmt())
4694 addLocalScopeForStmt(Range
);
4695 if (Stmt
*Begin
= S
->getBeginStmt())
4696 addLocalScopeForStmt(Begin
);
4697 if (Stmt
*End
= S
->getEndStmt())
4698 addLocalScopeForStmt(End
);
4699 addAutomaticObjHandling(ScopePos
, save_scope_pos
.get(), S
);
4701 LocalScope::const_iterator ContinueScopePos
= ScopePos
;
4703 // "for" is a control-flow statement. Thus we stop processing the current
4705 CFGBlock
*LoopSuccessor
= nullptr;
4709 LoopSuccessor
= Block
;
4711 LoopSuccessor
= Succ
;
4713 // Save the current value for the break targets.
4714 // All breaks should go to the code following the loop.
4715 SaveAndRestore
save_break(BreakJumpTarget
);
4716 BreakJumpTarget
= JumpTarget(LoopSuccessor
, ScopePos
);
4718 // The block for the __begin != __end expression.
4719 CFGBlock
*ConditionBlock
= createBlock(false);
4720 ConditionBlock
->setTerminator(S
);
4722 // Now add the actual condition to the condition block.
4723 if (Expr
*C
= S
->getCond()) {
4724 Block
= ConditionBlock
;
4725 CFGBlock
*BeginConditionBlock
= addStmt(C
);
4728 assert(BeginConditionBlock
== ConditionBlock
&&
4729 "condition block in for-range was unexpectedly complex");
4730 (void)BeginConditionBlock
;
4733 // The condition block is the implicit successor for the loop body as well as
4734 // any code above the loop.
4735 Succ
= ConditionBlock
;
4737 // See if this is a known constant.
4738 TryResult
KnownVal(true);
4741 KnownVal
= tryEvaluateBool(S
->getCond());
4743 // Now create the loop body.
4745 assert(S
->getBody());
4747 // Save the current values for Block, Succ, and continue targets.
4748 SaveAndRestore
save_Block(Block
), save_Succ(Succ
);
4749 SaveAndRestore
save_continue(ContinueJumpTarget
);
4751 // Generate increment code in its own basic block. This is the target of
4752 // continue statements.
4754 Succ
= addStmt(S
->getInc());
4757 ContinueJumpTarget
= JumpTarget(Succ
, ContinueScopePos
);
4759 // The starting block for the loop increment is the block that should
4760 // represent the 'loop target' for looping back to the start of the loop.
4761 ContinueJumpTarget
.block
->setLoopTarget(S
);
4763 // Finish up the increment block and prepare to start the loop body.
4769 // Add implicit scope and dtors for loop variable.
4770 addLocalScopeAndDtors(S
->getLoopVarStmt());
4772 // If body is not a compound statement create implicit scope
4773 // and add destructors.
4774 if (!isa
<CompoundStmt
>(S
->getBody()))
4775 addLocalScopeAndDtors(S
->getBody());
4777 // Populate a new block to contain the loop body and loop variable.
4778 addStmt(S
->getBody());
4782 CFGBlock
*LoopVarStmtBlock
= addStmt(S
->getLoopVarStmt());
4786 // This new body block is a successor to our condition block.
4787 addSuccessor(ConditionBlock
,
4788 KnownVal
.isFalse() ? nullptr : LoopVarStmtBlock
);
4791 // Link up the condition block with the code that follows the loop (the
4793 addSuccessor(ConditionBlock
, KnownVal
.isTrue() ? nullptr : LoopSuccessor
);
4795 // Add the initialization statements.
4796 Block
= createBlock();
4797 addStmt(S
->getBeginStmt());
4798 addStmt(S
->getEndStmt());
4799 CFGBlock
*Head
= addStmt(S
->getRangeStmt());
4801 Head
= addStmt(S
->getInit());
4805 CFGBlock
*CFGBuilder::VisitExprWithCleanups(ExprWithCleanups
*E
,
4806 AddStmtChoice asc
, bool ExternallyDestructed
) {
4807 if (BuildOpts
.AddTemporaryDtors
) {
4808 // If adding implicit destructors visit the full expression for adding
4809 // destructors of temporaries.
4810 TempDtorContext Context
;
4811 VisitForTemporaryDtors(E
->getSubExpr(), ExternallyDestructed
, Context
);
4813 // Full expression has to be added as CFGStmt so it will be sequenced
4814 // before destructors of it's temporaries.
4815 asc
= asc
.withAlwaysAdd(true);
4817 return Visit(E
->getSubExpr(), asc
);
4820 CFGBlock
*CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr
*E
,
4821 AddStmtChoice asc
) {
4822 if (asc
.alwaysAdd(*this, E
)) {
4824 appendStmt(Block
, E
);
4826 findConstructionContexts(
4827 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), E
),
4830 // We do not want to propagate the AlwaysAdd property.
4831 asc
= asc
.withAlwaysAdd(false);
4833 return Visit(E
->getSubExpr(), asc
);
4836 CFGBlock
*CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr
*C
,
4837 AddStmtChoice asc
) {
4838 // If the constructor takes objects as arguments by value, we need to properly
4839 // construct these objects. Construction contexts we find here aren't for the
4840 // constructor C, they're for its arguments only.
4841 findConstructionContextsForArguments(C
);
4842 appendConstructor(C
);
4844 return VisitChildren(C
);
4847 CFGBlock
*CFGBuilder::VisitCXXNewExpr(CXXNewExpr
*NE
,
4848 AddStmtChoice asc
) {
4850 appendStmt(Block
, NE
);
4852 findConstructionContexts(
4853 ConstructionContextLayer::create(cfg
->getBumpVectorContext(), NE
),
4854 const_cast<CXXConstructExpr
*>(NE
->getConstructExpr()));
4856 if (NE
->getInitializer())
4857 Block
= Visit(NE
->getInitializer());
4859 if (BuildOpts
.AddCXXNewAllocator
)
4860 appendNewAllocator(Block
, NE
);
4862 if (NE
->isArray() && *NE
->getArraySize())
4863 Block
= Visit(*NE
->getArraySize());
4865 for (CXXNewExpr::arg_iterator I
= NE
->placement_arg_begin(),
4866 E
= NE
->placement_arg_end(); I
!= E
; ++I
)
4872 CFGBlock
*CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr
*DE
,
4873 AddStmtChoice asc
) {
4875 appendStmt(Block
, DE
);
4876 QualType DTy
= DE
->getDestroyedType();
4877 if (!DTy
.isNull()) {
4878 DTy
= DTy
.getNonReferenceType();
4879 CXXRecordDecl
*RD
= Context
->getBaseElementType(DTy
)->getAsCXXRecordDecl();
4881 if (RD
->isCompleteDefinition() && !RD
->hasTrivialDestructor())
4882 appendDeleteDtor(Block
, RD
, DE
);
4886 return VisitChildren(DE
);
4889 CFGBlock
*CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr
*E
,
4890 AddStmtChoice asc
) {
4891 if (asc
.alwaysAdd(*this, E
)) {
4893 appendStmt(Block
, E
);
4894 // We do not want to propagate the AlwaysAdd property.
4895 asc
= asc
.withAlwaysAdd(false);
4897 return Visit(E
->getSubExpr(), asc
);
4900 CFGBlock
*CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr
*E
,
4901 AddStmtChoice asc
) {
4902 // If the constructor takes objects as arguments by value, we need to properly
4903 // construct these objects. Construction contexts we find here aren't for the
4904 // constructor C, they're for its arguments only.
4905 findConstructionContextsForArguments(E
);
4906 appendConstructor(E
);
4908 return VisitChildren(E
);
4911 CFGBlock
*CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr
*E
,
4912 AddStmtChoice asc
) {
4913 if (asc
.alwaysAdd(*this, E
)) {
4915 appendStmt(Block
, E
);
4918 if (E
->getCastKind() == CK_IntegralToBoolean
)
4919 tryEvaluateBool(E
->getSubExpr()->IgnoreParens());
4921 return Visit(E
->getSubExpr(), AddStmtChoice());
4924 CFGBlock
*CFGBuilder::VisitConstantExpr(ConstantExpr
*E
, AddStmtChoice asc
) {
4925 return Visit(E
->getSubExpr(), AddStmtChoice());
4928 CFGBlock
*CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt
*I
) {
4929 // Lazily create the indirect-goto dispatch block if there isn't one already.
4930 CFGBlock
*IBlock
= cfg
->getIndirectGotoBlock();
4933 IBlock
= createBlock(false);
4934 cfg
->setIndirectGotoBlock(IBlock
);
4937 // IndirectGoto is a control-flow statement. Thus we stop processing the
4938 // current block and create a new one.
4942 Block
= createBlock(false);
4943 Block
->setTerminator(I
);
4944 addSuccessor(Block
, IBlock
);
4945 return addStmt(I
->getTarget());
4948 CFGBlock
*CFGBuilder::VisitForTemporaryDtors(Stmt
*E
, bool ExternallyDestructed
,
4949 TempDtorContext
&Context
) {
4950 assert(BuildOpts
.AddImplicitDtors
&& BuildOpts
.AddTemporaryDtors
);
4957 switch (E
->getStmtClass()) {
4959 return VisitChildrenForTemporaryDtors(E
, false, Context
);
4961 case Stmt::InitListExprClass
:
4962 return VisitChildrenForTemporaryDtors(E
, ExternallyDestructed
, Context
);
4964 case Stmt::BinaryOperatorClass
:
4965 return VisitBinaryOperatorForTemporaryDtors(cast
<BinaryOperator
>(E
),
4966 ExternallyDestructed
,
4969 case Stmt::CXXBindTemporaryExprClass
:
4970 return VisitCXXBindTemporaryExprForTemporaryDtors(
4971 cast
<CXXBindTemporaryExpr
>(E
), ExternallyDestructed
, Context
);
4973 case Stmt::BinaryConditionalOperatorClass
:
4974 case Stmt::ConditionalOperatorClass
:
4975 return VisitConditionalOperatorForTemporaryDtors(
4976 cast
<AbstractConditionalOperator
>(E
), ExternallyDestructed
, Context
);
4978 case Stmt::ImplicitCastExprClass
:
4979 // For implicit cast we want ExternallyDestructed to be passed further.
4980 E
= cast
<CastExpr
>(E
)->getSubExpr();
4983 case Stmt::CXXFunctionalCastExprClass
:
4984 // For functional cast we want ExternallyDestructed to be passed further.
4985 E
= cast
<CXXFunctionalCastExpr
>(E
)->getSubExpr();
4988 case Stmt::ConstantExprClass
:
4989 E
= cast
<ConstantExpr
>(E
)->getSubExpr();
4992 case Stmt::ParenExprClass
:
4993 E
= cast
<ParenExpr
>(E
)->getSubExpr();
4996 case Stmt::MaterializeTemporaryExprClass
: {
4997 const MaterializeTemporaryExpr
* MTE
= cast
<MaterializeTemporaryExpr
>(E
);
4998 ExternallyDestructed
= (MTE
->getStorageDuration() != SD_FullExpression
);
4999 SmallVector
<const Expr
*, 2> CommaLHSs
;
5000 SmallVector
<SubobjectAdjustment
, 2> Adjustments
;
5001 // Find the expression whose lifetime needs to be extended.
5002 E
= const_cast<Expr
*>(
5003 cast
<MaterializeTemporaryExpr
>(E
)
5005 ->skipRValueSubobjectAdjustments(CommaLHSs
, Adjustments
));
5006 // Visit the skipped comma operator left-hand sides for other temporaries.
5007 for (const Expr
*CommaLHS
: CommaLHSs
) {
5008 VisitForTemporaryDtors(const_cast<Expr
*>(CommaLHS
),
5009 /*ExternallyDestructed=*/false, Context
);
5014 case Stmt::BlockExprClass
:
5015 // Don't recurse into blocks; their subexpressions don't get evaluated
5019 case Stmt::LambdaExprClass
: {
5020 // For lambda expressions, only recurse into the capture initializers,
5021 // and not the body.
5022 auto *LE
= cast
<LambdaExpr
>(E
);
5023 CFGBlock
*B
= Block
;
5024 for (Expr
*Init
: LE
->capture_inits()) {
5026 if (CFGBlock
*R
= VisitForTemporaryDtors(
5027 Init
, /*ExternallyDestructed=*/true, Context
))
5034 case Stmt::StmtExprClass
:
5035 // Don't recurse into statement expressions; any cleanups inside them
5036 // will be wrapped in their own ExprWithCleanups.
5039 case Stmt::CXXDefaultArgExprClass
:
5040 E
= cast
<CXXDefaultArgExpr
>(E
)->getExpr();
5043 case Stmt::CXXDefaultInitExprClass
:
5044 E
= cast
<CXXDefaultInitExpr
>(E
)->getExpr();
5049 CFGBlock
*CFGBuilder::VisitChildrenForTemporaryDtors(Stmt
*E
,
5050 bool ExternallyDestructed
,
5051 TempDtorContext
&Context
) {
5052 if (isa
<LambdaExpr
>(E
)) {
5053 // Do not visit the children of lambdas; they have their own CFGs.
5057 // When visiting children for destructors we want to visit them in reverse
5058 // order that they will appear in the CFG. Because the CFG is built
5059 // bottom-up, this means we visit them in their natural order, which
5060 // reverses them in the CFG.
5061 CFGBlock
*B
= Block
;
5062 for (Stmt
*Child
: E
->children())
5064 if (CFGBlock
*R
= VisitForTemporaryDtors(Child
, ExternallyDestructed
, Context
))
5070 CFGBlock
*CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
5071 BinaryOperator
*E
, bool ExternallyDestructed
, TempDtorContext
&Context
) {
5072 if (E
->isCommaOp()) {
5073 // For the comma operator, the LHS expression is evaluated before the RHS
5074 // expression, so prepend temporary destructors for the LHS first.
5075 CFGBlock
*LHSBlock
= VisitForTemporaryDtors(E
->getLHS(), false, Context
);
5076 CFGBlock
*RHSBlock
= VisitForTemporaryDtors(E
->getRHS(), ExternallyDestructed
, Context
);
5077 return RHSBlock
? RHSBlock
: LHSBlock
;
5080 if (E
->isLogicalOp()) {
5081 VisitForTemporaryDtors(E
->getLHS(), false, Context
);
5082 TryResult RHSExecuted
= tryEvaluateBool(E
->getLHS());
5083 if (RHSExecuted
.isKnown() && E
->getOpcode() == BO_LOr
)
5084 RHSExecuted
.negate();
5086 // We do not know at CFG-construction time whether the right-hand-side was
5087 // executed, thus we add a branch node that depends on the temporary
5088 // constructor call.
5089 TempDtorContext
RHSContext(
5090 bothKnownTrue(Context
.KnownExecuted
, RHSExecuted
));
5091 VisitForTemporaryDtors(E
->getRHS(), false, RHSContext
);
5092 InsertTempDtorDecisionBlock(RHSContext
);
5097 if (E
->isAssignmentOp()) {
5098 // For assignment operators, the RHS expression is evaluated before the LHS
5099 // expression, so prepend temporary destructors for the RHS first.
5100 CFGBlock
*RHSBlock
= VisitForTemporaryDtors(E
->getRHS(), false, Context
);
5101 CFGBlock
*LHSBlock
= VisitForTemporaryDtors(E
->getLHS(), false, Context
);
5102 return LHSBlock
? LHSBlock
: RHSBlock
;
5105 // Any other operator is visited normally.
5106 return VisitChildrenForTemporaryDtors(E
, ExternallyDestructed
, Context
);
5109 CFGBlock
*CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
5110 CXXBindTemporaryExpr
*E
, bool ExternallyDestructed
, TempDtorContext
&Context
) {
5111 // First add destructors for temporaries in subexpression.
5112 // Because VisitCXXBindTemporaryExpr calls setDestructed:
5113 CFGBlock
*B
= VisitForTemporaryDtors(E
->getSubExpr(), true, Context
);
5114 if (!ExternallyDestructed
) {
5115 // If lifetime of temporary is not prolonged (by assigning to constant
5116 // reference) add destructor for it.
5118 const CXXDestructorDecl
*Dtor
= E
->getTemporary()->getDestructor();
5120 if (Dtor
->getParent()->isAnyDestructorNoReturn()) {
5121 // If the destructor is marked as a no-return destructor, we need to
5122 // create a new block for the destructor which does not have as a
5123 // successor anything built thus far. Control won't flow out of this
5126 Block
= createNoReturnBlock();
5127 } else if (Context
.needsTempDtorBranch()) {
5128 // If we need to introduce a branch, we add a new block that we will hook
5129 // up to a decision block later.
5131 Block
= createBlock();
5135 if (Context
.needsTempDtorBranch()) {
5136 Context
.setDecisionPoint(Succ
, E
);
5138 appendTemporaryDtor(Block
, E
);
5145 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext
&Context
,
5146 CFGBlock
*FalseSucc
) {
5147 if (!Context
.TerminatorExpr
) {
5148 // If no temporary was found, we do not need to insert a decision point.
5151 assert(Context
.TerminatorExpr
);
5152 CFGBlock
*Decision
= createBlock(false);
5153 Decision
->setTerminator(CFGTerminator(Context
.TerminatorExpr
,
5154 CFGTerminator::TemporaryDtorsBranch
));
5155 addSuccessor(Decision
, Block
, !Context
.KnownExecuted
.isFalse());
5156 addSuccessor(Decision
, FalseSucc
? FalseSucc
: Context
.Succ
,
5157 !Context
.KnownExecuted
.isTrue());
5161 CFGBlock
*CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
5162 AbstractConditionalOperator
*E
, bool ExternallyDestructed
,
5163 TempDtorContext
&Context
) {
5164 VisitForTemporaryDtors(E
->getCond(), false, Context
);
5165 CFGBlock
*ConditionBlock
= Block
;
5166 CFGBlock
*ConditionSucc
= Succ
;
5167 TryResult ConditionVal
= tryEvaluateBool(E
->getCond());
5168 TryResult NegatedVal
= ConditionVal
;
5169 if (NegatedVal
.isKnown()) NegatedVal
.negate();
5171 TempDtorContext
TrueContext(
5172 bothKnownTrue(Context
.KnownExecuted
, ConditionVal
));
5173 VisitForTemporaryDtors(E
->getTrueExpr(), ExternallyDestructed
, TrueContext
);
5174 CFGBlock
*TrueBlock
= Block
;
5176 Block
= ConditionBlock
;
5177 Succ
= ConditionSucc
;
5178 TempDtorContext
FalseContext(
5179 bothKnownTrue(Context
.KnownExecuted
, NegatedVal
));
5180 VisitForTemporaryDtors(E
->getFalseExpr(), ExternallyDestructed
, FalseContext
);
5182 if (TrueContext
.TerminatorExpr
&& FalseContext
.TerminatorExpr
) {
5183 InsertTempDtorDecisionBlock(FalseContext
, TrueBlock
);
5184 } else if (TrueContext
.TerminatorExpr
) {
5186 InsertTempDtorDecisionBlock(TrueContext
);
5188 InsertTempDtorDecisionBlock(FalseContext
);
5193 CFGBlock
*CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective
*D
,
5194 AddStmtChoice asc
) {
5195 if (asc
.alwaysAdd(*this, D
)) {
5197 appendStmt(Block
, D
);
5200 // Iterate over all used expression in clauses.
5201 CFGBlock
*B
= Block
;
5203 // Reverse the elements to process them in natural order. Iterators are not
5204 // bidirectional, so we need to create temp vector.
5205 SmallVector
<Stmt
*, 8> Used(
5206 OMPExecutableDirective::used_clauses_children(D
->clauses()));
5207 for (Stmt
*S
: llvm::reverse(Used
)) {
5208 assert(S
&& "Expected non-null used-in-clause child.");
5209 if (CFGBlock
*R
= Visit(S
))
5212 // Visit associated structured block if any.
5213 if (!D
->isStandaloneDirective()) {
5214 Stmt
*S
= D
->getRawStmt();
5215 if (!isa
<CompoundStmt
>(S
))
5216 addLocalScopeAndDtors(S
);
5217 if (CFGBlock
*R
= addStmt(S
))
5224 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
5225 /// no successors or predecessors. If this is the first block created in the
5226 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
5227 CFGBlock
*CFG::createBlock() {
5228 bool first_block
= begin() == end();
5230 // Create the block.
5231 CFGBlock
*Mem
= new (getAllocator()) CFGBlock(NumBlockIDs
++, BlkBVC
, this);
5232 Blocks
.push_back(Mem
, BlkBVC
);
5234 // If this is the first block, set it as the Entry and Exit.
5236 Entry
= Exit
= &back();
5238 // Return the block.
5242 /// buildCFG - Constructs a CFG from an AST.
5243 std::unique_ptr
<CFG
> CFG::buildCFG(const Decl
*D
, Stmt
*Statement
,
5244 ASTContext
*C
, const BuildOptions
&BO
) {
5245 CFGBuilder
Builder(C
, BO
);
5246 return Builder
.buildCFG(D
, Statement
);
5249 bool CFG::isLinear() const {
5250 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
5251 // in between, then we have no room for control flow.
5255 // Traverse the CFG until we find a branch.
5256 // TODO: While this should still be very fast,
5257 // maybe we should cache the answer.
5258 llvm::SmallPtrSet
<const CFGBlock
*, 4> Visited
;
5259 const CFGBlock
*B
= Entry
;
5261 auto IteratorAndFlag
= Visited
.insert(B
);
5262 if (!IteratorAndFlag
.second
) {
5263 // We looped back to a block that we've already visited. Not linear.
5267 // Iterate over reachable successors.
5268 const CFGBlock
*FirstReachableB
= nullptr;
5269 for (const CFGBlock::AdjacentBlock
&AB
: B
->succs()) {
5270 if (!AB
.isReachable())
5273 if (FirstReachableB
== nullptr) {
5274 FirstReachableB
= &*AB
;
5276 // We've encountered a branch. It's not a linear CFG.
5281 if (!FirstReachableB
) {
5282 // We reached a dead end. EXIT is unreachable. This is linear enough.
5286 // There's only one way to move forward. Proceed.
5287 B
= FirstReachableB
;
5290 // We reached EXIT and found no branches.
5294 const CXXDestructorDecl
*
5295 CFGImplicitDtor::getDestructorDecl(ASTContext
&astContext
) const {
5296 switch (getKind()) {
5297 case CFGElement::Initializer
:
5298 case CFGElement::NewAllocator
:
5299 case CFGElement::LoopExit
:
5300 case CFGElement::LifetimeEnds
:
5301 case CFGElement::Statement
:
5302 case CFGElement::Constructor
:
5303 case CFGElement::CXXRecordTypedCall
:
5304 case CFGElement::ScopeBegin
:
5305 case CFGElement::ScopeEnd
:
5306 case CFGElement::CleanupFunction
:
5307 llvm_unreachable("getDestructorDecl should only be used with "
5309 case CFGElement::AutomaticObjectDtor
: {
5310 const VarDecl
*var
= castAs
<CFGAutomaticObjDtor
>().getVarDecl();
5311 QualType ty
= var
->getType();
5313 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
5315 // Lifetime-extending constructs are handled here. This works for a single
5316 // temporary in an initializer expression.
5317 if (ty
->isReferenceType()) {
5318 if (const Expr
*Init
= var
->getInit()) {
5319 ty
= getReferenceInitTemporaryType(Init
);
5323 while (const ArrayType
*arrayType
= astContext
.getAsArrayType(ty
)) {
5324 ty
= arrayType
->getElementType();
5327 // The situation when the type of the lifetime-extending reference
5328 // does not correspond to the type of the object is supposed
5329 // to be handled by now. In particular, 'ty' is now the unwrapped
5331 const CXXRecordDecl
*classDecl
= ty
->getAsCXXRecordDecl();
5333 return classDecl
->getDestructor();
5335 case CFGElement::DeleteDtor
: {
5336 const CXXDeleteExpr
*DE
= castAs
<CFGDeleteDtor
>().getDeleteExpr();
5337 QualType DTy
= DE
->getDestroyedType();
5338 DTy
= DTy
.getNonReferenceType();
5339 const CXXRecordDecl
*classDecl
=
5340 astContext
.getBaseElementType(DTy
)->getAsCXXRecordDecl();
5341 return classDecl
->getDestructor();
5343 case CFGElement::TemporaryDtor
: {
5344 const CXXBindTemporaryExpr
*bindExpr
=
5345 castAs
<CFGTemporaryDtor
>().getBindTemporaryExpr();
5346 const CXXTemporary
*temp
= bindExpr
->getTemporary();
5347 return temp
->getDestructor();
5349 case CFGElement::MemberDtor
: {
5350 const FieldDecl
*field
= castAs
<CFGMemberDtor
>().getFieldDecl();
5351 QualType ty
= field
->getType();
5353 while (const ArrayType
*arrayType
= astContext
.getAsArrayType(ty
)) {
5354 ty
= arrayType
->getElementType();
5357 const CXXRecordDecl
*classDecl
= ty
->getAsCXXRecordDecl();
5359 return classDecl
->getDestructor();
5361 case CFGElement::BaseDtor
:
5362 // Not yet supported.
5365 llvm_unreachable("getKind() returned bogus value");
5368 //===----------------------------------------------------------------------===//
5369 // CFGBlock operations.
5370 //===----------------------------------------------------------------------===//
5372 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock
*B
, bool IsReachable
)
5373 : ReachableBlock(IsReachable
? B
: nullptr),
5374 UnreachableBlock(!IsReachable
? B
: nullptr,
5375 B
&& IsReachable
? AB_Normal
: AB_Unreachable
) {}
5377 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock
*B
, CFGBlock
*AlternateBlock
)
5378 : ReachableBlock(B
),
5379 UnreachableBlock(B
== AlternateBlock
? nullptr : AlternateBlock
,
5380 B
== AlternateBlock
? AB_Alternate
: AB_Normal
) {}
5382 void CFGBlock::addSuccessor(AdjacentBlock Succ
,
5383 BumpVectorContext
&C
) {
5384 if (CFGBlock
*B
= Succ
.getReachableBlock())
5385 B
->Preds
.push_back(AdjacentBlock(this, Succ
.isReachable()), C
);
5387 if (CFGBlock
*UnreachableB
= Succ
.getPossiblyUnreachableBlock())
5388 UnreachableB
->Preds
.push_back(AdjacentBlock(this, false), C
);
5390 Succs
.push_back(Succ
, C
);
5393 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions
&F
,
5394 const CFGBlock
*From
, const CFGBlock
*To
) {
5395 if (F
.IgnoreNullPredecessors
&& !From
)
5398 if (To
&& From
&& F
.IgnoreDefaultsWithCoveredEnums
) {
5399 // If the 'To' has no label or is labeled but the label isn't a
5400 // CaseStmt then filter this edge.
5401 if (const SwitchStmt
*S
=
5402 dyn_cast_or_null
<SwitchStmt
>(From
->getTerminatorStmt())) {
5403 if (S
->isAllEnumCasesCovered()) {
5404 const Stmt
*L
= To
->getLabel();
5405 if (!L
|| !isa
<CaseStmt
>(L
))
5414 //===----------------------------------------------------------------------===//
5415 // CFG pretty printing
5416 //===----------------------------------------------------------------------===//
5420 class StmtPrinterHelper
: public PrinterHelper
{
5421 using StmtMapTy
= llvm::DenseMap
<const Stmt
*, std::pair
<unsigned, unsigned>>;
5422 using DeclMapTy
= llvm::DenseMap
<const Decl
*, std::pair
<unsigned, unsigned>>;
5426 signed currentBlock
= 0;
5427 unsigned currStmt
= 0;
5428 const LangOptions
&LangOpts
;
5431 StmtPrinterHelper(const CFG
* cfg
, const LangOptions
&LO
)
5435 for (CFG::const_iterator I
= cfg
->begin(), E
= cfg
->end(); I
!= E
; ++I
) {
5437 for (CFGBlock::const_iterator BI
= (*I
)->begin(), BEnd
= (*I
)->end() ;
5438 BI
!= BEnd
; ++BI
, ++j
) {
5439 if (std::optional
<CFGStmt
> SE
= BI
->getAs
<CFGStmt
>()) {
5440 const Stmt
*stmt
= SE
->getStmt();
5441 std::pair
<unsigned, unsigned> P((*I
)->getBlockID(), j
);
5444 switch (stmt
->getStmtClass()) {
5445 case Stmt::DeclStmtClass
:
5446 DeclMap
[cast
<DeclStmt
>(stmt
)->getSingleDecl()] = P
;
5448 case Stmt::IfStmtClass
: {
5449 const VarDecl
*var
= cast
<IfStmt
>(stmt
)->getConditionVariable();
5454 case Stmt::ForStmtClass
: {
5455 const VarDecl
*var
= cast
<ForStmt
>(stmt
)->getConditionVariable();
5460 case Stmt::WhileStmtClass
: {
5461 const VarDecl
*var
=
5462 cast
<WhileStmt
>(stmt
)->getConditionVariable();
5467 case Stmt::SwitchStmtClass
: {
5468 const VarDecl
*var
=
5469 cast
<SwitchStmt
>(stmt
)->getConditionVariable();
5474 case Stmt::CXXCatchStmtClass
: {
5475 const VarDecl
*var
=
5476 cast
<CXXCatchStmt
>(stmt
)->getExceptionDecl();
5489 ~StmtPrinterHelper() override
= default;
5491 const LangOptions
&getLangOpts() const { return LangOpts
; }
5492 void setBlockID(signed i
) { currentBlock
= i
; }
5493 void setStmtID(unsigned i
) { currStmt
= i
; }
5495 bool handledStmt(Stmt
*S
, raw_ostream
&OS
) override
{
5496 StmtMapTy::iterator I
= StmtMap
.find(S
);
5498 if (I
== StmtMap
.end())
5501 if (currentBlock
>= 0 && I
->second
.first
== (unsigned) currentBlock
5502 && I
->second
.second
== currStmt
) {
5506 OS
<< "[B" << I
->second
.first
<< "." << I
->second
.second
<< "]";
5510 bool handleDecl(const Decl
*D
, raw_ostream
&OS
) {
5511 DeclMapTy::iterator I
= DeclMap
.find(D
);
5513 if (I
== DeclMap
.end())
5516 if (currentBlock
>= 0 && I
->second
.first
== (unsigned) currentBlock
5517 && I
->second
.second
== currStmt
) {
5521 OS
<< "[B" << I
->second
.first
<< "." << I
->second
.second
<< "]";
5526 class CFGBlockTerminatorPrint
5527 : public StmtVisitor
<CFGBlockTerminatorPrint
,void> {
5529 StmtPrinterHelper
* Helper
;
5530 PrintingPolicy Policy
;
5533 CFGBlockTerminatorPrint(raw_ostream
&os
, StmtPrinterHelper
* helper
,
5534 const PrintingPolicy
&Policy
)
5535 : OS(os
), Helper(helper
), Policy(Policy
) {
5536 this->Policy
.IncludeNewlines
= false;
5539 void VisitIfStmt(IfStmt
*I
) {
5541 if (Stmt
*C
= I
->getCond())
5542 C
->printPretty(OS
, Helper
, Policy
);
5546 void VisitStmt(Stmt
*Terminator
) {
5547 Terminator
->printPretty(OS
, Helper
, Policy
);
5550 void VisitDeclStmt(DeclStmt
*DS
) {
5551 VarDecl
*VD
= cast
<VarDecl
>(DS
->getSingleDecl());
5552 OS
<< "static init " << VD
->getName();
5555 void VisitForStmt(ForStmt
*F
) {
5560 if (Stmt
*C
= F
->getCond())
5561 C
->printPretty(OS
, Helper
, Policy
);
5568 void VisitWhileStmt(WhileStmt
*W
) {
5570 if (Stmt
*C
= W
->getCond())
5571 C
->printPretty(OS
, Helper
, Policy
);
5574 void VisitDoStmt(DoStmt
*D
) {
5575 OS
<< "do ... while ";
5576 if (Stmt
*C
= D
->getCond())
5577 C
->printPretty(OS
, Helper
, Policy
);
5580 void VisitSwitchStmt(SwitchStmt
*Terminator
) {
5582 Terminator
->getCond()->printPretty(OS
, Helper
, Policy
);
5585 void VisitCXXTryStmt(CXXTryStmt
*) { OS
<< "try ..."; }
5587 void VisitObjCAtTryStmt(ObjCAtTryStmt
*) { OS
<< "@try ..."; }
5589 void VisitSEHTryStmt(SEHTryStmt
*CS
) { OS
<< "__try ..."; }
5591 void VisitAbstractConditionalOperator(AbstractConditionalOperator
* C
) {
5592 if (Stmt
*Cond
= C
->getCond())
5593 Cond
->printPretty(OS
, Helper
, Policy
);
5594 OS
<< " ? ... : ...";
5597 void VisitChooseExpr(ChooseExpr
*C
) {
5598 OS
<< "__builtin_choose_expr( ";
5599 if (Stmt
*Cond
= C
->getCond())
5600 Cond
->printPretty(OS
, Helper
, Policy
);
5604 void VisitIndirectGotoStmt(IndirectGotoStmt
*I
) {
5606 if (Stmt
*T
= I
->getTarget())
5607 T
->printPretty(OS
, Helper
, Policy
);
5610 void VisitBinaryOperator(BinaryOperator
* B
) {
5611 if (!B
->isLogicalOp()) {
5617 B
->getLHS()->printPretty(OS
, Helper
, Policy
);
5619 switch (B
->getOpcode()) {
5627 llvm_unreachable("Invalid logical operator.");
5631 void VisitExpr(Expr
*E
) {
5632 E
->printPretty(OS
, Helper
, Policy
);
5636 void print(CFGTerminator T
) {
5637 switch (T
.getKind()) {
5638 case CFGTerminator::StmtBranch
:
5641 case CFGTerminator::TemporaryDtorsBranch
:
5642 OS
<< "(Temp Dtor) ";
5645 case CFGTerminator::VirtualBaseBranch
:
5646 OS
<< "(See if most derived ctor has already initialized vbases)";
5654 static void print_initializer(raw_ostream
&OS
, StmtPrinterHelper
&Helper
,
5655 const CXXCtorInitializer
*I
) {
5656 if (I
->isBaseInitializer())
5657 OS
<< I
->getBaseClass()->getAsCXXRecordDecl()->getName();
5658 else if (I
->isDelegatingInitializer())
5659 OS
<< I
->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5661 OS
<< I
->getAnyMember()->getName();
5663 if (Expr
*IE
= I
->getInit())
5664 IE
->printPretty(OS
, &Helper
, PrintingPolicy(Helper
.getLangOpts()));
5667 if (I
->isBaseInitializer())
5668 OS
<< " (Base initializer)";
5669 else if (I
->isDelegatingInitializer())
5670 OS
<< " (Delegating initializer)";
5672 OS
<< " (Member initializer)";
5675 static void print_construction_context(raw_ostream
&OS
,
5676 StmtPrinterHelper
&Helper
,
5677 const ConstructionContext
*CC
) {
5678 SmallVector
<const Stmt
*, 3> Stmts
;
5679 switch (CC
->getKind()) {
5680 case ConstructionContext::SimpleConstructorInitializerKind
: {
5682 const auto *SICC
= cast
<SimpleConstructorInitializerConstructionContext
>(CC
);
5683 print_initializer(OS
, Helper
, SICC
->getCXXCtorInitializer());
5686 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind
: {
5689 cast
<CXX17ElidedCopyConstructorInitializerConstructionContext
>(CC
);
5690 print_initializer(OS
, Helper
, CICC
->getCXXCtorInitializer());
5691 Stmts
.push_back(CICC
->getCXXBindTemporaryExpr());
5694 case ConstructionContext::SimpleVariableKind
: {
5695 const auto *SDSCC
= cast
<SimpleVariableConstructionContext
>(CC
);
5696 Stmts
.push_back(SDSCC
->getDeclStmt());
5699 case ConstructionContext::CXX17ElidedCopyVariableKind
: {
5700 const auto *CDSCC
= cast
<CXX17ElidedCopyVariableConstructionContext
>(CC
);
5701 Stmts
.push_back(CDSCC
->getDeclStmt());
5702 Stmts
.push_back(CDSCC
->getCXXBindTemporaryExpr());
5705 case ConstructionContext::NewAllocatedObjectKind
: {
5706 const auto *NECC
= cast
<NewAllocatedObjectConstructionContext
>(CC
);
5707 Stmts
.push_back(NECC
->getCXXNewExpr());
5710 case ConstructionContext::SimpleReturnedValueKind
: {
5711 const auto *RSCC
= cast
<SimpleReturnedValueConstructionContext
>(CC
);
5712 Stmts
.push_back(RSCC
->getReturnStmt());
5715 case ConstructionContext::CXX17ElidedCopyReturnedValueKind
: {
5717 cast
<CXX17ElidedCopyReturnedValueConstructionContext
>(CC
);
5718 Stmts
.push_back(RSCC
->getReturnStmt());
5719 Stmts
.push_back(RSCC
->getCXXBindTemporaryExpr());
5722 case ConstructionContext::SimpleTemporaryObjectKind
: {
5723 const auto *TOCC
= cast
<SimpleTemporaryObjectConstructionContext
>(CC
);
5724 Stmts
.push_back(TOCC
->getCXXBindTemporaryExpr());
5725 Stmts
.push_back(TOCC
->getMaterializedTemporaryExpr());
5728 case ConstructionContext::ElidedTemporaryObjectKind
: {
5729 const auto *TOCC
= cast
<ElidedTemporaryObjectConstructionContext
>(CC
);
5730 Stmts
.push_back(TOCC
->getCXXBindTemporaryExpr());
5731 Stmts
.push_back(TOCC
->getMaterializedTemporaryExpr());
5732 Stmts
.push_back(TOCC
->getConstructorAfterElision());
5735 case ConstructionContext::LambdaCaptureKind
: {
5736 const auto *LCC
= cast
<LambdaCaptureConstructionContext
>(CC
);
5737 Helper
.handledStmt(const_cast<LambdaExpr
*>(LCC
->getLambdaExpr()), OS
);
5738 OS
<< "+" << LCC
->getIndex();
5741 case ConstructionContext::ArgumentKind
: {
5742 const auto *ACC
= cast
<ArgumentConstructionContext
>(CC
);
5743 if (const Stmt
*BTE
= ACC
->getCXXBindTemporaryExpr()) {
5745 Helper
.handledStmt(const_cast<Stmt
*>(BTE
), OS
);
5748 Helper
.handledStmt(const_cast<Expr
*>(ACC
->getCallLikeExpr()), OS
);
5749 OS
<< "+" << ACC
->getIndex();
5756 Helper
.handledStmt(const_cast<Stmt
*>(I
), OS
);
5760 static void print_elem(raw_ostream
&OS
, StmtPrinterHelper
&Helper
,
5761 const CFGElement
&E
);
5763 void CFGElement::dumpToStream(llvm::raw_ostream
&OS
) const {
5764 LangOptions LangOpts
;
5765 StmtPrinterHelper
Helper(nullptr, LangOpts
);
5766 print_elem(OS
, Helper
, *this);
5769 static void print_elem(raw_ostream
&OS
, StmtPrinterHelper
&Helper
,
5770 const CFGElement
&E
) {
5771 switch (E
.getKind()) {
5772 case CFGElement::Kind::Statement
:
5773 case CFGElement::Kind::CXXRecordTypedCall
:
5774 case CFGElement::Kind::Constructor
: {
5775 CFGStmt CS
= E
.castAs
<CFGStmt
>();
5776 const Stmt
*S
= CS
.getStmt();
5777 assert(S
!= nullptr && "Expecting non-null Stmt");
5779 // special printing for statement-expressions.
5780 if (const StmtExpr
*SE
= dyn_cast
<StmtExpr
>(S
)) {
5781 const CompoundStmt
*Sub
= SE
->getSubStmt();
5783 auto Children
= Sub
->children();
5784 if (Children
.begin() != Children
.end()) {
5786 Helper
.handledStmt(*SE
->getSubStmt()->body_rbegin(),OS
);
5791 // special printing for comma expressions.
5792 if (const BinaryOperator
* B
= dyn_cast
<BinaryOperator
>(S
)) {
5793 if (B
->getOpcode() == BO_Comma
) {
5795 Helper
.handledStmt(B
->getRHS(),OS
);
5800 S
->printPretty(OS
, &Helper
, PrintingPolicy(Helper
.getLangOpts()));
5802 if (auto VTC
= E
.getAs
<CFGCXXRecordTypedCall
>()) {
5803 if (isa
<CXXOperatorCallExpr
>(S
))
5804 OS
<< " (OperatorCall)";
5805 OS
<< " (CXXRecordTypedCall";
5806 print_construction_context(OS
, Helper
, VTC
->getConstructionContext());
5808 } else if (isa
<CXXOperatorCallExpr
>(S
)) {
5809 OS
<< " (OperatorCall)";
5810 } else if (isa
<CXXBindTemporaryExpr
>(S
)) {
5811 OS
<< " (BindTemporary)";
5812 } else if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(S
)) {
5813 OS
<< " (CXXConstructExpr";
5814 if (std::optional
<CFGConstructor
> CE
= E
.getAs
<CFGConstructor
>()) {
5815 print_construction_context(OS
, Helper
, CE
->getConstructionContext());
5817 OS
<< ", " << CCE
->getType() << ")";
5818 } else if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(S
)) {
5819 OS
<< " (" << CE
->getStmtClassName() << ", " << CE
->getCastKindName()
5820 << ", " << CE
->getType() << ")";
5823 // Expressions need a newline.
5830 case CFGElement::Kind::Initializer
:
5831 print_initializer(OS
, Helper
, E
.castAs
<CFGInitializer
>().getInitializer());
5835 case CFGElement::Kind::AutomaticObjectDtor
: {
5836 CFGAutomaticObjDtor DE
= E
.castAs
<CFGAutomaticObjDtor
>();
5837 const VarDecl
*VD
= DE
.getVarDecl();
5838 Helper
.handleDecl(VD
, OS
);
5840 QualType T
= VD
->getType();
5841 if (T
->isReferenceType())
5842 T
= getReferenceInitTemporaryType(VD
->getInit(), nullptr);
5845 T
.getUnqualifiedType().print(OS
, PrintingPolicy(Helper
.getLangOpts()));
5846 OS
<< "() (Implicit destructor)\n";
5850 case CFGElement::Kind::CleanupFunction
:
5851 OS
<< "CleanupFunction ("
5852 << E
.castAs
<CFGCleanupFunction
>().getFunctionDecl()->getName() << ")\n";
5855 case CFGElement::Kind::LifetimeEnds
:
5856 Helper
.handleDecl(E
.castAs
<CFGLifetimeEnds
>().getVarDecl(), OS
);
5857 OS
<< " (Lifetime ends)\n";
5860 case CFGElement::Kind::LoopExit
:
5861 OS
<< E
.castAs
<CFGLoopExit
>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
5864 case CFGElement::Kind::ScopeBegin
:
5865 OS
<< "CFGScopeBegin(";
5866 if (const VarDecl
*VD
= E
.castAs
<CFGScopeBegin
>().getVarDecl())
5867 OS
<< VD
->getQualifiedNameAsString();
5871 case CFGElement::Kind::ScopeEnd
:
5872 OS
<< "CFGScopeEnd(";
5873 if (const VarDecl
*VD
= E
.castAs
<CFGScopeEnd
>().getVarDecl())
5874 OS
<< VD
->getQualifiedNameAsString();
5878 case CFGElement::Kind::NewAllocator
:
5879 OS
<< "CFGNewAllocator(";
5880 if (const CXXNewExpr
*AllocExpr
= E
.castAs
<CFGNewAllocator
>().getAllocatorExpr())
5881 AllocExpr
->getType().print(OS
, PrintingPolicy(Helper
.getLangOpts()));
5885 case CFGElement::Kind::DeleteDtor
: {
5886 CFGDeleteDtor DE
= E
.castAs
<CFGDeleteDtor
>();
5887 const CXXRecordDecl
*RD
= DE
.getCXXRecordDecl();
5890 CXXDeleteExpr
*DelExpr
=
5891 const_cast<CXXDeleteExpr
*>(DE
.getDeleteExpr());
5892 Helper
.handledStmt(cast
<Stmt
>(DelExpr
->getArgument()), OS
);
5893 OS
<< "->~" << RD
->getName().str() << "()";
5894 OS
<< " (Implicit destructor)\n";
5898 case CFGElement::Kind::BaseDtor
: {
5899 const CXXBaseSpecifier
*BS
= E
.castAs
<CFGBaseDtor
>().getBaseSpecifier();
5900 OS
<< "~" << BS
->getType()->getAsCXXRecordDecl()->getName() << "()";
5901 OS
<< " (Base object destructor)\n";
5905 case CFGElement::Kind::MemberDtor
: {
5906 const FieldDecl
*FD
= E
.castAs
<CFGMemberDtor
>().getFieldDecl();
5907 const Type
*T
= FD
->getType()->getBaseElementTypeUnsafe();
5908 OS
<< "this->" << FD
->getName();
5909 OS
<< ".~" << T
->getAsCXXRecordDecl()->getName() << "()";
5910 OS
<< " (Member object destructor)\n";
5914 case CFGElement::Kind::TemporaryDtor
: {
5915 const CXXBindTemporaryExpr
*BT
=
5916 E
.castAs
<CFGTemporaryDtor
>().getBindTemporaryExpr();
5918 BT
->getType().print(OS
, PrintingPolicy(Helper
.getLangOpts()));
5919 OS
<< "() (Temporary object destructor)\n";
5925 static void print_block(raw_ostream
&OS
, const CFG
* cfg
,
5927 StmtPrinterHelper
&Helper
, bool print_edges
,
5929 Helper
.setBlockID(B
.getBlockID());
5931 // Print the header.
5933 OS
.changeColor(raw_ostream::YELLOW
, true);
5935 OS
<< "\n [B" << B
.getBlockID();
5937 if (&B
== &cfg
->getEntry())
5938 OS
<< " (ENTRY)]\n";
5939 else if (&B
== &cfg
->getExit())
5941 else if (&B
== cfg
->getIndirectGotoBlock())
5942 OS
<< " (INDIRECT GOTO DISPATCH)]\n";
5943 else if (B
.hasNoReturnElement())
5944 OS
<< " (NORETURN)]\n";
5951 // Print the label of this block.
5952 if (Stmt
*Label
= const_cast<Stmt
*>(B
.getLabel())) {
5956 if (LabelStmt
*L
= dyn_cast
<LabelStmt
>(Label
))
5958 else if (CaseStmt
*C
= dyn_cast
<CaseStmt
>(Label
)) {
5960 if (const Expr
*LHS
= C
->getLHS())
5961 LHS
->printPretty(OS
, &Helper
, PrintingPolicy(Helper
.getLangOpts()));
5962 if (const Expr
*RHS
= C
->getRHS()) {
5964 RHS
->printPretty(OS
, &Helper
, PrintingPolicy(Helper
.getLangOpts()));
5966 } else if (isa
<DefaultStmt
>(Label
))
5968 else if (CXXCatchStmt
*CS
= dyn_cast
<CXXCatchStmt
>(Label
)) {
5970 if (const VarDecl
*ED
= CS
->getExceptionDecl())
5971 ED
->print(OS
, PrintingPolicy(Helper
.getLangOpts()), 0);
5975 } else if (ObjCAtCatchStmt
*CS
= dyn_cast
<ObjCAtCatchStmt
>(Label
)) {
5977 if (const VarDecl
*PD
= CS
->getCatchParamDecl())
5978 PD
->print(OS
, PrintingPolicy(Helper
.getLangOpts()), 0);
5982 } else if (SEHExceptStmt
*ES
= dyn_cast
<SEHExceptStmt
>(Label
)) {
5984 ES
->getFilterExpr()->printPretty(OS
, &Helper
,
5985 PrintingPolicy(Helper
.getLangOpts()), 0);
5988 llvm_unreachable("Invalid label statement in CFGBlock.");
5993 // Iterate through the statements in the block and print them.
5996 for (CFGBlock::const_iterator I
= B
.begin(), E
= B
.end() ;
5997 I
!= E
; ++I
, ++j
) {
5998 // Print the statement # in the basic block and the statement itself.
6002 OS
<< llvm::format("%3d", j
) << ": ";
6004 Helper
.setStmtID(j
);
6006 print_elem(OS
, Helper
, *I
);
6009 // Print the terminator of this block.
6010 if (B
.getTerminator().isValid()) {
6012 OS
.changeColor(raw_ostream::GREEN
);
6016 Helper
.setBlockID(-1);
6018 PrintingPolicy
PP(Helper
.getLangOpts());
6019 CFGBlockTerminatorPrint
TPrinter(OS
, &Helper
, PP
);
6020 TPrinter
.print(B
.getTerminator());
6028 // Print the predecessors of this block.
6029 if (!B
.pred_empty()) {
6030 const raw_ostream::Colors Color
= raw_ostream::BLUE
;
6032 OS
.changeColor(Color
);
6036 OS
<< '(' << B
.pred_size() << "):";
6040 OS
.changeColor(Color
);
6042 for (CFGBlock::const_pred_iterator I
= B
.pred_begin(), E
= B
.pred_end();
6048 bool Reachable
= true;
6051 B
= I
->getPossiblyUnreachableBlock();
6054 OS
<< " B" << B
->getBlockID();
6056 OS
<< "(Unreachable)";
6065 // Print the successors of this block.
6066 if (!B
.succ_empty()) {
6067 const raw_ostream::Colors Color
= raw_ostream::MAGENTA
;
6069 OS
.changeColor(Color
);
6073 OS
<< '(' << B
.succ_size() << "):";
6077 OS
.changeColor(Color
);
6079 for (CFGBlock::const_succ_iterator I
= B
.succ_begin(), E
= B
.succ_end();
6086 bool Reachable
= true;
6089 B
= I
->getPossiblyUnreachableBlock();
6093 OS
<< " B" << B
->getBlockID();
6095 OS
<< "(Unreachable)";
6109 /// dump - A simple pretty printer of a CFG that outputs to stderr.
6110 void CFG::dump(const LangOptions
&LO
, bool ShowColors
) const {
6111 print(llvm::errs(), LO
, ShowColors
);
6114 /// print - A simple pretty printer of a CFG that outputs to an ostream.
6115 void CFG::print(raw_ostream
&OS
, const LangOptions
&LO
, bool ShowColors
) const {
6116 StmtPrinterHelper
Helper(this, LO
);
6118 // Print the entry block.
6119 print_block(OS
, this, getEntry(), Helper
, true, ShowColors
);
6121 // Iterate through the CFGBlocks and print them one by one.
6122 for (const_iterator I
= Blocks
.begin(), E
= Blocks
.end() ; I
!= E
; ++I
) {
6123 // Skip the entry block, because we already printed it.
6124 if (&(**I
) == &getEntry() || &(**I
) == &getExit())
6127 print_block(OS
, this, **I
, Helper
, true, ShowColors
);
6130 // Print the exit block.
6131 print_block(OS
, this, getExit(), Helper
, true, ShowColors
);
6136 size_t CFGBlock::getIndexInCFG() const {
6137 return llvm::find(*getParent(), this) - getParent()->begin();
6140 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
6141 void CFGBlock::dump(const CFG
* cfg
, const LangOptions
&LO
,
6142 bool ShowColors
) const {
6143 print(llvm::errs(), cfg
, LO
, ShowColors
);
6146 LLVM_DUMP_METHOD
void CFGBlock::dump() const {
6147 dump(getParent(), LangOptions(), false);
6150 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
6151 /// Generally this will only be called from CFG::print.
6152 void CFGBlock::print(raw_ostream
&OS
, const CFG
* cfg
,
6153 const LangOptions
&LO
, bool ShowColors
) const {
6154 StmtPrinterHelper
Helper(cfg
, LO
);
6155 print_block(OS
, cfg
, *this, Helper
, true, ShowColors
);
6159 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
6160 void CFGBlock::printTerminator(raw_ostream
&OS
,
6161 const LangOptions
&LO
) const {
6162 CFGBlockTerminatorPrint
TPrinter(OS
, nullptr, PrintingPolicy(LO
));
6163 TPrinter
.print(getTerminator());
6166 /// printTerminatorJson - Pretty-prints the terminator in JSON format.
6167 void CFGBlock::printTerminatorJson(raw_ostream
&Out
, const LangOptions
&LO
,
6168 bool AddQuotes
) const {
6170 llvm::raw_string_ostream
TempOut(Buf
);
6172 printTerminator(TempOut
, LO
);
6174 Out
<< JsonFormat(Buf
, AddQuotes
);
6177 // Returns true if by simply looking at the block, we can be sure that it
6178 // results in a sink during analysis. This is useful to know when the analysis
6179 // was interrupted, and we try to figure out if it would sink eventually.
6180 // There may be many more reasons why a sink would appear during analysis
6181 // (eg. checkers may generate sinks arbitrarily), but here we only consider
6182 // sinks that would be obvious by looking at the CFG.
6183 static bool isImmediateSinkBlock(const CFGBlock
*Blk
) {
6184 if (Blk
->hasNoReturnElement())
6187 // FIXME: Throw-expressions are currently generating sinks during analysis:
6188 // they're not supported yet, and also often used for actually terminating
6189 // the program. So we should treat them as sinks in this analysis as well,
6190 // at least for now, but once we have better support for exceptions,
6191 // we'd need to carefully handle the case when the throw is being
6192 // immediately caught.
6193 if (llvm::any_of(*Blk
, [](const CFGElement
&Elm
) {
6194 if (std::optional
<CFGStmt
> StmtElm
= Elm
.getAs
<CFGStmt
>())
6195 if (isa
<CXXThrowExpr
>(StmtElm
->getStmt()))
6204 bool CFGBlock::isInevitablySinking() const {
6205 const CFG
&Cfg
= *getParent();
6207 const CFGBlock
*StartBlk
= this;
6208 if (isImmediateSinkBlock(StartBlk
))
6211 llvm::SmallVector
<const CFGBlock
*, 32> DFSWorkList
;
6212 llvm::SmallPtrSet
<const CFGBlock
*, 32> Visited
;
6214 DFSWorkList
.push_back(StartBlk
);
6215 while (!DFSWorkList
.empty()) {
6216 const CFGBlock
*Blk
= DFSWorkList
.back();
6217 DFSWorkList
.pop_back();
6218 Visited
.insert(Blk
);
6220 // If at least one path reaches the CFG exit, it means that control is
6221 // returned to the caller. For now, say that we are not sure what
6222 // happens next. If necessary, this can be improved to analyze
6223 // the parent StackFrameContext's call site in a similar manner.
6224 if (Blk
== &Cfg
.getExit())
6227 for (const auto &Succ
: Blk
->succs()) {
6228 if (const CFGBlock
*SuccBlk
= Succ
.getReachableBlock()) {
6229 if (!isImmediateSinkBlock(SuccBlk
) && !Visited
.count(SuccBlk
)) {
6230 // If the block has reachable child blocks that aren't no-return,
6231 // add them to the worklist.
6232 DFSWorkList
.push_back(SuccBlk
);
6238 // Nothing reached the exit. It can only mean one thing: there's no return.
6242 const Expr
*CFGBlock::getLastCondition() const {
6243 // If the terminator is a temporary dtor or a virtual base, etc, we can't
6244 // retrieve a meaningful condition, bail out.
6245 if (Terminator
.getKind() != CFGTerminator::StmtBranch
)
6248 // Also, if this method was called on a block that doesn't have 2 successors,
6249 // this block doesn't have retrievable condition.
6250 if (succ_size() < 2)
6253 // FIXME: Is there a better condition expression we can return in this case?
6257 auto StmtElem
= rbegin()->getAs
<CFGStmt
>();
6261 const Stmt
*Cond
= StmtElem
->getStmt();
6262 if (isa
<ObjCForCollectionStmt
>(Cond
) || isa
<DeclStmt
>(Cond
))
6265 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
6267 return cast
<Expr
>(Cond
)->IgnoreParens();
6270 Stmt
*CFGBlock::getTerminatorCondition(bool StripParens
) {
6271 Stmt
*Terminator
= getTerminatorStmt();
6277 switch (Terminator
->getStmtClass()) {
6281 case Stmt::CXXForRangeStmtClass
:
6282 E
= cast
<CXXForRangeStmt
>(Terminator
)->getCond();
6285 case Stmt::ForStmtClass
:
6286 E
= cast
<ForStmt
>(Terminator
)->getCond();
6289 case Stmt::WhileStmtClass
:
6290 E
= cast
<WhileStmt
>(Terminator
)->getCond();
6293 case Stmt::DoStmtClass
:
6294 E
= cast
<DoStmt
>(Terminator
)->getCond();
6297 case Stmt::IfStmtClass
:
6298 E
= cast
<IfStmt
>(Terminator
)->getCond();
6301 case Stmt::ChooseExprClass
:
6302 E
= cast
<ChooseExpr
>(Terminator
)->getCond();
6305 case Stmt::IndirectGotoStmtClass
:
6306 E
= cast
<IndirectGotoStmt
>(Terminator
)->getTarget();
6309 case Stmt::SwitchStmtClass
:
6310 E
= cast
<SwitchStmt
>(Terminator
)->getCond();
6313 case Stmt::BinaryConditionalOperatorClass
:
6314 E
= cast
<BinaryConditionalOperator
>(Terminator
)->getCond();
6317 case Stmt::ConditionalOperatorClass
:
6318 E
= cast
<ConditionalOperator
>(Terminator
)->getCond();
6321 case Stmt::BinaryOperatorClass
: // '&&' and '||'
6322 E
= cast
<BinaryOperator
>(Terminator
)->getLHS();
6325 case Stmt::ObjCForCollectionStmtClass
:
6332 return E
? E
->IgnoreParens() : nullptr;
6335 //===----------------------------------------------------------------------===//
6336 // CFG Graphviz Visualization
6337 //===----------------------------------------------------------------------===//
6339 static StmtPrinterHelper
*GraphHelper
;
6341 void CFG::viewCFG(const LangOptions
&LO
) const {
6342 StmtPrinterHelper
H(this, LO
);
6344 llvm::ViewGraph(this,"CFG");
6345 GraphHelper
= nullptr;
6351 struct DOTGraphTraits
<const CFG
*> : public DefaultDOTGraphTraits
{
6352 DOTGraphTraits(bool isSimple
= false) : DefaultDOTGraphTraits(isSimple
) {}
6354 static std::string
getNodeLabel(const CFGBlock
*Node
, const CFG
*Graph
) {
6356 llvm::raw_string_ostream
Out(OutStr
);
6357 print_block(Out
,Graph
, *Node
, *GraphHelper
, false, false);
6359 if (OutStr
[0] == '\n') OutStr
.erase(OutStr
.begin());
6361 // Process string output to make it nicer...
6362 for (unsigned i
= 0; i
!= OutStr
.length(); ++i
)
6363 if (OutStr
[i
] == '\n') { // Left justify
6365 OutStr
.insert(OutStr
.begin()+i
+1, 'l');