[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Analysis / CFG.cpp
blobb82f9010a83f771e8ff39ce6c69ee713cf5eae62
1 //===- CFG.cpp - Classes for representing and building CFGs ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the CFG and CFGBuilder classes for representing and
10 // building Control-Flow Graphs (CFGs) from ASTs.
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"
56 #include <cassert>
57 #include <memory>
58 #include <optional>
59 #include <string>
60 #include <tuple>
61 #include <utility>
62 #include <vector>
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) {
80 // Allow parentheses
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)
86 return false;
87 E = CE->getSubExpr();
90 // Allow negative numbers.
91 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
92 if (UO->getOpcode() != UO_Minus)
93 return false;
94 E = UO->getSubExpr();
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,
102 /// returns nullptr.
103 static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
104 E = E->IgnoreParens();
105 if (IsIntegerLiteralConstantExpr(E))
106 return E;
107 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
108 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
109 return nullptr;
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
116 /// null.
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) {
125 // Flip the operator
126 if (Op == BO_GT)
127 Op = BO_LT;
128 else if (Op == BO_GE)
129 Op = BO_LE;
130 else if (Op == BO_LT)
131 Op = BO_GT;
132 else if (Op == BO_LE)
133 Op = BO_GE;
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
144 /// literals.
146 /// It's an error to pass this arguments that are not either IntegerLiterals
147 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
148 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
149 // User intent isn't clear if they're mixing int literals with enum
150 // constants.
151 if (isa<DeclRefExpr>(E1) != isa<DeclRefExpr>(E2))
152 return false;
154 // Integer literal comparisons, regardless of literal type, are acceptable.
155 if (!isa<DeclRefExpr>(E1))
156 return true;
158 // IntegerLiterals are handled above and only EnumConstantDecls are expected
159 // beyond this point
160 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
161 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
162 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
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));
169 return DC1 == DC2;
172 namespace {
174 class CFGBuilder;
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:
180 /// exp1 || exp2
182 /// When processing the '||' expression, we know that exp1 and exp2
183 /// need to be added as block-level expressions, even though they
184 /// might not normally need to be. AddStmtChoice records this
185 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
186 /// the builder has an option not to add a subexpression as a
187 /// block-level expression.
188 class AddStmtChoice {
189 public:
190 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
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);
203 private:
204 Kind kind;
207 /// LocalScope - Node in tree of local scopes created for C++ implicit
208 /// destructor calls generation. It contains list of automatic variables
209 /// declared in the scope and link to position in previous scope this scope
210 /// began in.
212 /// The process of creating local scopes is as follows:
213 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
214 /// - Before processing statements in scope (e.g. CompoundStmt) create
215 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
216 /// and set CFGBuilder::ScopePos to the end of new scope,
217 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
218 /// at this VarDecl,
219 /// - For every normal (without jump) end of scope add to CFGBlock destructors
220 /// for objects in the current scope,
221 /// - For every jump add to CFGBlock destructors for objects
222 /// between CFGBuilder::ScopePos and local scope position saved for jump
223 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
224 /// jump target position will be on the path to root from CFGBuilder::ScopePos
225 /// (adding any variable that doesn't need constructor to be called to
226 /// LocalScope can break this assumption),
228 class LocalScope {
229 public:
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;
241 public:
242 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
243 /// Incrementing invalid iterator is allowed and will result in invalid
244 /// iterator.
245 const_iterator() = default;
247 /// Create valid iterator. In case when S.Prev is an invalid iterator and
248 /// I is equal to 0, this will create invalid iterator.
249 const_iterator(const LocalScope& S, unsigned I)
250 : Scope(&S), VarIter(I) {
251 // Iterator to "end" of scope is not allowed. Handle it by going up
252 // in scopes tree possibly up to invalid iterator in the root.
253 if (VarIter == 0 && Scope)
254 *this = Scope->Prev;
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++() {
274 if (!Scope)
275 return *this;
277 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
278 --VarIter;
279 if (VarIter == 0)
280 *this = Scope->Prev;
281 return *this;
283 const_iterator operator++(int) {
284 const_iterator P = *this;
285 ++*this;
286 return P;
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; }
306 private:
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.
314 const_iterator Prev;
316 public:
317 /// Constructs empty scope linked to previous scope in specified place.
318 LocalScope(BumpVectorContext ctx, const_iterator P)
319 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
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);
329 } // namespace
331 /// distance - Calculates distance from this to L. L must be reachable from this
332 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
333 /// number of scopes between this and L.
334 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
335 int D = 0;
336 const_iterator F = *this;
337 while (F.Scope != L.Scope) {
338 assert(F != const_iterator() &&
339 "L iterator is not reachable from F iterator.");
340 D += F.VarIter;
341 F = F.Scope->Prev;
343 D += F.VarIter - L.VarIter;
344 return D;
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);
363 return F;
366 llvm::SmallDenseMap<const LocalScope *, unsigned, 4> ScopesOfL;
367 while (true) {
368 ScopesOfL.try_emplace(L.Scope, L.VarIter);
369 if (L == const_iterator())
370 break;
371 L = L.Scope->Prev;
374 while (true) {
375 if (auto LIt = ScopesOfL.find(F.Scope); LIt != ScopesOfL.end()) {
376 // Get common subset of variables in given scope
377 F.VarIter = std::min(F.VarIter, LIt->getSecond());
378 return F;
380 assert(F != const_iterator() &&
381 "L iterator is not reachable from F iterator.");
382 F = F.Scope->Prev;
386 namespace {
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.
404 class TryResult {
405 int X = -1;
407 public:
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; }
415 void negate() {
416 assert(isKnown());
417 X ^= 0x1;
421 } // namespace
423 static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
424 if (!R1.isKnown() || !R2.isKnown())
425 return TryResult();
426 return TryResult(R1.isTrue() && R2.isTrue());
429 namespace {
431 class reverse_children {
432 llvm::SmallVector<Stmt *, 12> childrenBuf;
433 ArrayRef<Stmt *> children;
435 public:
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(); }
444 } // namespace
446 reverse_children::reverse_children(Stmt *S) {
447 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
448 children = CE->getRawSubExprs();
449 return;
451 switch (S->getStmtClass()) {
452 // Note: Fill in this switch with more cases we want to optimize.
453 case Stmt::InitListExprClass: {
454 InitListExpr *IE = cast<InitListExpr>(S);
455 children = llvm::ArrayRef(reinterpret_cast<Stmt **>(IE->getInits()),
456 IE->getNumInits());
457 return;
459 default:
460 break;
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;
470 namespace {
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.
476 /// Example usage:
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.
485 class CFGBuilder {
486 using JumpTarget = BlockScopePosPair;
487 using JumpSource = BlockScopePosPair;
489 ASTContext *Context;
490 std::unique_ptr<CFG> cfg;
492 // Current block.
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>;
515 LabelMapTy LabelMap;
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;
532 bool badCFG = false;
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;
547 public:
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);
557 private:
558 // Visitors to walk an AST and construct the CFG.
559 CFGBlock *VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc);
560 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
561 CFGBlock *VisitAttributedStmt(AttributedStmt *A, AddStmtChoice asc);
562 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
563 CFGBlock *VisitBreakStmt(BreakStmt *B);
564 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
565 CFGBlock *VisitCaseStmt(CaseStmt *C);
566 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
567 CFGBlock *VisitCompoundStmt(CompoundStmt *C, bool ExternallyDestructed);
568 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
569 AddStmtChoice asc);
570 CFGBlock *VisitContinueStmt(ContinueStmt *C);
571 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
572 AddStmtChoice asc);
573 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
574 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
575 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
576 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
577 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
578 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
579 AddStmtChoice asc);
580 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
581 AddStmtChoice asc);
582 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
583 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
584 CFGBlock *VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc);
585 CFGBlock *VisitDeclStmt(DeclStmt *DS);
586 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
587 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
588 CFGBlock *VisitDoStmt(DoStmt *D);
589 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E,
590 AddStmtChoice asc, bool ExternallyDestructed);
591 CFGBlock *VisitForStmt(ForStmt *F);
592 CFGBlock *VisitGotoStmt(GotoStmt *G);
593 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
594 CFGBlock *VisitIfStmt(IfStmt *I);
595 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
596 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
597 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
598 CFGBlock *VisitLabelStmt(LabelStmt *L);
599 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
600 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
601 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
602 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
603 Stmt *Term,
604 CFGBlock *TrueBlock,
605 CFGBlock *FalseBlock);
606 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
607 AddStmtChoice asc);
608 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
609 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
610 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
611 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
612 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
613 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
614 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
615 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
616 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
617 CFGBlock *VisitReturnStmt(Stmt *S);
618 CFGBlock *VisitCoroutineSuspendExpr(CoroutineSuspendExpr *S,
619 AddStmtChoice asc);
620 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
621 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
622 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
623 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
624 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
625 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
626 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
627 AddStmtChoice asc);
628 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
629 CFGBlock *VisitWhileStmt(WhileStmt *W);
630 CFGBlock *VisitArrayInitLoopExpr(ArrayInitLoopExpr *A, AddStmtChoice asc);
632 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd,
633 bool ExternallyDestructed = false);
634 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
635 CFGBlock *VisitChildren(Stmt *S);
636 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
637 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
638 AddStmtChoice asc);
640 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
641 const Stmt *S) {
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
658 /// follows:
659 /// 1. If a subexpression is executed unconditionally, we add the temporary
660 /// destructor calls to the current block.
661 /// 2. If a subexpression is executed conditionally, when we encounter a
662 /// CXXBindTemporaryExpr:
663 /// a) If it is the first temporary destructor call in the subexpression,
664 /// we remember the CXXBindTemporaryExpr and the current block in the
665 /// TempDtorContext; we start a new block, and insert the temporary
666 /// destructor call.
667 /// b) Otherwise, add the temporary destructor call to the current block.
668 /// 3. When we finished visiting a conditionally executed subexpression,
669 /// and we found at least one temporary constructor during the visitation
670 /// (2.a has executed), we insert a decision block that uses the
671 /// CXXBindTemporaryExpr as terminator, and branches to the current block
672 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
673 /// branches to the stored successor.
674 struct TempDtorContext {
675 TempDtorContext() = default;
676 TempDtorContext(TryResult KnownExecuted)
677 : IsConditional(true), KnownExecuted(KnownExecuted) {}
679 /// Returns whether we need to start a new branch for a temporary destructor
680 /// call. This is the case when the temporary destructor is
681 /// conditionally executed, and it is the first one we encounter while
682 /// visiting a subexpression - other temporary destructors at the same level
683 /// will be added to the same block and are executed under the same
684 /// condition.
685 bool needsTempDtorBranch() const {
686 return IsConditional && !TerminatorExpr;
689 /// Remember the successor S of a temporary destructor decision branch for
690 /// the corresponding CXXBindTemporaryExpr E.
691 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
692 Succ = S;
693 TerminatorExpr = E;
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
703 // full expression.
704 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
705 TempDtorContext &Context);
706 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
707 TempDtorContext &Context);
708 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
709 bool ExternallyDestructed,
710 TempDtorContext &Context);
711 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
712 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context);
713 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
714 AbstractConditionalOperator *E, bool ExternallyDestructed,
715 TempDtorContext &Context);
716 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
717 CFGBlock *FalseSucc = nullptr);
719 // NYS == Not Yet Supported
720 CFGBlock *NYS() {
721 badCFG = true;
722 return Block;
725 // Remember to apply the construction context based on the current \p Layer
726 // when constructing the CFG element for \p CE.
727 void consumeConstructionContext(const ConstructionContextLayer *Layer,
728 Expr *E);
730 // Scan \p Child statement to find constructors in it, while keeping in mind
731 // that its parent statement is providing a partial construction context
732 // described by \p Layer. If a constructor is found, it would be assigned
733 // the context based on the layer. If an additional construction context layer
734 // is found, the function recurses into that.
735 void findConstructionContexts(const ConstructionContextLayer *Layer,
736 Stmt *Child);
738 // Scan all arguments of a call expression for a construction context.
739 // These sorts of call expressions don't have a common superclass,
740 // hence strict duck-typing.
741 template <typename CallLikeExpr,
742 typename = std::enable_if_t<
743 std::is_base_of_v<CallExpr, CallLikeExpr> ||
744 std::is_base_of_v<CXXConstructExpr, CallLikeExpr> ||
745 std::is_base_of_v<ObjCMessageExpr, CallLikeExpr>>>
746 void findConstructionContextsForArguments(CallLikeExpr *E) {
747 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
748 Expr *Arg = E->getArg(i);
749 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
750 findConstructionContexts(
751 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
752 ConstructionContextItem(E, i)),
753 Arg);
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(); }
763 CFGBlock *createBlock(bool add_successor = true);
764 CFGBlock *createNoReturnBlock();
766 CFGBlock *addStmt(Stmt *S) {
767 return Visit(S, AddStmtChoice::AlwaysAdd);
770 CFGBlock *addInitializer(CXXCtorInitializer *I);
771 void addLoopExit(const Stmt *LoopStmt);
772 void addAutomaticObjHandling(LocalScope::const_iterator B,
773 LocalScope::const_iterator E, Stmt *S);
774 void addAutomaticObjDestruction(LocalScope::const_iterator B,
775 LocalScope::const_iterator E, Stmt *S);
776 void addScopeExitHandling(LocalScope::const_iterator B,
777 LocalScope::const_iterator E, Stmt *S);
778 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
779 void addScopeChangesHandling(LocalScope::const_iterator SrcPos,
780 LocalScope::const_iterator DstPos,
781 Stmt *S);
782 CFGBlock *createScopeChangesHandlingBlock(LocalScope::const_iterator SrcPos,
783 CFGBlock *SrcBlk,
784 LocalScope::const_iterator DstPost,
785 CFGBlock *DstBlk);
787 // Local scopes creation.
788 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
790 void addLocalScopeForStmt(Stmt *S);
791 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
792 LocalScope* Scope = nullptr);
793 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
795 void addLocalScopeAndDtors(Stmt *S);
797 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
798 if (!BuildOpts.AddRichCXXConstructors)
799 return nullptr;
801 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
802 if (!Layer)
803 return nullptr;
805 cleanupConstructionContext(E);
806 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
807 Layer);
810 // Interface to CFGBlock - adding CFGElements.
812 void appendStmt(CFGBlock *B, const Stmt *S) {
813 if (alwaysAdd(S) && cachedEntry)
814 cachedEntry->second = B;
816 // All block-level expressions should have already been IgnoreParens()ed.
817 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
818 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
821 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
822 if (const ConstructionContext *CC =
823 retrieveAndCleanupConstructionContext(CE)) {
824 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
825 return;
828 // No valid construction context found. Fall back to statement.
829 B->appendStmt(CE, cfg->getBumpVectorContext());
832 void appendCall(CFGBlock *B, CallExpr *CE) {
833 if (alwaysAdd(CE) && cachedEntry)
834 cachedEntry->second = B;
836 if (const ConstructionContext *CC =
837 retrieveAndCleanupConstructionContext(CE)) {
838 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
839 return;
842 // No valid construction context found. Fall back to statement.
843 B->appendStmt(CE, cfg->getBumpVectorContext());
846 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
847 B->appendInitializer(I, cfg->getBumpVectorContext());
850 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
851 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
854 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
855 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
858 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
859 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
862 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
863 if (alwaysAdd(ME) && cachedEntry)
864 cachedEntry->second = B;
866 if (const ConstructionContext *CC =
867 retrieveAndCleanupConstructionContext(ME)) {
868 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
869 return;
872 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
873 cfg->getBumpVectorContext());
876 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
877 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
880 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
881 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
884 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
885 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
888 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
889 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
892 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
893 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
896 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
897 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
898 cfg->getBumpVectorContext());
901 /// Add a reachable successor to a block, with the alternate variant that is
902 /// unreachable.
903 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
904 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
905 cfg->getBumpVectorContext());
908 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
909 if (BuildOpts.AddScopes)
910 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
913 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
914 if (BuildOpts.AddScopes)
915 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
918 /// Find a relational comparison with an expression evaluating to a
919 /// boolean and a constant other than 0 and 1.
920 /// e.g. if ((x < y) == 10)
921 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
922 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
923 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
925 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
926 const Expr *BoolExpr = RHSExpr;
927 bool IntFirst = true;
928 if (!IntLiteral) {
929 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
930 BoolExpr = LHSExpr;
931 IntFirst = false;
934 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
935 return TryResult();
937 llvm::APInt IntValue = IntLiteral->getValue();
938 if ((IntValue == 1) || (IntValue == 0))
939 return TryResult();
941 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
942 !IntValue.isNegative();
944 BinaryOperatorKind Bok = B->getOpcode();
945 if (Bok == BO_GT || Bok == BO_GE) {
946 // Always true for 10 > bool and bool > -1
947 // Always false for -1 > bool and bool > 10
948 return TryResult(IntFirst == IntLarger);
949 } else {
950 // Always true for -1 < bool and bool < 10
951 // Always false for 10 < bool and bool < -1
952 return TryResult(IntFirst != IntLarger);
956 /// Find an incorrect equality comparison. Either with an expression
957 /// evaluating to a boolean and a constant other than 0 and 1.
958 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
959 /// true/false e.q. (x & 8) == 4.
960 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
961 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
962 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
964 std::optional<llvm::APInt> IntLiteral1 =
965 getIntegerLiteralSubexpressionValue(LHSExpr);
966 const Expr *BoolExpr = RHSExpr;
968 if (!IntLiteral1) {
969 IntLiteral1 = getIntegerLiteralSubexpressionValue(RHSExpr);
970 BoolExpr = LHSExpr;
973 if (!IntLiteral1)
974 return TryResult();
976 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
977 if (BitOp && (BitOp->getOpcode() == BO_And ||
978 BitOp->getOpcode() == BO_Or)) {
979 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
980 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
982 std::optional<llvm::APInt> IntLiteral2 =
983 getIntegerLiteralSubexpressionValue(LHSExpr2);
985 if (!IntLiteral2)
986 IntLiteral2 = getIntegerLiteralSubexpressionValue(RHSExpr2);
988 if (!IntLiteral2)
989 return TryResult();
991 if ((BitOp->getOpcode() == BO_And &&
992 (*IntLiteral2 & *IntLiteral1) != *IntLiteral1) ||
993 (BitOp->getOpcode() == BO_Or &&
994 (*IntLiteral2 | *IntLiteral1) != *IntLiteral1)) {
995 if (BuildOpts.Observer)
996 BuildOpts.Observer->compareBitwiseEquality(B,
997 B->getOpcode() != BO_EQ);
998 return TryResult(B->getOpcode() != BO_EQ);
1000 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
1001 if ((*IntLiteral1 == 1) || (*IntLiteral1 == 0)) {
1002 return TryResult();
1004 return TryResult(B->getOpcode() != BO_EQ);
1007 return TryResult();
1010 // Helper function to get an APInt from an expression. Supports expressions
1011 // which are an IntegerLiteral or a UnaryOperator and returns the value with
1012 // all operations performed on it.
1013 // FIXME: it would be good to unify this function with
1014 // IsIntegerLiteralConstantExpr at some point given the similarity between the
1015 // functions.
1016 std::optional<llvm::APInt>
1017 getIntegerLiteralSubexpressionValue(const Expr *E) {
1019 // If unary.
1020 if (const auto *UnOp = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1021 // Get the sub expression of the unary expression and get the Integer
1022 // Literal.
1023 const Expr *SubExpr = UnOp->getSubExpr()->IgnoreParens();
1025 if (const auto *IntLiteral = dyn_cast<IntegerLiteral>(SubExpr)) {
1027 llvm::APInt Value = IntLiteral->getValue();
1029 // Perform the operation manually.
1030 switch (UnOp->getOpcode()) {
1031 case UO_Plus:
1032 return Value;
1033 case UO_Minus:
1034 return -Value;
1035 case UO_Not:
1036 return ~Value;
1037 case UO_LNot:
1038 return llvm::APInt(Context->getTypeSize(Context->IntTy), !Value);
1039 default:
1040 assert(false && "Unexpected unary operator!");
1041 return std::nullopt;
1044 } else if (const auto *IntLiteral =
1045 dyn_cast<IntegerLiteral>(E->IgnoreParens()))
1046 return IntLiteral->getValue();
1048 return std::nullopt;
1051 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
1052 const llvm::APSInt &Value1,
1053 const llvm::APSInt &Value2) {
1054 assert(Value1.isSigned() == Value2.isSigned());
1055 switch (Relation) {
1056 default:
1057 return TryResult();
1058 case BO_EQ:
1059 return TryResult(Value1 == Value2);
1060 case BO_NE:
1061 return TryResult(Value1 != Value2);
1062 case BO_LT:
1063 return TryResult(Value1 < Value2);
1064 case BO_LE:
1065 return TryResult(Value1 <= Value2);
1066 case BO_GT:
1067 return TryResult(Value1 > Value2);
1068 case BO_GE:
1069 return TryResult(Value1 >= Value2);
1073 /// There are two checks handled by this function:
1074 /// 1. Find a law-of-excluded-middle or law-of-noncontradiction expression
1075 /// e.g. if (x || !x), if (x && !x)
1076 /// 2. Find a pair of comparison expressions with or without parentheses
1077 /// with a shared variable and constants and a logical operator between them
1078 /// that always evaluates to either true or false.
1079 /// e.g. if (x != 3 || x != 4)
1080 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1081 assert(B->isLogicalOp());
1082 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
1083 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
1085 auto CheckLogicalOpWithNegatedVariable = [this, B](const Expr *E1,
1086 const Expr *E2) {
1087 if (const auto *Negate = dyn_cast<UnaryOperator>(E1)) {
1088 if (Negate->getOpcode() == UO_LNot &&
1089 Expr::isSameComparisonOperand(Negate->getSubExpr(), E2)) {
1090 bool AlwaysTrue = B->getOpcode() == BO_LOr;
1091 if (BuildOpts.Observer)
1092 BuildOpts.Observer->logicAlwaysTrue(B, AlwaysTrue);
1093 return TryResult(AlwaysTrue);
1096 return TryResult();
1099 TryResult Result = CheckLogicalOpWithNegatedVariable(LHSExpr, RHSExpr);
1100 if (Result.isKnown())
1101 return Result;
1102 Result = CheckLogicalOpWithNegatedVariable(RHSExpr, LHSExpr);
1103 if (Result.isKnown())
1104 return Result;
1106 const auto *LHS = dyn_cast<BinaryOperator>(LHSExpr);
1107 const auto *RHS = dyn_cast<BinaryOperator>(RHSExpr);
1108 if (!LHS || !RHS)
1109 return {};
1111 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
1112 return {};
1114 const Expr *DeclExpr1;
1115 const Expr *NumExpr1;
1116 BinaryOperatorKind BO1;
1117 std::tie(DeclExpr1, BO1, NumExpr1) = tryNormalizeBinaryOperator(LHS);
1119 if (!DeclExpr1 || !NumExpr1)
1120 return {};
1122 const Expr *DeclExpr2;
1123 const Expr *NumExpr2;
1124 BinaryOperatorKind BO2;
1125 std::tie(DeclExpr2, BO2, NumExpr2) = tryNormalizeBinaryOperator(RHS);
1127 if (!DeclExpr2 || !NumExpr2)
1128 return {};
1130 // Check that it is the same variable on both sides.
1131 if (!Expr::isSameComparisonOperand(DeclExpr1, DeclExpr2))
1132 return {};
1134 // Make sure the user's intent is clear (e.g. they're comparing against two
1135 // int literals, or two things from the same enum)
1136 if (!areExprTypesCompatible(NumExpr1, NumExpr2))
1137 return {};
1139 Expr::EvalResult L1Result, L2Result;
1140 if (!NumExpr1->EvaluateAsInt(L1Result, *Context) ||
1141 !NumExpr2->EvaluateAsInt(L2Result, *Context))
1142 return {};
1144 llvm::APSInt L1 = L1Result.Val.getInt();
1145 llvm::APSInt L2 = L2Result.Val.getInt();
1147 // Can't compare signed with unsigned or with different bit width.
1148 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
1149 return {};
1151 // Values that will be used to determine if result of logical
1152 // operator is always true/false
1153 const llvm::APSInt Values[] = {
1154 // Value less than both Value1 and Value2
1155 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1156 // L1
1158 // Value between Value1 and Value2
1159 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1160 L1.isUnsigned()),
1161 // L2
1163 // Value greater than both Value1 and Value2
1164 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1167 // Check whether expression is always true/false by evaluating the following
1168 // * variable x is less than the smallest literal.
1169 // * variable x is equal to the smallest literal.
1170 // * Variable x is between smallest and largest literal.
1171 // * Variable x is equal to the largest literal.
1172 // * Variable x is greater than largest literal.
1173 bool AlwaysTrue = true, AlwaysFalse = true;
1174 // Track value of both subexpressions. If either side is always
1175 // true/false, another warning should have already been emitted.
1176 bool LHSAlwaysTrue = true, LHSAlwaysFalse = true;
1177 bool RHSAlwaysTrue = true, RHSAlwaysFalse = true;
1178 for (const llvm::APSInt &Value : Values) {
1179 TryResult Res1, Res2;
1180 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1181 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1183 if (!Res1.isKnown() || !Res2.isKnown())
1184 return {};
1186 if (B->getOpcode() == BO_LAnd) {
1187 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1188 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1189 } else {
1190 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1191 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1194 LHSAlwaysTrue &= Res1.isTrue();
1195 LHSAlwaysFalse &= Res1.isFalse();
1196 RHSAlwaysTrue &= Res2.isTrue();
1197 RHSAlwaysFalse &= Res2.isFalse();
1200 if (AlwaysTrue || AlwaysFalse) {
1201 if (!LHSAlwaysTrue && !LHSAlwaysFalse && !RHSAlwaysTrue &&
1202 !RHSAlwaysFalse && BuildOpts.Observer)
1203 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1204 return TryResult(AlwaysTrue);
1206 return {};
1209 /// A bitwise-or with a non-zero constant always evaluates to true.
1210 TryResult checkIncorrectBitwiseOrOperator(const BinaryOperator *B) {
1211 const Expr *LHSConstant =
1212 tryTransformToIntOrEnumConstant(B->getLHS()->IgnoreParenImpCasts());
1213 const Expr *RHSConstant =
1214 tryTransformToIntOrEnumConstant(B->getRHS()->IgnoreParenImpCasts());
1216 if ((LHSConstant && RHSConstant) || (!LHSConstant && !RHSConstant))
1217 return {};
1219 const Expr *Constant = LHSConstant ? LHSConstant : RHSConstant;
1221 Expr::EvalResult Result;
1222 if (!Constant->EvaluateAsInt(Result, *Context))
1223 return {};
1225 if (Result.Val.getInt() == 0)
1226 return {};
1228 if (BuildOpts.Observer)
1229 BuildOpts.Observer->compareBitwiseOr(B);
1231 return TryResult(true);
1234 /// Try and evaluate an expression to an integer constant.
1235 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1236 if (!BuildOpts.PruneTriviallyFalseEdges)
1237 return false;
1238 return !S->isTypeDependent() &&
1239 !S->isValueDependent() &&
1240 S->EvaluateAsRValue(outResult, *Context);
1243 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
1244 /// if we can evaluate to a known value, otherwise return -1.
1245 TryResult tryEvaluateBool(Expr *S) {
1246 if (!BuildOpts.PruneTriviallyFalseEdges ||
1247 S->isTypeDependent() || S->isValueDependent())
1248 return {};
1250 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1251 if (Bop->isLogicalOp() || Bop->isEqualityOp()) {
1252 // Check the cache first.
1253 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1254 if (I != CachedBoolEvals.end())
1255 return I->second; // already in map;
1257 // Retrieve result at first, or the map might be updated.
1258 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1259 CachedBoolEvals[S] = Result; // update or insert
1260 return Result;
1262 else {
1263 switch (Bop->getOpcode()) {
1264 default: break;
1265 // For 'x & 0' and 'x * 0', we can determine that
1266 // the value is always false.
1267 case BO_Mul:
1268 case BO_And: {
1269 // If either operand is zero, we know the value
1270 // must be false.
1271 Expr::EvalResult LHSResult;
1272 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1273 llvm::APSInt IntVal = LHSResult.Val.getInt();
1274 if (!IntVal.getBoolValue()) {
1275 return TryResult(false);
1278 Expr::EvalResult RHSResult;
1279 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1280 llvm::APSInt IntVal = RHSResult.Val.getInt();
1281 if (!IntVal.getBoolValue()) {
1282 return TryResult(false);
1286 break;
1291 return evaluateAsBooleanConditionNoCache(S);
1294 /// Evaluate as boolean \param E without using the cache.
1295 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1296 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1297 if (Bop->isLogicalOp()) {
1298 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1299 if (LHS.isKnown()) {
1300 // We were able to evaluate the LHS, see if we can get away with not
1301 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1302 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1303 return LHS.isTrue();
1305 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1306 if (RHS.isKnown()) {
1307 if (Bop->getOpcode() == BO_LOr)
1308 return LHS.isTrue() || RHS.isTrue();
1309 else
1310 return LHS.isTrue() && RHS.isTrue();
1312 } else {
1313 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1314 if (RHS.isKnown()) {
1315 // We can't evaluate the LHS; however, sometimes the result
1316 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1317 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1318 return RHS.isTrue();
1319 } else {
1320 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1321 if (BopRes.isKnown())
1322 return BopRes.isTrue();
1326 return {};
1327 } else if (Bop->isEqualityOp()) {
1328 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1329 if (BopRes.isKnown())
1330 return BopRes.isTrue();
1331 } else if (Bop->isRelationalOp()) {
1332 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1333 if (BopRes.isKnown())
1334 return BopRes.isTrue();
1335 } else if (Bop->getOpcode() == BO_Or) {
1336 TryResult BopRes = checkIncorrectBitwiseOrOperator(Bop);
1337 if (BopRes.isKnown())
1338 return BopRes.isTrue();
1342 bool Result;
1343 if (E->EvaluateAsBooleanCondition(Result, *Context))
1344 return Result;
1346 return {};
1349 bool hasTrivialDestructor(VarDecl *VD);
1352 } // namespace
1354 Expr *
1355 clang::extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE) {
1356 if (!AILE)
1357 return nullptr;
1359 Expr *AILEInit = AILE->getSubExpr();
1360 while (const auto *E = dyn_cast<ArrayInitLoopExpr>(AILEInit))
1361 AILEInit = E->getSubExpr();
1363 return AILEInit;
1366 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1367 const Stmt *stmt) const {
1368 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1371 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
1372 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1374 if (!BuildOpts.forcedBlkExprs)
1375 return shouldAdd;
1377 if (lastLookup == stmt) {
1378 if (cachedEntry) {
1379 assert(cachedEntry->first == stmt);
1380 return true;
1382 return shouldAdd;
1385 lastLookup = stmt;
1387 // Perform the lookup!
1388 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1390 if (!fb) {
1391 // No need to update 'cachedEntry', since it will always be null.
1392 assert(!cachedEntry);
1393 return shouldAdd;
1396 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
1397 if (itr == fb->end()) {
1398 cachedEntry = nullptr;
1399 return shouldAdd;
1402 cachedEntry = &*itr;
1403 return true;
1406 // FIXME: Add support for dependent-sized array types in C++?
1407 // Does it even make sense to build a CFG for an uninstantiated template?
1408 static const VariableArrayType *FindVA(const Type *t) {
1409 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1410 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1411 if (vat->getSizeExpr())
1412 return vat;
1414 t = vt->getElementType().getTypePtr();
1417 return nullptr;
1420 void CFGBuilder::consumeConstructionContext(
1421 const ConstructionContextLayer *Layer, Expr *E) {
1422 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1423 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
1424 if (const ConstructionContextLayer *PreviouslyStoredLayer =
1425 ConstructionContextMap.lookup(E)) {
1426 (void)PreviouslyStoredLayer;
1427 // We might have visited this child when we were finding construction
1428 // contexts within its parents.
1429 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
1430 "Already within a different construction context!");
1431 } else {
1432 ConstructionContextMap[E] = Layer;
1436 void CFGBuilder::findConstructionContexts(
1437 const ConstructionContextLayer *Layer, Stmt *Child) {
1438 if (!BuildOpts.AddRichCXXConstructors)
1439 return;
1441 if (!Child)
1442 return;
1444 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1445 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1446 Layer);
1449 switch(Child->getStmtClass()) {
1450 case Stmt::CXXConstructExprClass:
1451 case Stmt::CXXTemporaryObjectExprClass: {
1452 // Support pre-C++17 copy elision AST.
1453 auto *CE = cast<CXXConstructExpr>(Child);
1454 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
1455 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1458 consumeConstructionContext(Layer, CE);
1459 break;
1461 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1462 // FIXME: An isa<> would look much better but this whole switch is a
1463 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1464 case Stmt::CallExprClass:
1465 case Stmt::CXXMemberCallExprClass:
1466 case Stmt::CXXOperatorCallExprClass:
1467 case Stmt::UserDefinedLiteralClass:
1468 case Stmt::ObjCMessageExprClass: {
1469 auto *E = cast<Expr>(Child);
1470 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1471 consumeConstructionContext(Layer, E);
1472 break;
1474 case Stmt::ExprWithCleanupsClass: {
1475 auto *Cleanups = cast<ExprWithCleanups>(Child);
1476 findConstructionContexts(Layer, Cleanups->getSubExpr());
1477 break;
1479 case Stmt::CXXFunctionalCastExprClass: {
1480 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
1481 findConstructionContexts(Layer, Cast->getSubExpr());
1482 break;
1484 case Stmt::ImplicitCastExprClass: {
1485 auto *Cast = cast<ImplicitCastExpr>(Child);
1486 // Should we support other implicit cast kinds?
1487 switch (Cast->getCastKind()) {
1488 case CK_NoOp:
1489 case CK_ConstructorConversion:
1490 findConstructionContexts(Layer, Cast->getSubExpr());
1491 break;
1492 default:
1493 break;
1495 break;
1497 case Stmt::CXXBindTemporaryExprClass: {
1498 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
1499 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1500 break;
1502 case Stmt::MaterializeTemporaryExprClass: {
1503 // Normally we don't want to search in MaterializeTemporaryExpr because
1504 // it indicates the beginning of a temporary object construction context,
1505 // so it shouldn't be found in the middle. However, if it is the beginning
1506 // of an elidable copy or move construction context, we need to include it.
1507 if (Layer->getItem().getKind() ==
1508 ConstructionContextItem::ElidableConstructorKind) {
1509 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1510 findConstructionContexts(withExtraLayer(MTE), MTE->getSubExpr());
1512 break;
1514 case Stmt::ConditionalOperatorClass: {
1515 auto *CO = cast<ConditionalOperator>(Child);
1516 if (Layer->getItem().getKind() !=
1517 ConstructionContextItem::MaterializationKind) {
1518 // If the object returned by the conditional operator is not going to be a
1519 // temporary object that needs to be immediately materialized, then
1520 // it must be C++17 with its mandatory copy elision. Do not yet promise
1521 // to support this case.
1522 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1523 Context->getLangOpts().CPlusPlus17);
1524 break;
1526 findConstructionContexts(Layer, CO->getLHS());
1527 findConstructionContexts(Layer, CO->getRHS());
1528 break;
1530 case Stmt::InitListExprClass: {
1531 auto *ILE = cast<InitListExpr>(Child);
1532 if (ILE->isTransparent()) {
1533 findConstructionContexts(Layer, ILE->getInit(0));
1534 break;
1536 // TODO: Handle other cases. For now, fail to find construction contexts.
1537 break;
1539 case Stmt::ParenExprClass: {
1540 // If expression is placed into parenthesis we should propagate the parent
1541 // construction context to subexpressions.
1542 auto *PE = cast<ParenExpr>(Child);
1543 findConstructionContexts(Layer, PE->getSubExpr());
1544 break;
1546 default:
1547 break;
1551 void CFGBuilder::cleanupConstructionContext(Expr *E) {
1552 assert(BuildOpts.AddRichCXXConstructors &&
1553 "We should not be managing construction contexts!");
1554 assert(ConstructionContextMap.count(E) &&
1555 "Cannot exit construction context without the context!");
1556 ConstructionContextMap.erase(E);
1559 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1560 /// arbitrary statement. Examples include a single expression or a function
1561 /// body (compound statement). The ownership of the returned CFG is
1562 /// transferred to the caller. If CFG construction fails, this method returns
1563 /// NULL.
1564 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1565 assert(cfg.get());
1566 if (!Statement)
1567 return nullptr;
1569 // Create an empty block that will serve as the exit block for the CFG. Since
1570 // this is the first block added to the CFG, it will be implicitly registered
1571 // as the exit block.
1572 Succ = createBlock();
1573 assert(Succ == &cfg->getExit());
1574 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1576 if (BuildOpts.AddImplicitDtors)
1577 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1578 addImplicitDtorsForDestructor(DD);
1580 // Visit the statements and create the CFG.
1581 CFGBlock *B = addStmt(Statement);
1583 if (badCFG)
1584 return nullptr;
1586 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1587 // are ignored unless the object is of the most derived class.
1588 // class VBase { VBase() = default; VBase(int) {} };
1589 // class A : virtual public VBase { A() : VBase(0) {} };
1590 // class B : public A {};
1591 // B b; // Constructor calls in order: VBase(), A(), B().
1592 // // VBase(0) is ignored because A isn't the most derived class.
1593 // This may result in the virtual base(s) being already initialized at this
1594 // point, in which case we should jump right onto non-virtual bases and
1595 // fields. To handle this, make a CFG branch. We only need to add one such
1596 // branch per constructor, since the Standard states that all virtual bases
1597 // shall be initialized before non-virtual bases and direct data members.
1598 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1599 CFGBlock *VBaseSucc = nullptr;
1600 for (auto *I : llvm::reverse(CD->inits())) {
1601 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1602 I->isBaseInitializer() && I->isBaseVirtual()) {
1603 // We've reached the first virtual base init while iterating in reverse
1604 // order. Make a new block for virtual base initializers so that we
1605 // could skip them.
1606 VBaseSucc = Succ = B ? B : &cfg->getExit();
1607 Block = createBlock();
1609 B = addInitializer(I);
1610 if (badCFG)
1611 return nullptr;
1613 if (VBaseSucc) {
1614 // Make a branch block for potentially skipping virtual base initializers.
1615 Succ = VBaseSucc;
1616 B = createBlock();
1617 B->setTerminator(
1618 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1619 addSuccessor(B, Block, true);
1623 if (B)
1624 Succ = B;
1626 // Backpatch the gotos whose label -> block mappings we didn't know when we
1627 // encountered them.
1628 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1629 E = BackpatchBlocks.end(); I != E; ++I ) {
1631 CFGBlock *B = I->block;
1632 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1633 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1634 // If there is no target for the goto, then we are looking at an
1635 // incomplete AST. Handle this by not registering a successor.
1636 if (LI == LabelMap.end())
1637 continue;
1638 JumpTarget JT = LI->second;
1640 CFGBlock *SuccBlk = createScopeChangesHandlingBlock(
1641 I->scopePosition, B, JT.scopePosition, JT.block);
1642 addSuccessor(B, SuccBlk);
1643 } else if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1644 CFGBlock *Successor = (I+1)->block;
1645 for (auto *L : G->labels()) {
1646 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1647 // If there is no target for the goto, then we are looking at an
1648 // incomplete AST. Handle this by not registering a successor.
1649 if (LI == LabelMap.end())
1650 continue;
1651 JumpTarget JT = LI->second;
1652 // Successor has been added, so skip it.
1653 if (JT.block == Successor)
1654 continue;
1655 addSuccessor(B, JT.block);
1657 I++;
1661 // Add successors to the Indirect Goto Dispatch block (if we have one).
1662 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1663 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1664 E = AddressTakenLabels.end(); I != E; ++I ) {
1665 // Lookup the target block.
1666 LabelMapTy::iterator LI = LabelMap.find(*I);
1668 // If there is no target block that contains label, then we are looking
1669 // at an incomplete AST. Handle this by not registering a successor.
1670 if (LI == LabelMap.end()) continue;
1672 addSuccessor(B, LI->second.block);
1675 // Create an empty entry block that has no predecessors.
1676 cfg->setEntry(createBlock());
1678 if (BuildOpts.AddRichCXXConstructors)
1679 assert(ConstructionContextMap.empty() &&
1680 "Not all construction contexts were cleaned up!");
1682 return std::move(cfg);
1685 /// createBlock - Used to lazily create blocks that are connected
1686 /// to the current (global) successor.
1687 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1688 CFGBlock *B = cfg->createBlock();
1689 if (add_successor && Succ)
1690 addSuccessor(B, Succ);
1691 return B;
1694 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1695 /// CFG. It is *not* connected to the current (global) successor, and instead
1696 /// directly tied to the exit block in order to be reachable.
1697 CFGBlock *CFGBuilder::createNoReturnBlock() {
1698 CFGBlock *B = createBlock(false);
1699 B->setHasNoReturnElement();
1700 addSuccessor(B, &cfg->getExit(), Succ);
1701 return B;
1704 /// addInitializer - Add C++ base or member initializer element to CFG.
1705 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1706 if (!BuildOpts.AddInitializers)
1707 return Block;
1709 bool HasTemporaries = false;
1711 // Destructors of temporaries in initialization expression should be called
1712 // after initialization finishes.
1713 Expr *Init = I->getInit();
1714 if (Init) {
1715 HasTemporaries = isa<ExprWithCleanups>(Init);
1717 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1718 // Generate destructors for temporaries in initialization expression.
1719 TempDtorContext Context;
1720 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1721 /*ExternallyDestructed=*/false, Context);
1725 autoCreateBlock();
1726 appendInitializer(Block, I);
1728 if (Init) {
1729 // If the initializer is an ArrayInitLoopExpr, we want to extract the
1730 // initializer, that's used for each element.
1731 auto *AILEInit = extractElementInitializerFromNestedAILE(
1732 dyn_cast<ArrayInitLoopExpr>(Init));
1734 findConstructionContexts(
1735 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
1736 AILEInit ? AILEInit : Init);
1738 if (HasTemporaries) {
1739 // For expression with temporaries go directly to subexpression to omit
1740 // generating destructors for the second time.
1741 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1743 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1744 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1745 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1746 // may cause the same Expr to appear more than once in the CFG. Doing it
1747 // here is safe because there's only one initializer per field.
1748 autoCreateBlock();
1749 appendStmt(Block, Default);
1750 if (Stmt *Child = Default->getExpr())
1751 if (CFGBlock *R = Visit(Child))
1752 Block = R;
1753 return Block;
1756 return Visit(Init);
1759 return Block;
1762 /// Retrieve the type of the temporary object whose lifetime was
1763 /// extended by a local reference with the given initializer.
1764 static QualType getReferenceInitTemporaryType(const Expr *Init,
1765 bool *FoundMTE = nullptr) {
1766 while (true) {
1767 // Skip parentheses.
1768 Init = Init->IgnoreParens();
1770 // Skip through cleanups.
1771 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1772 Init = EWC->getSubExpr();
1773 continue;
1776 // Skip through the temporary-materialization expression.
1777 if (const MaterializeTemporaryExpr *MTE
1778 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1779 Init = MTE->getSubExpr();
1780 if (FoundMTE)
1781 *FoundMTE = true;
1782 continue;
1785 // Skip sub-object accesses into rvalues.
1786 SmallVector<const Expr *, 2> CommaLHSs;
1787 SmallVector<SubobjectAdjustment, 2> Adjustments;
1788 const Expr *SkippedInit =
1789 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1790 if (SkippedInit != Init) {
1791 Init = SkippedInit;
1792 continue;
1795 break;
1798 return Init->getType();
1801 // TODO: Support adding LoopExit element to the CFG in case where the loop is
1802 // ended by ReturnStmt, GotoStmt or ThrowExpr.
1803 void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1804 if(!BuildOpts.AddLoopExit)
1805 return;
1806 autoCreateBlock();
1807 appendLoopExit(Block, LoopStmt);
1810 /// Adds the CFG elements for leaving the scope of automatic objects in
1811 /// range [B, E). This include following:
1812 /// * AutomaticObjectDtor for variables with non-trivial destructor
1813 /// * LifetimeEnds for all variables
1814 /// * ScopeEnd for each scope left
1815 void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1816 LocalScope::const_iterator E,
1817 Stmt *S) {
1818 if (!BuildOpts.AddScopes && !BuildOpts.AddImplicitDtors &&
1819 !BuildOpts.AddLifetime)
1820 return;
1822 if (B == E)
1823 return;
1825 // Not leaving the scope, only need to handle destruction and lifetime
1826 if (B.inSameLocalScope(E)) {
1827 addAutomaticObjDestruction(B, E, S);
1828 return;
1831 // Extract information about all local scopes that are left
1832 SmallVector<LocalScope::const_iterator, 10> LocalScopeEndMarkers;
1833 LocalScopeEndMarkers.push_back(B);
1834 for (LocalScope::const_iterator I = B; I != E; ++I) {
1835 if (!I.inSameLocalScope(LocalScopeEndMarkers.back()))
1836 LocalScopeEndMarkers.push_back(I);
1838 LocalScopeEndMarkers.push_back(E);
1840 // We need to leave the scope in reverse order, so we reverse the end
1841 // markers
1842 std::reverse(LocalScopeEndMarkers.begin(), LocalScopeEndMarkers.end());
1843 auto Pairwise =
1844 llvm::zip(LocalScopeEndMarkers, llvm::drop_begin(LocalScopeEndMarkers));
1845 for (auto [E, B] : Pairwise) {
1846 if (!B.inSameLocalScope(E))
1847 addScopeExitHandling(B, E, S);
1848 addAutomaticObjDestruction(B, E, S);
1852 /// Add CFG elements corresponding to call destructor and end of lifetime
1853 /// of all automatic variables with non-trivial destructor in range [B, E).
1854 /// This include AutomaticObjectDtor and LifetimeEnds elements.
1855 void CFGBuilder::addAutomaticObjDestruction(LocalScope::const_iterator B,
1856 LocalScope::const_iterator E,
1857 Stmt *S) {
1858 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
1859 return;
1861 if (B == E)
1862 return;
1864 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1865 DeclsNonTrivial.reserve(B.distance(E));
1867 for (VarDecl* D : llvm::make_range(B, E))
1868 if (!hasTrivialDestructor(D))
1869 DeclsNonTrivial.push_back(D);
1871 for (VarDecl *VD : llvm::reverse(DeclsNonTrivial)) {
1872 if (BuildOpts.AddImplicitDtors) {
1873 // If this destructor is marked as a no-return destructor, we need to
1874 // create a new block for the destructor which does not have as a
1875 // successor anything built thus far: control won't flow out of this
1876 // block.
1877 QualType Ty = VD->getType();
1878 if (Ty->isReferenceType())
1879 Ty = getReferenceInitTemporaryType(VD->getInit());
1880 Ty = Context->getBaseElementType(Ty);
1882 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1883 Block = createNoReturnBlock();
1886 autoCreateBlock();
1888 // Add LifetimeEnd after automatic obj with non-trivial destructors,
1889 // as they end their lifetime when the destructor returns. For trivial
1890 // objects, we end lifetime with scope end.
1891 if (BuildOpts.AddLifetime)
1892 appendLifetimeEnds(Block, VD, S);
1893 if (BuildOpts.AddImplicitDtors)
1894 appendAutomaticObjDtor(Block, VD, S);
1898 /// Add CFG elements corresponding to leaving a scope.
1899 /// Assumes that range [B, E) corresponds to single scope.
1900 /// This add following elements:
1901 /// * LifetimeEnds for all variables with non-trivial destructor
1902 /// * ScopeEnd for each scope left
1903 void CFGBuilder::addScopeExitHandling(LocalScope::const_iterator B,
1904 LocalScope::const_iterator E, Stmt *S) {
1905 assert(!B.inSameLocalScope(E));
1906 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes)
1907 return;
1909 if (BuildOpts.AddScopes) {
1910 autoCreateBlock();
1911 appendScopeEnd(Block, B.getFirstVarInScope(), S);
1914 if (!BuildOpts.AddLifetime)
1915 return;
1917 // We need to perform the scope leaving in reverse order
1918 SmallVector<VarDecl *, 10> DeclsTrivial;
1919 DeclsTrivial.reserve(B.distance(E));
1921 // Objects with trivial destructor ends their lifetime when their storage
1922 // is destroyed, for automatic variables, this happens when the end of the
1923 // scope is added.
1924 for (VarDecl* D : llvm::make_range(B, E))
1925 if (hasTrivialDestructor(D))
1926 DeclsTrivial.push_back(D);
1928 if (DeclsTrivial.empty())
1929 return;
1931 autoCreateBlock();
1932 for (VarDecl *VD : llvm::reverse(DeclsTrivial))
1933 appendLifetimeEnds(Block, VD, S);
1936 /// addScopeChangesHandling - appends information about destruction, lifetime
1937 /// and cfgScopeEnd for variables in the scope that was left by the jump, and
1938 /// appends cfgScopeBegin for all scopes that where entered.
1939 /// We insert the cfgScopeBegin at the end of the jump node, as depending on
1940 /// the sourceBlock, each goto, may enter different amount of scopes.
1941 void CFGBuilder::addScopeChangesHandling(LocalScope::const_iterator SrcPos,
1942 LocalScope::const_iterator DstPos,
1943 Stmt *S) {
1944 assert(Block && "Source block should be always crated");
1945 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1946 !BuildOpts.AddScopes) {
1947 return;
1950 if (SrcPos == DstPos)
1951 return;
1953 // Get common scope, the jump leaves all scopes [SrcPos, BasePos), and
1954 // enter all scopes between [DstPos, BasePos)
1955 LocalScope::const_iterator BasePos = SrcPos.shared_parent(DstPos);
1957 // Append scope begins for scopes entered by goto
1958 if (BuildOpts.AddScopes && !DstPos.inSameLocalScope(BasePos)) {
1959 for (LocalScope::const_iterator I = DstPos; I != BasePos; ++I)
1960 if (I.pointsToFirstDeclaredVar())
1961 appendScopeBegin(Block, *I, S);
1964 // Append scopeEnds, destructor and lifetime with the terminator for
1965 // block left by goto.
1966 addAutomaticObjHandling(SrcPos, BasePos, S);
1969 /// createScopeChangesHandlingBlock - Creates a block with cfgElements
1970 /// corresponding to changing the scope from the source scope of the GotoStmt,
1971 /// to destination scope. Add destructor, lifetime and cfgScopeEnd
1972 /// CFGElements to newly created CFGBlock, that will have the CFG terminator
1973 /// transferred.
1974 CFGBlock *CFGBuilder::createScopeChangesHandlingBlock(
1975 LocalScope::const_iterator SrcPos, CFGBlock *SrcBlk,
1976 LocalScope::const_iterator DstPos, CFGBlock *DstBlk) {
1977 if (SrcPos == DstPos)
1978 return DstBlk;
1980 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1981 (!BuildOpts.AddScopes || SrcPos.inSameLocalScope(DstPos)))
1982 return DstBlk;
1984 // We will update CFBBuilder when creating new block, restore the
1985 // previous state at exit.
1986 SaveAndRestore save_Block(Block), save_Succ(Succ);
1988 // Create a new block, and transfer terminator
1989 Block = createBlock(false);
1990 Block->setTerminator(SrcBlk->getTerminator());
1991 SrcBlk->setTerminator(CFGTerminator());
1992 addSuccessor(Block, DstBlk);
1994 // Fill the created Block with the required elements.
1995 addScopeChangesHandling(SrcPos, DstPos, Block->getTerminatorStmt());
1997 assert(Block && "There should be at least one scope changing Block");
1998 return Block;
2001 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
2002 /// base and member objects in destructor.
2003 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
2004 assert(BuildOpts.AddImplicitDtors &&
2005 "Can be called only when dtors should be added");
2006 const CXXRecordDecl *RD = DD->getParent();
2008 // At the end destroy virtual base objects.
2009 for (const auto &VI : RD->vbases()) {
2010 // TODO: Add a VirtualBaseBranch to see if the most derived class
2011 // (which is different from the current class) is responsible for
2012 // destroying them.
2013 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
2014 if (CD && !CD->hasTrivialDestructor()) {
2015 autoCreateBlock();
2016 appendBaseDtor(Block, &VI);
2020 // Before virtual bases destroy direct base objects.
2021 for (const auto &BI : RD->bases()) {
2022 if (!BI.isVirtual()) {
2023 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
2024 if (CD && !CD->hasTrivialDestructor()) {
2025 autoCreateBlock();
2026 appendBaseDtor(Block, &BI);
2031 // First destroy member objects.
2032 for (auto *FI : RD->fields()) {
2033 // Check for constant size array. Set type to array element type.
2034 QualType QT = FI->getType();
2035 // It may be a multidimensional array.
2036 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2037 if (AT->getSize() == 0)
2038 break;
2039 QT = AT->getElementType();
2042 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2043 if (!CD->hasTrivialDestructor()) {
2044 autoCreateBlock();
2045 appendMemberDtor(Block, FI);
2050 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
2051 /// way return valid LocalScope object.
2052 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
2053 if (Scope)
2054 return Scope;
2055 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
2056 return new (alloc) LocalScope(BumpVectorContext(alloc), ScopePos);
2059 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
2060 /// that should create implicit scope (e.g. if/else substatements).
2061 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
2062 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2063 !BuildOpts.AddScopes)
2064 return;
2066 LocalScope *Scope = nullptr;
2068 // For compound statement we will be creating explicit scope.
2069 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
2070 for (auto *BI : CS->body()) {
2071 Stmt *SI = BI->stripLabelLikeStatements();
2072 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
2073 Scope = addLocalScopeForDeclStmt(DS, Scope);
2075 return;
2078 // For any other statement scope will be implicit and as such will be
2079 // interesting only for DeclStmt.
2080 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
2081 addLocalScopeForDeclStmt(DS);
2084 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
2085 /// reuse Scope if not NULL.
2086 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
2087 LocalScope* Scope) {
2088 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2089 !BuildOpts.AddScopes)
2090 return Scope;
2092 for (auto *DI : DS->decls())
2093 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
2094 Scope = addLocalScopeForVarDecl(VD, Scope);
2095 return Scope;
2098 bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
2099 // Check for const references bound to temporary. Set type to pointee.
2100 QualType QT = VD->getType();
2101 if (QT->isReferenceType()) {
2102 // Attempt to determine whether this declaration lifetime-extends a
2103 // temporary.
2105 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
2106 // temporaries, and a single declaration can extend multiple temporaries.
2107 // We should look at the storage duration on each nested
2108 // MaterializeTemporaryExpr instead.
2110 const Expr *Init = VD->getInit();
2111 if (!Init) {
2112 // Probably an exception catch-by-reference variable.
2113 // FIXME: It doesn't really mean that the object has a trivial destructor.
2114 // Also are there other cases?
2115 return true;
2118 // Lifetime-extending a temporary?
2119 bool FoundMTE = false;
2120 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
2121 if (!FoundMTE)
2122 return true;
2125 // Check for constant size array. Set type to array element type.
2126 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
2127 if (AT->getSize() == 0)
2128 return true;
2129 QT = AT->getElementType();
2132 // Check if type is a C++ class with non-trivial destructor.
2133 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
2134 return !CD->hasDefinition() || CD->hasTrivialDestructor();
2135 return true;
2138 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
2139 /// create add scope for automatic objects and temporary objects bound to
2140 /// const reference. Will reuse Scope if not NULL.
2141 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
2142 LocalScope* Scope) {
2143 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
2144 !BuildOpts.AddScopes)
2145 return Scope;
2147 // Check if variable is local.
2148 if (!VD->hasLocalStorage())
2149 return Scope;
2151 if (!BuildOpts.AddLifetime && !BuildOpts.AddScopes &&
2152 hasTrivialDestructor(VD)) {
2153 assert(BuildOpts.AddImplicitDtors);
2154 return Scope;
2157 // Add the variable to scope
2158 Scope = createOrReuseLocalScope(Scope);
2159 Scope->addVar(VD);
2160 ScopePos = Scope->begin();
2161 return Scope;
2164 /// addLocalScopeAndDtors - For given statement add local scope for it and
2165 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
2166 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
2167 LocalScope::const_iterator scopeBeginPos = ScopePos;
2168 addLocalScopeForStmt(S);
2169 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
2172 /// Visit - Walk the subtree of a statement and add extra
2173 /// blocks for ternary operators, &&, and ||. We also process "," and
2174 /// DeclStmts (which may contain nested control-flow).
2175 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc,
2176 bool ExternallyDestructed) {
2177 if (!S) {
2178 badCFG = true;
2179 return nullptr;
2182 if (Expr *E = dyn_cast<Expr>(S))
2183 S = E->IgnoreParens();
2185 if (Context->getLangOpts().OpenMP)
2186 if (auto *D = dyn_cast<OMPExecutableDirective>(S))
2187 return VisitOMPExecutableDirective(D, asc);
2189 switch (S->getStmtClass()) {
2190 default:
2191 return VisitStmt(S, asc);
2193 case Stmt::ImplicitValueInitExprClass:
2194 if (BuildOpts.OmitImplicitValueInitializers)
2195 return Block;
2196 return VisitStmt(S, asc);
2198 case Stmt::InitListExprClass:
2199 return VisitInitListExpr(cast<InitListExpr>(S), asc);
2201 case Stmt::AttributedStmtClass:
2202 return VisitAttributedStmt(cast<AttributedStmt>(S), asc);
2204 case Stmt::AddrLabelExprClass:
2205 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
2207 case Stmt::BinaryConditionalOperatorClass:
2208 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2210 case Stmt::BinaryOperatorClass:
2211 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
2213 case Stmt::BlockExprClass:
2214 return VisitBlockExpr(cast<BlockExpr>(S), asc);
2216 case Stmt::BreakStmtClass:
2217 return VisitBreakStmt(cast<BreakStmt>(S));
2219 case Stmt::CallExprClass:
2220 case Stmt::CXXOperatorCallExprClass:
2221 case Stmt::CXXMemberCallExprClass:
2222 case Stmt::UserDefinedLiteralClass:
2223 return VisitCallExpr(cast<CallExpr>(S), asc);
2225 case Stmt::CaseStmtClass:
2226 return VisitCaseStmt(cast<CaseStmt>(S));
2228 case Stmt::ChooseExprClass:
2229 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
2231 case Stmt::CompoundStmtClass:
2232 return VisitCompoundStmt(cast<CompoundStmt>(S), ExternallyDestructed);
2234 case Stmt::ConditionalOperatorClass:
2235 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
2237 case Stmt::ContinueStmtClass:
2238 return VisitContinueStmt(cast<ContinueStmt>(S));
2240 case Stmt::CXXCatchStmtClass:
2241 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2243 case Stmt::ExprWithCleanupsClass:
2244 return VisitExprWithCleanups(cast<ExprWithCleanups>(S),
2245 asc, ExternallyDestructed);
2247 case Stmt::CXXDefaultArgExprClass:
2248 case Stmt::CXXDefaultInitExprClass:
2249 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2250 // called function's declaration, not by the caller. If we simply add
2251 // this expression to the CFG, we could end up with the same Expr
2252 // appearing multiple times (PR13385).
2254 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2255 // expression to be used in the same function (through aggregate
2256 // initialization).
2257 return VisitStmt(S, asc);
2259 case Stmt::CXXBindTemporaryExprClass:
2260 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2262 case Stmt::CXXConstructExprClass:
2263 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2265 case Stmt::CXXNewExprClass:
2266 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2268 case Stmt::CXXDeleteExprClass:
2269 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2271 case Stmt::CXXFunctionalCastExprClass:
2272 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2274 case Stmt::CXXTemporaryObjectExprClass:
2275 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2277 case Stmt::CXXThrowExprClass:
2278 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
2280 case Stmt::CXXTryStmtClass:
2281 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
2283 case Stmt::CXXTypeidExprClass:
2284 return VisitCXXTypeidExpr(cast<CXXTypeidExpr>(S), asc);
2286 case Stmt::CXXForRangeStmtClass:
2287 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2289 case Stmt::DeclStmtClass:
2290 return VisitDeclStmt(cast<DeclStmt>(S));
2292 case Stmt::DefaultStmtClass:
2293 return VisitDefaultStmt(cast<DefaultStmt>(S));
2295 case Stmt::DoStmtClass:
2296 return VisitDoStmt(cast<DoStmt>(S));
2298 case Stmt::ForStmtClass:
2299 return VisitForStmt(cast<ForStmt>(S));
2301 case Stmt::GotoStmtClass:
2302 return VisitGotoStmt(cast<GotoStmt>(S));
2304 case Stmt::GCCAsmStmtClass:
2305 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2307 case Stmt::IfStmtClass:
2308 return VisitIfStmt(cast<IfStmt>(S));
2310 case Stmt::ImplicitCastExprClass:
2311 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
2313 case Stmt::ConstantExprClass:
2314 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2316 case Stmt::IndirectGotoStmtClass:
2317 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
2319 case Stmt::LabelStmtClass:
2320 return VisitLabelStmt(cast<LabelStmt>(S));
2322 case Stmt::LambdaExprClass:
2323 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2325 case Stmt::MaterializeTemporaryExprClass:
2326 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2327 asc);
2329 case Stmt::MemberExprClass:
2330 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2332 case Stmt::NullStmtClass:
2333 return Block;
2335 case Stmt::ObjCAtCatchStmtClass:
2336 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2338 case Stmt::ObjCAutoreleasePoolStmtClass:
2339 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2341 case Stmt::ObjCAtSynchronizedStmtClass:
2342 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
2344 case Stmt::ObjCAtThrowStmtClass:
2345 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
2347 case Stmt::ObjCAtTryStmtClass:
2348 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
2350 case Stmt::ObjCForCollectionStmtClass:
2351 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
2353 case Stmt::ObjCMessageExprClass:
2354 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2356 case Stmt::OpaqueValueExprClass:
2357 return Block;
2359 case Stmt::PseudoObjectExprClass:
2360 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2362 case Stmt::ReturnStmtClass:
2363 case Stmt::CoreturnStmtClass:
2364 return VisitReturnStmt(S);
2366 case Stmt::CoyieldExprClass:
2367 case Stmt::CoawaitExprClass:
2368 return VisitCoroutineSuspendExpr(cast<CoroutineSuspendExpr>(S), asc);
2370 case Stmt::SEHExceptStmtClass:
2371 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2373 case Stmt::SEHFinallyStmtClass:
2374 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2376 case Stmt::SEHLeaveStmtClass:
2377 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2379 case Stmt::SEHTryStmtClass:
2380 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2382 case Stmt::UnaryExprOrTypeTraitExprClass:
2383 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2384 asc);
2386 case Stmt::StmtExprClass:
2387 return VisitStmtExpr(cast<StmtExpr>(S), asc);
2389 case Stmt::SwitchStmtClass:
2390 return VisitSwitchStmt(cast<SwitchStmt>(S));
2392 case Stmt::UnaryOperatorClass:
2393 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2395 case Stmt::WhileStmtClass:
2396 return VisitWhileStmt(cast<WhileStmt>(S));
2398 case Stmt::ArrayInitLoopExprClass:
2399 return VisitArrayInitLoopExpr(cast<ArrayInitLoopExpr>(S), asc);
2403 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
2404 if (asc.alwaysAdd(*this, S)) {
2405 autoCreateBlock();
2406 appendStmt(Block, S);
2409 return VisitChildren(S);
2412 /// VisitChildren - Visit the children of a Stmt.
2413 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2414 CFGBlock *B = Block;
2416 // Visit the children in their reverse order so that they appear in
2417 // left-to-right (natural) order in the CFG.
2418 reverse_children RChildren(S);
2419 for (Stmt *Child : RChildren) {
2420 if (Child)
2421 if (CFGBlock *R = Visit(Child))
2422 B = R;
2424 return B;
2427 CFGBlock *CFGBuilder::VisitInitListExpr(InitListExpr *ILE, AddStmtChoice asc) {
2428 if (asc.alwaysAdd(*this, ILE)) {
2429 autoCreateBlock();
2430 appendStmt(Block, ILE);
2432 CFGBlock *B = Block;
2434 reverse_children RChildren(ILE);
2435 for (Stmt *Child : RChildren) {
2436 if (!Child)
2437 continue;
2438 if (CFGBlock *R = Visit(Child))
2439 B = R;
2440 if (BuildOpts.AddCXXDefaultInitExprInAggregates) {
2441 if (auto *DIE = dyn_cast<CXXDefaultInitExpr>(Child))
2442 if (Stmt *Child = DIE->getExpr())
2443 if (CFGBlock *R = Visit(Child))
2444 B = R;
2447 return B;
2450 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2451 AddStmtChoice asc) {
2452 AddressTakenLabels.insert(A->getLabel());
2454 if (asc.alwaysAdd(*this, A)) {
2455 autoCreateBlock();
2456 appendStmt(Block, A);
2459 return Block;
2462 static bool isFallthroughStatement(const AttributedStmt *A) {
2463 bool isFallthrough = hasSpecificAttr<FallThroughAttr>(A->getAttrs());
2464 assert((!isFallthrough || isa<NullStmt>(A->getSubStmt())) &&
2465 "expected fallthrough not to have children");
2466 return isFallthrough;
2469 CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
2470 AddStmtChoice asc) {
2471 // AttributedStmts for [[likely]] can have arbitrary statements as children,
2472 // and the current visitation order here would add the AttributedStmts
2473 // for [[likely]] after the child nodes, which is undesirable: For example,
2474 // if the child contains an unconditional return, the [[likely]] would be
2475 // considered unreachable.
2476 // So only add the AttributedStmt for FallThrough, which has CFG effects and
2477 // also no children, and omit the others. None of the other current StmtAttrs
2478 // have semantic meaning for the CFG.
2479 if (isFallthroughStatement(A) && asc.alwaysAdd(*this, A)) {
2480 autoCreateBlock();
2481 appendStmt(Block, A);
2484 return VisitChildren(A);
2487 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc) {
2488 if (asc.alwaysAdd(*this, U)) {
2489 autoCreateBlock();
2490 appendStmt(Block, U);
2493 if (U->getOpcode() == UO_LNot)
2494 tryEvaluateBool(U->getSubExpr()->IgnoreParens());
2496 return Visit(U->getSubExpr(), AddStmtChoice());
2499 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2500 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2501 appendStmt(ConfluenceBlock, B);
2503 if (badCFG)
2504 return nullptr;
2506 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2507 ConfluenceBlock).first;
2510 std::pair<CFGBlock*, CFGBlock*>
2511 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2512 Stmt *Term,
2513 CFGBlock *TrueBlock,
2514 CFGBlock *FalseBlock) {
2515 // Introspect the RHS. If it is a nested logical operation, we recursively
2516 // build the CFG using this function. Otherwise, resort to default
2517 // CFG construction behavior.
2518 Expr *RHS = B->getRHS()->IgnoreParens();
2519 CFGBlock *RHSBlock, *ExitBlock;
2521 do {
2522 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2523 if (B_RHS->isLogicalOp()) {
2524 std::tie(RHSBlock, ExitBlock) =
2525 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2526 break;
2529 // The RHS is not a nested logical operation. Don't push the terminator
2530 // down further, but instead visit RHS and construct the respective
2531 // pieces of the CFG, and link up the RHSBlock with the terminator
2532 // we have been provided.
2533 ExitBlock = RHSBlock = createBlock(false);
2535 // Even though KnownVal is only used in the else branch of the next
2536 // conditional, tryEvaluateBool performs additional checking on the
2537 // Expr, so it should be called unconditionally.
2538 TryResult KnownVal = tryEvaluateBool(RHS);
2539 if (!KnownVal.isKnown())
2540 KnownVal = tryEvaluateBool(B);
2542 if (!Term) {
2543 assert(TrueBlock == FalseBlock);
2544 addSuccessor(RHSBlock, TrueBlock);
2546 else {
2547 RHSBlock->setTerminator(Term);
2548 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2549 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
2552 Block = RHSBlock;
2553 RHSBlock = addStmt(RHS);
2555 while (false);
2557 if (badCFG)
2558 return std::make_pair(nullptr, nullptr);
2560 // Generate the blocks for evaluating the LHS.
2561 Expr *LHS = B->getLHS()->IgnoreParens();
2563 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2564 if (B_LHS->isLogicalOp()) {
2565 if (B->getOpcode() == BO_LOr)
2566 FalseBlock = RHSBlock;
2567 else
2568 TrueBlock = RHSBlock;
2570 // For the LHS, treat 'B' as the terminator that we want to sink
2571 // into the nested branch. The RHS always gets the top-most
2572 // terminator.
2573 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2576 // Create the block evaluating the LHS.
2577 // This contains the '&&' or '||' as the terminator.
2578 CFGBlock *LHSBlock = createBlock(false);
2579 LHSBlock->setTerminator(B);
2581 Block = LHSBlock;
2582 CFGBlock *EntryLHSBlock = addStmt(LHS);
2584 if (badCFG)
2585 return std::make_pair(nullptr, nullptr);
2587 // See if this is a known constant.
2588 TryResult KnownVal = tryEvaluateBool(LHS);
2590 // Now link the LHSBlock with RHSBlock.
2591 if (B->getOpcode() == BO_LOr) {
2592 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2593 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
2594 } else {
2595 assert(B->getOpcode() == BO_LAnd);
2596 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2597 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
2600 return std::make_pair(EntryLHSBlock, ExitBlock);
2603 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2604 AddStmtChoice asc) {
2605 // && or ||
2606 if (B->isLogicalOp())
2607 return VisitLogicalOperator(B);
2609 if (B->getOpcode() == BO_Comma) { // ,
2610 autoCreateBlock();
2611 appendStmt(Block, B);
2612 addStmt(B->getRHS());
2613 return addStmt(B->getLHS());
2616 if (B->isAssignmentOp()) {
2617 if (asc.alwaysAdd(*this, B)) {
2618 autoCreateBlock();
2619 appendStmt(Block, B);
2621 Visit(B->getLHS());
2622 return Visit(B->getRHS());
2625 if (asc.alwaysAdd(*this, B)) {
2626 autoCreateBlock();
2627 appendStmt(Block, B);
2630 if (B->isEqualityOp() || B->isRelationalOp())
2631 tryEvaluateBool(B);
2633 CFGBlock *RBlock = Visit(B->getRHS());
2634 CFGBlock *LBlock = Visit(B->getLHS());
2635 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2636 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2637 // return RBlock. Otherwise we'll incorrectly return NULL.
2638 return (LBlock ? LBlock : RBlock);
2641 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
2642 if (asc.alwaysAdd(*this, E)) {
2643 autoCreateBlock();
2644 appendStmt(Block, E);
2646 return Block;
2649 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2650 // "break" is a control-flow statement. Thus we stop processing the current
2651 // block.
2652 if (badCFG)
2653 return nullptr;
2655 // Now create a new block that ends with the break statement.
2656 Block = createBlock(false);
2657 Block->setTerminator(B);
2659 // If there is no target for the break, then we are looking at an incomplete
2660 // AST. This means that the CFG cannot be constructed.
2661 if (BreakJumpTarget.block) {
2662 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
2663 addSuccessor(Block, BreakJumpTarget.block);
2664 } else
2665 badCFG = true;
2667 return Block;
2670 static bool CanThrow(Expr *E, ASTContext &Ctx) {
2671 QualType Ty = E->getType();
2672 if (Ty->isFunctionPointerType() || Ty->isBlockPointerType())
2673 Ty = Ty->getPointeeType();
2675 const FunctionType *FT = Ty->getAs<FunctionType>();
2676 if (FT) {
2677 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
2678 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
2679 Proto->isNothrow())
2680 return false;
2682 return true;
2685 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
2686 // Compute the callee type.
2687 QualType calleeType = C->getCallee()->getType();
2688 if (calleeType == Context->BoundMemberTy) {
2689 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2691 // We should only get a null bound type if processing a dependent
2692 // CFG. Recover by assuming nothing.
2693 if (!boundType.isNull()) calleeType = boundType;
2696 // If this is a call to a no-return function, this stops the block here.
2697 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2699 bool AddEHEdge = false;
2701 // Languages without exceptions are assumed to not throw.
2702 if (Context->getLangOpts().Exceptions) {
2703 if (BuildOpts.AddEHEdges)
2704 AddEHEdge = true;
2707 // If this is a call to a builtin function, it might not actually evaluate
2708 // its arguments. Don't add them to the CFG if this is the case.
2709 bool OmitArguments = false;
2711 if (FunctionDecl *FD = C->getDirectCallee()) {
2712 // TODO: Support construction contexts for variadic function arguments.
2713 // These are a bit problematic and not very useful because passing
2714 // C++ objects as C-style variadic arguments doesn't work in general
2715 // (see [expr.call]).
2716 if (!FD->isVariadic())
2717 findConstructionContextsForArguments(C);
2719 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
2720 NoReturn = true;
2721 if (FD->hasAttr<NoThrowAttr>())
2722 AddEHEdge = false;
2723 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2724 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
2725 OmitArguments = true;
2728 if (!CanThrow(C->getCallee(), *Context))
2729 AddEHEdge = false;
2731 if (OmitArguments) {
2732 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2733 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2734 autoCreateBlock();
2735 appendStmt(Block, C);
2736 return Visit(C->getCallee());
2739 if (!NoReturn && !AddEHEdge) {
2740 autoCreateBlock();
2741 appendCall(Block, C);
2743 return VisitChildren(C);
2746 if (Block) {
2747 Succ = Block;
2748 if (badCFG)
2749 return nullptr;
2752 if (NoReturn)
2753 Block = createNoReturnBlock();
2754 else
2755 Block = createBlock();
2757 appendCall(Block, C);
2759 if (AddEHEdge) {
2760 // Add exceptional edges.
2761 if (TryTerminatedBlock)
2762 addSuccessor(Block, TryTerminatedBlock);
2763 else
2764 addSuccessor(Block, &cfg->getExit());
2767 return VisitChildren(C);
2770 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2771 AddStmtChoice asc) {
2772 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2773 appendStmt(ConfluenceBlock, C);
2774 if (badCFG)
2775 return nullptr;
2777 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2778 Succ = ConfluenceBlock;
2779 Block = nullptr;
2780 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
2781 if (badCFG)
2782 return nullptr;
2784 Succ = ConfluenceBlock;
2785 Block = nullptr;
2786 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
2787 if (badCFG)
2788 return nullptr;
2790 Block = createBlock(false);
2791 // See if this is a known constant.
2792 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2793 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2794 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
2795 Block->setTerminator(C);
2796 return addStmt(C->getCond());
2799 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C,
2800 bool ExternallyDestructed) {
2801 LocalScope::const_iterator scopeBeginPos = ScopePos;
2802 addLocalScopeForStmt(C);
2804 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
2805 // If the body ends with a ReturnStmt, the dtors will be added in
2806 // VisitReturnStmt.
2807 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
2810 CFGBlock *LastBlock = Block;
2812 for (Stmt *S : llvm::reverse(C->body())) {
2813 // If we hit a segment of code just containing ';' (NullStmts), we can
2814 // get a null block back. In such cases, just use the LastBlock
2815 CFGBlock *newBlock = Visit(S, AddStmtChoice::AlwaysAdd,
2816 ExternallyDestructed);
2818 if (newBlock)
2819 LastBlock = newBlock;
2821 if (badCFG)
2822 return nullptr;
2824 ExternallyDestructed = false;
2827 return LastBlock;
2830 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
2831 AddStmtChoice asc) {
2832 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
2833 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
2835 // Create the confluence block that will "merge" the results of the ternary
2836 // expression.
2837 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2838 appendStmt(ConfluenceBlock, C);
2839 if (badCFG)
2840 return nullptr;
2842 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
2844 // Create a block for the LHS expression if there is an LHS expression. A
2845 // GCC extension allows LHS to be NULL, causing the condition to be the
2846 // value that is returned instead.
2847 // e.g: x ?: y is shorthand for: x ? x : y;
2848 Succ = ConfluenceBlock;
2849 Block = nullptr;
2850 CFGBlock *LHSBlock = nullptr;
2851 const Expr *trueExpr = C->getTrueExpr();
2852 if (trueExpr != opaqueValue) {
2853 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2854 if (badCFG)
2855 return nullptr;
2856 Block = nullptr;
2858 else
2859 LHSBlock = ConfluenceBlock;
2861 // Create the block for the RHS expression.
2862 Succ = ConfluenceBlock;
2863 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2864 if (badCFG)
2865 return nullptr;
2867 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2868 if (BinaryOperator *Cond =
2869 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2870 if (Cond->isLogicalOp())
2871 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2873 // Create the block that will contain the condition.
2874 Block = createBlock(false);
2876 // See if this is a known constant.
2877 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2878 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2879 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2880 Block->setTerminator(C);
2881 Expr *condExpr = C->getCond();
2883 if (opaqueValue) {
2884 // Run the condition expression if it's not trivially expressed in
2885 // terms of the opaque value (or if there is no opaque value).
2886 if (condExpr != opaqueValue)
2887 addStmt(condExpr);
2889 // Before that, run the common subexpression if there was one.
2890 // At least one of this or the above will be run.
2891 return addStmt(BCO->getCommon());
2894 return addStmt(condExpr);
2897 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2898 // Check if the Decl is for an __label__. If so, elide it from the
2899 // CFG entirely.
2900 if (isa<LabelDecl>(*DS->decl_begin()))
2901 return Block;
2903 // This case also handles static_asserts.
2904 if (DS->isSingleDecl())
2905 return VisitDeclSubExpr(DS);
2907 CFGBlock *B = nullptr;
2909 // Build an individual DeclStmt for each decl.
2910 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2911 E = DS->decl_rend();
2912 I != E; ++I) {
2914 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2915 // automatically freed with the CFG.
2916 DeclGroupRef DG(*I);
2917 Decl *D = *I;
2918 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2919 cfg->addSyntheticDeclStmt(DSNew, DS);
2921 // Append the fake DeclStmt to block.
2922 B = VisitDeclSubExpr(DSNew);
2925 return B;
2928 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2929 /// DeclStmts and initializers in them.
2930 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2931 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2933 if (const auto *TND = dyn_cast<TypedefNameDecl>(DS->getSingleDecl())) {
2934 // If we encounter a VLA, process its size expressions.
2935 const Type *T = TND->getUnderlyingType().getTypePtr();
2936 if (!T->isVariablyModifiedType())
2937 return Block;
2939 autoCreateBlock();
2940 appendStmt(Block, DS);
2942 CFGBlock *LastBlock = Block;
2943 for (const VariableArrayType *VA = FindVA(T); VA != nullptr;
2944 VA = FindVA(VA->getElementType().getTypePtr())) {
2945 if (CFGBlock *NewBlock = addStmt(VA->getSizeExpr()))
2946 LastBlock = NewBlock;
2948 return LastBlock;
2951 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2953 if (!VD) {
2954 // Of everything that can be declared in a DeclStmt, only VarDecls and the
2955 // exceptions above impact runtime semantics.
2956 return Block;
2959 bool HasTemporaries = false;
2961 // Guard static initializers under a branch.
2962 CFGBlock *blockAfterStaticInit = nullptr;
2964 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2965 // For static variables, we need to create a branch to track
2966 // whether or not they are initialized.
2967 if (Block) {
2968 Succ = Block;
2969 Block = nullptr;
2970 if (badCFG)
2971 return nullptr;
2973 blockAfterStaticInit = Succ;
2976 // Destructors of temporaries in initialization expression should be called
2977 // after initialization finishes.
2978 Expr *Init = VD->getInit();
2979 if (Init) {
2980 HasTemporaries = isa<ExprWithCleanups>(Init);
2982 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2983 // Generate destructors for temporaries in initialization expression.
2984 TempDtorContext Context;
2985 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2986 /*ExternallyDestructed=*/true, Context);
2990 // If we bind to a tuple-like type, we iterate over the HoldingVars, and
2991 // create a DeclStmt for each of them.
2992 if (const auto *DD = dyn_cast<DecompositionDecl>(VD)) {
2993 for (auto *BD : llvm::reverse(DD->bindings())) {
2994 if (auto *VD = BD->getHoldingVar()) {
2995 DeclGroupRef DG(VD);
2996 DeclStmt *DSNew =
2997 new (Context) DeclStmt(DG, VD->getLocation(), GetEndLoc(VD));
2998 cfg->addSyntheticDeclStmt(DSNew, DS);
2999 Block = VisitDeclSubExpr(DSNew);
3004 autoCreateBlock();
3005 appendStmt(Block, DS);
3007 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3008 // initializer, that's used for each element.
3009 const auto *AILE = dyn_cast_or_null<ArrayInitLoopExpr>(Init);
3011 findConstructionContexts(
3012 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3013 AILE ? AILE->getSubExpr() : Init);
3015 // Keep track of the last non-null block, as 'Block' can be nulled out
3016 // if the initializer expression is something like a 'while' in a
3017 // statement-expression.
3018 CFGBlock *LastBlock = Block;
3020 if (Init) {
3021 if (HasTemporaries) {
3022 // For expression with temporaries go directly to subexpression to omit
3023 // generating destructors for the second time.
3024 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
3025 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
3026 LastBlock = newBlock;
3028 else {
3029 if (CFGBlock *newBlock = Visit(Init))
3030 LastBlock = newBlock;
3034 // If the type of VD is a VLA, then we must process its size expressions.
3035 // FIXME: This does not find the VLA if it is embedded in other types,
3036 // like here: `int (*p_vla)[x];`
3037 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
3038 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
3039 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
3040 LastBlock = newBlock;
3043 maybeAddScopeBeginForVarDecl(Block, VD, DS);
3045 // Remove variable from local scope.
3046 if (ScopePos && VD == *ScopePos)
3047 ++ScopePos;
3049 CFGBlock *B = LastBlock;
3050 if (blockAfterStaticInit) {
3051 Succ = B;
3052 Block = createBlock(false);
3053 Block->setTerminator(DS);
3054 addSuccessor(Block, blockAfterStaticInit);
3055 addSuccessor(Block, B);
3056 B = Block;
3059 return B;
3062 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
3063 // We may see an if statement in the middle of a basic block, or it may be the
3064 // first statement we are processing. In either case, we create a new basic
3065 // block. First, we create the blocks for the then...else statements, and
3066 // then we create the block containing the if statement. If we were in the
3067 // middle of a block, we stop processing that block. That block is then the
3068 // implicit successor for the "then" and "else" clauses.
3070 // Save local scope position because in case of condition variable ScopePos
3071 // won't be restored when traversing AST.
3072 SaveAndRestore save_scope_pos(ScopePos);
3074 // Create local scope for C++17 if init-stmt if one exists.
3075 if (Stmt *Init = I->getInit())
3076 addLocalScopeForStmt(Init);
3078 // Create local scope for possible condition variable.
3079 // Store scope position. Add implicit destructor.
3080 if (VarDecl *VD = I->getConditionVariable())
3081 addLocalScopeForVarDecl(VD);
3083 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
3085 // The block we were processing is now finished. Make it the successor
3086 // block.
3087 if (Block) {
3088 Succ = Block;
3089 if (badCFG)
3090 return nullptr;
3093 // Process the false branch.
3094 CFGBlock *ElseBlock = Succ;
3096 if (Stmt *Else = I->getElse()) {
3097 SaveAndRestore sv(Succ);
3099 // NULL out Block so that the recursive call to Visit will
3100 // create a new basic block.
3101 Block = nullptr;
3103 // If branch is not a compound statement create implicit scope
3104 // and add destructors.
3105 if (!isa<CompoundStmt>(Else))
3106 addLocalScopeAndDtors(Else);
3108 ElseBlock = addStmt(Else);
3110 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
3111 ElseBlock = sv.get();
3112 else if (Block) {
3113 if (badCFG)
3114 return nullptr;
3118 // Process the true branch.
3119 CFGBlock *ThenBlock;
3121 Stmt *Then = I->getThen();
3122 assert(Then);
3123 SaveAndRestore sv(Succ);
3124 Block = nullptr;
3126 // If branch is not a compound statement create implicit scope
3127 // and add destructors.
3128 if (!isa<CompoundStmt>(Then))
3129 addLocalScopeAndDtors(Then);
3131 ThenBlock = addStmt(Then);
3133 if (!ThenBlock) {
3134 // We can reach here if the "then" body has all NullStmts.
3135 // Create an empty block so we can distinguish between true and false
3136 // branches in path-sensitive analyses.
3137 ThenBlock = createBlock(false);
3138 addSuccessor(ThenBlock, sv.get());
3139 } else if (Block) {
3140 if (badCFG)
3141 return nullptr;
3145 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
3146 // having these handle the actual control-flow jump. Note that
3147 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
3148 // we resort to the old control-flow behavior. This special handling
3149 // removes infeasible paths from the control-flow graph by having the
3150 // control-flow transfer of '&&' or '||' go directly into the then/else
3151 // blocks directly.
3152 BinaryOperator *Cond =
3153 (I->isConsteval() || I->getConditionVariable())
3154 ? nullptr
3155 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
3156 CFGBlock *LastBlock;
3157 if (Cond && Cond->isLogicalOp())
3158 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
3159 else {
3160 // Now create a new block containing the if statement.
3161 Block = createBlock(false);
3163 // Set the terminator of the new block to the If statement.
3164 Block->setTerminator(I);
3166 // See if this is a known constant.
3167 TryResult KnownVal;
3168 if (!I->isConsteval())
3169 KnownVal = tryEvaluateBool(I->getCond());
3171 // Add the successors. If we know that specific branches are
3172 // unreachable, inform addSuccessor() of that knowledge.
3173 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
3174 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
3176 // Add the condition as the last statement in the new block. This may
3177 // create new blocks as the condition may contain control-flow. Any newly
3178 // created blocks will be pointed to be "Block".
3179 LastBlock = addStmt(I->getCond());
3181 // If the IfStmt contains a condition variable, add it and its
3182 // initializer to the CFG.
3183 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
3184 autoCreateBlock();
3185 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
3189 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
3190 if (Stmt *Init = I->getInit()) {
3191 autoCreateBlock();
3192 LastBlock = addStmt(Init);
3195 return LastBlock;
3198 CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
3199 // If we were in the middle of a block we stop processing that block.
3201 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
3202 // means that the code afterwards is DEAD (unreachable). We still keep
3203 // a basic block for that code; a simple "mark-and-sweep" from the entry
3204 // block will be able to report such dead blocks.
3205 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
3207 // Create the new block.
3208 Block = createBlock(false);
3210 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
3212 if (auto *R = dyn_cast<ReturnStmt>(S))
3213 findConstructionContexts(
3214 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
3215 R->getRetValue());
3217 // If the one of the destructors does not return, we already have the Exit
3218 // block as a successor.
3219 if (!Block->hasNoReturnElement())
3220 addSuccessor(Block, &cfg->getExit());
3222 // Add the return statement to the block.
3223 appendStmt(Block, S);
3225 // Visit children
3226 if (ReturnStmt *RS = dyn_cast<ReturnStmt>(S)) {
3227 if (Expr *O = RS->getRetValue())
3228 return Visit(O, AddStmtChoice::AlwaysAdd, /*ExternallyDestructed=*/true);
3229 return Block;
3232 CoreturnStmt *CRS = cast<CoreturnStmt>(S);
3233 auto *B = Block;
3234 if (CFGBlock *R = Visit(CRS->getPromiseCall()))
3235 B = R;
3237 if (Expr *RV = CRS->getOperand())
3238 if (RV->getType()->isVoidType() && !isa<InitListExpr>(RV))
3239 // A non-initlist void expression.
3240 if (CFGBlock *R = Visit(RV))
3241 B = R;
3243 return B;
3246 CFGBlock *CFGBuilder::VisitCoroutineSuspendExpr(CoroutineSuspendExpr *E,
3247 AddStmtChoice asc) {
3248 // We're modelling the pre-coro-xform CFG. Thus just evalate the various
3249 // active components of the co_await or co_yield. Note we do not model the
3250 // edge from the builtin_suspend to the exit node.
3251 if (asc.alwaysAdd(*this, E)) {
3252 autoCreateBlock();
3253 appendStmt(Block, E);
3255 CFGBlock *B = Block;
3256 if (auto *R = Visit(E->getResumeExpr()))
3257 B = R;
3258 if (auto *R = Visit(E->getSuspendExpr()))
3259 B = R;
3260 if (auto *R = Visit(E->getReadyExpr()))
3261 B = R;
3262 if (auto *R = Visit(E->getCommonExpr()))
3263 B = R;
3264 return B;
3267 CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
3268 // SEHExceptStmt are treated like labels, so they are the first statement in a
3269 // block.
3271 // Save local scope position because in case of exception variable ScopePos
3272 // won't be restored when traversing AST.
3273 SaveAndRestore save_scope_pos(ScopePos);
3275 addStmt(ES->getBlock());
3276 CFGBlock *SEHExceptBlock = Block;
3277 if (!SEHExceptBlock)
3278 SEHExceptBlock = createBlock();
3280 appendStmt(SEHExceptBlock, ES);
3282 // Also add the SEHExceptBlock as a label, like with regular labels.
3283 SEHExceptBlock->setLabel(ES);
3285 // Bail out if the CFG is bad.
3286 if (badCFG)
3287 return nullptr;
3289 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3290 Block = nullptr;
3292 return SEHExceptBlock;
3295 CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3296 return VisitCompoundStmt(FS->getBlock(), /*ExternallyDestructed=*/false);
3299 CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3300 // "__leave" is a control-flow statement. Thus we stop processing the current
3301 // block.
3302 if (badCFG)
3303 return nullptr;
3305 // Now create a new block that ends with the __leave statement.
3306 Block = createBlock(false);
3307 Block->setTerminator(LS);
3309 // If there is no target for the __leave, then we are looking at an incomplete
3310 // AST. This means that the CFG cannot be constructed.
3311 if (SEHLeaveJumpTarget.block) {
3312 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3313 addSuccessor(Block, SEHLeaveJumpTarget.block);
3314 } else
3315 badCFG = true;
3317 return Block;
3320 CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3321 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3322 // processing the current block.
3323 CFGBlock *SEHTrySuccessor = nullptr;
3325 if (Block) {
3326 if (badCFG)
3327 return nullptr;
3328 SEHTrySuccessor = Block;
3329 } else SEHTrySuccessor = Succ;
3331 // FIXME: Implement __finally support.
3332 if (Terminator->getFinallyHandler())
3333 return NYS();
3335 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3337 // Create a new block that will contain the __try statement.
3338 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3340 // Add the terminator in the __try block.
3341 NewTryTerminatedBlock->setTerminator(Terminator);
3343 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3344 // The code after the try is the implicit successor if there's an __except.
3345 Succ = SEHTrySuccessor;
3346 Block = nullptr;
3347 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3348 if (!ExceptBlock)
3349 return nullptr;
3350 // Add this block to the list of successors for the block with the try
3351 // statement.
3352 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3354 if (PrevSEHTryTerminatedBlock)
3355 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3356 else
3357 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3359 // The code after the try is the implicit successor.
3360 Succ = SEHTrySuccessor;
3362 // Save the current "__try" context.
3363 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
3364 cfg->addTryDispatchBlock(TryTerminatedBlock);
3366 // Save the current value for the __leave target.
3367 // All __leaves should go to the code following the __try
3368 // (FIXME: or if the __try has a __finally, to the __finally.)
3369 SaveAndRestore save_break(SEHLeaveJumpTarget);
3370 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3372 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3373 Block = nullptr;
3374 return addStmt(Terminator->getTryBlock());
3377 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
3378 // Get the block of the labeled statement. Add it to our map.
3379 addStmt(L->getSubStmt());
3380 CFGBlock *LabelBlock = Block;
3382 if (!LabelBlock) // This can happen when the body is empty, i.e.
3383 LabelBlock = createBlock(); // scopes that only contains NullStmts.
3385 assert(!LabelMap.contains(L->getDecl()) && "label already in map");
3386 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
3388 // Labels partition blocks, so this is the end of the basic block we were
3389 // processing (L is the block's label). Because this is label (and we have
3390 // already processed the substatement) there is no extra control-flow to worry
3391 // about.
3392 LabelBlock->setLabel(L);
3393 if (badCFG)
3394 return nullptr;
3396 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3397 Block = nullptr;
3399 // This block is now the implicit successor of other blocks.
3400 Succ = LabelBlock;
3402 return LabelBlock;
3405 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3406 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3407 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3408 if (Expr *CopyExpr = CI.getCopyExpr()) {
3409 CFGBlock *Tmp = Visit(CopyExpr);
3410 if (Tmp)
3411 LastBlock = Tmp;
3414 return LastBlock;
3417 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3418 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3420 unsigned Idx = 0;
3421 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3422 et = E->capture_init_end();
3423 it != et; ++it, ++Idx) {
3424 if (Expr *Init = *it) {
3425 // If the initializer is an ArrayInitLoopExpr, we want to extract the
3426 // initializer, that's used for each element.
3427 auto *AILEInit = extractElementInitializerFromNestedAILE(
3428 dyn_cast<ArrayInitLoopExpr>(Init));
3430 findConstructionContexts(ConstructionContextLayer::create(
3431 cfg->getBumpVectorContext(), {E, Idx}),
3432 AILEInit ? AILEInit : Init);
3434 CFGBlock *Tmp = Visit(Init);
3435 if (Tmp)
3436 LastBlock = Tmp;
3439 return LastBlock;
3442 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
3443 // Goto is a control-flow statement. Thus we stop processing the current
3444 // block and create a new one.
3446 Block = createBlock(false);
3447 Block->setTerminator(G);
3449 // If we already know the mapping to the label block add the successor now.
3450 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
3452 if (I == LabelMap.end())
3453 // We will need to backpatch this block later.
3454 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3455 else {
3456 JumpTarget JT = I->second;
3457 addSuccessor(Block, JT.block);
3458 addScopeChangesHandling(ScopePos, JT.scopePosition, G);
3461 return Block;
3464 CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3465 // Goto is a control-flow statement. Thus we stop processing the current
3466 // block and create a new one.
3468 if (!G->isAsmGoto())
3469 return VisitStmt(G, asc);
3471 if (Block) {
3472 Succ = Block;
3473 if (badCFG)
3474 return nullptr;
3476 Block = createBlock();
3477 Block->setTerminator(G);
3478 // We will backpatch this block later for all the labels.
3479 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3480 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3481 // used to avoid adding "Succ" again.
3482 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3483 return VisitChildren(G);
3486 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
3487 CFGBlock *LoopSuccessor = nullptr;
3489 // Save local scope position because in case of condition variable ScopePos
3490 // won't be restored when traversing AST.
3491 SaveAndRestore save_scope_pos(ScopePos);
3493 // Create local scope for init statement and possible condition variable.
3494 // Add destructor for init statement and condition variable.
3495 // Store scope position for continue statement.
3496 if (Stmt *Init = F->getInit())
3497 addLocalScopeForStmt(Init);
3498 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3500 if (VarDecl *VD = F->getConditionVariable())
3501 addLocalScopeForVarDecl(VD);
3502 LocalScope::const_iterator ContinueScopePos = ScopePos;
3504 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
3506 addLoopExit(F);
3508 // "for" is a control-flow statement. Thus we stop processing the current
3509 // block.
3510 if (Block) {
3511 if (badCFG)
3512 return nullptr;
3513 LoopSuccessor = Block;
3514 } else
3515 LoopSuccessor = Succ;
3517 // Save the current value for the break targets.
3518 // All breaks should go to the code following the loop.
3519 SaveAndRestore save_break(BreakJumpTarget);
3520 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3522 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3524 // Now create the loop body.
3526 assert(F->getBody());
3528 // Save the current values for Block, Succ, continue and break targets.
3529 SaveAndRestore save_Block(Block), save_Succ(Succ);
3530 SaveAndRestore save_continue(ContinueJumpTarget);
3532 // Create an empty block to represent the transition block for looping back
3533 // to the head of the loop. If we have increment code, it will
3534 // go in this block as well.
3535 Block = Succ = TransitionBlock = createBlock(false);
3536 TransitionBlock->setLoopTarget(F);
3539 // Loop iteration (after increment) should end with destructor of Condition
3540 // variable (if any).
3541 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
3543 if (Stmt *I = F->getInc()) {
3544 // Generate increment code in its own basic block. This is the target of
3545 // continue statements.
3546 Succ = addStmt(I);
3549 // Finish up the increment (or empty) block if it hasn't been already.
3550 if (Block) {
3551 assert(Block == Succ);
3552 if (badCFG)
3553 return nullptr;
3554 Block = nullptr;
3557 // The starting block for the loop increment is the block that should
3558 // represent the 'loop target' for looping back to the start of the loop.
3559 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3560 ContinueJumpTarget.block->setLoopTarget(F);
3563 // If body is not a compound statement create implicit scope
3564 // and add destructors.
3565 if (!isa<CompoundStmt>(F->getBody()))
3566 addLocalScopeAndDtors(F->getBody());
3568 // Now populate the body block, and in the process create new blocks as we
3569 // walk the body of the loop.
3570 BodyBlock = addStmt(F->getBody());
3572 if (!BodyBlock) {
3573 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3574 // Use the continue jump target as the proxy for the body.
3575 BodyBlock = ContinueJumpTarget.block;
3577 else if (badCFG)
3578 return nullptr;
3581 // Because of short-circuit evaluation, the condition of the loop can span
3582 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3583 // evaluate the condition.
3584 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3586 do {
3587 Expr *C = F->getCond();
3588 SaveAndRestore save_scope_pos(ScopePos);
3590 // Specially handle logical operators, which have a slightly
3591 // more optimal CFG representation.
3592 if (BinaryOperator *Cond =
3593 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
3594 if (Cond->isLogicalOp()) {
3595 std::tie(EntryConditionBlock, ExitConditionBlock) =
3596 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3597 break;
3600 // The default case when not handling logical operators.
3601 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3602 ExitConditionBlock->setTerminator(F);
3604 // See if this is a known constant.
3605 TryResult KnownVal(true);
3607 if (C) {
3608 // Now add the actual condition to the condition block.
3609 // Because the condition itself may contain control-flow, new blocks may
3610 // be created. Thus we update "Succ" after adding the condition.
3611 Block = ExitConditionBlock;
3612 EntryConditionBlock = addStmt(C);
3614 // If this block contains a condition variable, add both the condition
3615 // variable and initializer to the CFG.
3616 if (VarDecl *VD = F->getConditionVariable()) {
3617 if (Expr *Init = VD->getInit()) {
3618 autoCreateBlock();
3619 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3620 assert(DS->isSingleDecl());
3621 findConstructionContexts(
3622 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
3623 Init);
3624 appendStmt(Block, DS);
3625 EntryConditionBlock = addStmt(Init);
3626 assert(Block == EntryConditionBlock);
3627 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3631 if (Block && badCFG)
3632 return nullptr;
3634 KnownVal = tryEvaluateBool(C);
3637 // Add the loop body entry as a successor to the condition.
3638 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3639 // Link up the condition block with the code that follows the loop. (the
3640 // false branch).
3641 addSuccessor(ExitConditionBlock,
3642 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3643 } while (false);
3645 // Link up the loop-back block to the entry condition block.
3646 addSuccessor(TransitionBlock, EntryConditionBlock);
3648 // The condition block is the implicit successor for any code above the loop.
3649 Succ = EntryConditionBlock;
3651 // If the loop contains initialization, create a new block for those
3652 // statements. This block can also contain statements that precede the loop.
3653 if (Stmt *I = F->getInit()) {
3654 SaveAndRestore save_scope_pos(ScopePos);
3655 ScopePos = LoopBeginScopePos;
3656 Block = createBlock();
3657 return addStmt(I);
3660 // There is no loop initialization. We are thus basically a while loop.
3661 // NULL out Block to force lazy block construction.
3662 Block = nullptr;
3663 Succ = EntryConditionBlock;
3664 return EntryConditionBlock;
3667 CFGBlock *
3668 CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3669 AddStmtChoice asc) {
3670 findConstructionContexts(
3671 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
3672 MTE->getSubExpr());
3674 return VisitStmt(MTE, asc);
3677 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
3678 if (asc.alwaysAdd(*this, M)) {
3679 autoCreateBlock();
3680 appendStmt(Block, M);
3682 return Visit(M->getBase());
3685 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
3686 // Objective-C fast enumeration 'for' statements:
3687 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3689 // for ( Type newVariable in collection_expression ) { statements }
3691 // becomes:
3693 // prologue:
3694 // 1. collection_expression
3695 // T. jump to loop_entry
3696 // loop_entry:
3697 // 1. side-effects of element expression
3698 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3699 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3700 // TB:
3701 // statements
3702 // T. jump to loop_entry
3703 // FB:
3704 // what comes after
3706 // and
3708 // Type existingItem;
3709 // for ( existingItem in expression ) { statements }
3711 // becomes:
3713 // the same with newVariable replaced with existingItem; the binding works
3714 // the same except that for one ObjCForCollectionStmt::getElement() returns
3715 // a DeclStmt and the other returns a DeclRefExpr.
3717 CFGBlock *LoopSuccessor = nullptr;
3719 if (Block) {
3720 if (badCFG)
3721 return nullptr;
3722 LoopSuccessor = Block;
3723 Block = nullptr;
3724 } else
3725 LoopSuccessor = Succ;
3727 // Build the condition blocks.
3728 CFGBlock *ExitConditionBlock = createBlock(false);
3730 // Set the terminator for the "exit" condition block.
3731 ExitConditionBlock->setTerminator(S);
3733 // The last statement in the block should be the ObjCForCollectionStmt, which
3734 // performs the actual binding to 'element' and determines if there are any
3735 // more items in the collection.
3736 appendStmt(ExitConditionBlock, S);
3737 Block = ExitConditionBlock;
3739 // Walk the 'element' expression to see if there are any side-effects. We
3740 // generate new blocks as necessary. We DON'T add the statement by default to
3741 // the CFG unless it contains control-flow.
3742 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3743 AddStmtChoice::NotAlwaysAdd);
3744 if (Block) {
3745 if (badCFG)
3746 return nullptr;
3747 Block = nullptr;
3750 // The condition block is the implicit successor for the loop body as well as
3751 // any code above the loop.
3752 Succ = EntryConditionBlock;
3754 // Now create the true branch.
3756 // Save the current values for Succ, continue and break targets.
3757 SaveAndRestore save_Block(Block), save_Succ(Succ);
3758 SaveAndRestore save_continue(ContinueJumpTarget),
3759 save_break(BreakJumpTarget);
3761 // Add an intermediate block between the BodyBlock and the
3762 // EntryConditionBlock to represent the "loop back" transition, for looping
3763 // back to the head of the loop.
3764 CFGBlock *LoopBackBlock = nullptr;
3765 Succ = LoopBackBlock = createBlock();
3766 LoopBackBlock->setLoopTarget(S);
3768 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3769 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
3771 CFGBlock *BodyBlock = addStmt(S->getBody());
3773 if (!BodyBlock)
3774 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
3775 else if (Block) {
3776 if (badCFG)
3777 return nullptr;
3780 // This new body block is a successor to our "exit" condition block.
3781 addSuccessor(ExitConditionBlock, BodyBlock);
3784 // Link up the condition block with the code that follows the loop.
3785 // (the false branch).
3786 addSuccessor(ExitConditionBlock, LoopSuccessor);
3788 // Now create a prologue block to contain the collection expression.
3789 Block = createBlock();
3790 return addStmt(S->getCollection());
3793 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3794 // Inline the body.
3795 return addStmt(S->getSubStmt());
3796 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3799 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
3800 // FIXME: Add locking 'primitives' to CFG for @synchronized.
3802 // Inline the body.
3803 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
3805 // The sync body starts its own basic block. This makes it a little easier
3806 // for diagnostic clients.
3807 if (SyncBlock) {
3808 if (badCFG)
3809 return nullptr;
3811 Block = nullptr;
3812 Succ = SyncBlock;
3815 // Add the @synchronized to the CFG.
3816 autoCreateBlock();
3817 appendStmt(Block, S);
3819 // Inline the sync expression.
3820 return addStmt(S->getSynchExpr());
3823 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3824 autoCreateBlock();
3826 // Add the PseudoObject as the last thing.
3827 appendStmt(Block, E);
3829 CFGBlock *lastBlock = Block;
3831 // Before that, evaluate all of the semantics in order. In
3832 // CFG-land, that means appending them in reverse order.
3833 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3834 Expr *Semantic = E->getSemanticExpr(--i);
3836 // If the semantic is an opaque value, we're being asked to bind
3837 // it to its source expression.
3838 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3839 Semantic = OVE->getSourceExpr();
3841 if (CFGBlock *B = Visit(Semantic))
3842 lastBlock = B;
3845 return lastBlock;
3848 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
3849 CFGBlock *LoopSuccessor = nullptr;
3851 // Save local scope position because in case of condition variable ScopePos
3852 // won't be restored when traversing AST.
3853 SaveAndRestore save_scope_pos(ScopePos);
3855 // Create local scope for possible condition variable.
3856 // Store scope position for continue statement.
3857 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3858 if (VarDecl *VD = W->getConditionVariable()) {
3859 addLocalScopeForVarDecl(VD);
3860 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3862 addLoopExit(W);
3864 // "while" is a control-flow statement. Thus we stop processing the current
3865 // block.
3866 if (Block) {
3867 if (badCFG)
3868 return nullptr;
3869 LoopSuccessor = Block;
3870 Block = nullptr;
3871 } else {
3872 LoopSuccessor = Succ;
3875 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
3877 // Process the loop body.
3879 assert(W->getBody());
3881 // Save the current values for Block, Succ, continue and break targets.
3882 SaveAndRestore save_Block(Block), save_Succ(Succ);
3883 SaveAndRestore save_continue(ContinueJumpTarget),
3884 save_break(BreakJumpTarget);
3886 // Create an empty block to represent the transition block for looping back
3887 // to the head of the loop.
3888 Succ = TransitionBlock = createBlock(false);
3889 TransitionBlock->setLoopTarget(W);
3890 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
3892 // All breaks should go to the code following the loop.
3893 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3895 // Loop body should end with destructor of Condition variable (if any).
3896 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
3898 // If body is not a compound statement create implicit scope
3899 // and add destructors.
3900 if (!isa<CompoundStmt>(W->getBody()))
3901 addLocalScopeAndDtors(W->getBody());
3903 // Create the body. The returned block is the entry to the loop body.
3904 BodyBlock = addStmt(W->getBody());
3906 if (!BodyBlock)
3907 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
3908 else if (Block && badCFG)
3909 return nullptr;
3912 // Because of short-circuit evaluation, the condition of the loop can span
3913 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3914 // evaluate the condition.
3915 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
3917 do {
3918 Expr *C = W->getCond();
3920 // Specially handle logical operators, which have a slightly
3921 // more optimal CFG representation.
3922 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
3923 if (Cond->isLogicalOp()) {
3924 std::tie(EntryConditionBlock, ExitConditionBlock) =
3925 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
3926 break;
3929 // The default case when not handling logical operators.
3930 ExitConditionBlock = createBlock(false);
3931 ExitConditionBlock->setTerminator(W);
3933 // Now add the actual condition to the condition block.
3934 // Because the condition itself may contain control-flow, new blocks may
3935 // be created. Thus we update "Succ" after adding the condition.
3936 Block = ExitConditionBlock;
3937 Block = EntryConditionBlock = addStmt(C);
3939 // If this block contains a condition variable, add both the condition
3940 // variable and initializer to the CFG.
3941 if (VarDecl *VD = W->getConditionVariable()) {
3942 if (Expr *Init = VD->getInit()) {
3943 autoCreateBlock();
3944 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3945 assert(DS->isSingleDecl());
3946 findConstructionContexts(
3947 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3948 const_cast<DeclStmt *>(DS)),
3949 Init);
3950 appendStmt(Block, DS);
3951 EntryConditionBlock = addStmt(Init);
3952 assert(Block == EntryConditionBlock);
3953 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
3957 if (Block && badCFG)
3958 return nullptr;
3960 // See if this is a known constant.
3961 const TryResult& KnownVal = tryEvaluateBool(C);
3963 // Add the loop body entry as a successor to the condition.
3964 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
3965 // Link up the condition block with the code that follows the loop. (the
3966 // false branch).
3967 addSuccessor(ExitConditionBlock,
3968 KnownVal.isTrue() ? nullptr : LoopSuccessor);
3969 } while(false);
3971 // Link up the loop-back block to the entry condition block.
3972 addSuccessor(TransitionBlock, EntryConditionBlock);
3974 // There can be no more statements in the condition block since we loop back
3975 // to this block. NULL out Block to force lazy creation of another block.
3976 Block = nullptr;
3978 // Return the condition block, which is the dominating block for the loop.
3979 Succ = EntryConditionBlock;
3980 return EntryConditionBlock;
3983 CFGBlock *CFGBuilder::VisitArrayInitLoopExpr(ArrayInitLoopExpr *A,
3984 AddStmtChoice asc) {
3985 if (asc.alwaysAdd(*this, A)) {
3986 autoCreateBlock();
3987 appendStmt(Block, A);
3990 CFGBlock *B = Block;
3992 if (CFGBlock *R = Visit(A->getSubExpr()))
3993 B = R;
3995 auto *OVE = dyn_cast<OpaqueValueExpr>(A->getCommonExpr());
3996 assert(OVE && "ArrayInitLoopExpr->getCommonExpr() should be wrapped in an "
3997 "OpaqueValueExpr!");
3998 if (CFGBlock *R = Visit(OVE->getSourceExpr()))
3999 B = R;
4001 return B;
4004 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *CS) {
4005 // ObjCAtCatchStmt are treated like labels, so they are the first statement
4006 // in a block.
4008 // Save local scope position because in case of exception variable ScopePos
4009 // won't be restored when traversing AST.
4010 SaveAndRestore save_scope_pos(ScopePos);
4012 if (CS->getCatchBody())
4013 addStmt(CS->getCatchBody());
4015 CFGBlock *CatchBlock = Block;
4016 if (!CatchBlock)
4017 CatchBlock = createBlock();
4019 appendStmt(CatchBlock, CS);
4021 // Also add the ObjCAtCatchStmt as a label, like with regular labels.
4022 CatchBlock->setLabel(CS);
4024 // Bail out if the CFG is bad.
4025 if (badCFG)
4026 return nullptr;
4028 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4029 Block = nullptr;
4031 return CatchBlock;
4034 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4035 // If we were in the middle of a block we stop processing that block.
4036 if (badCFG)
4037 return nullptr;
4039 // Create the new block.
4040 Block = createBlock(false);
4042 if (TryTerminatedBlock)
4043 // The current try statement is the only successor.
4044 addSuccessor(Block, TryTerminatedBlock);
4045 else
4046 // otherwise the Exit block is the only successor.
4047 addSuccessor(Block, &cfg->getExit());
4049 // Add the statement to the block. This may create new blocks if S contains
4050 // control-flow (short-circuit operations).
4051 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
4054 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *Terminator) {
4055 // "@try"/"@catch" is a control-flow statement. Thus we stop processing the
4056 // current block.
4057 CFGBlock *TrySuccessor = nullptr;
4059 if (Block) {
4060 if (badCFG)
4061 return nullptr;
4062 TrySuccessor = Block;
4063 } else
4064 TrySuccessor = Succ;
4066 // FIXME: Implement @finally support.
4067 if (Terminator->getFinallyStmt())
4068 return NYS();
4070 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4072 // Create a new block that will contain the try statement.
4073 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4074 // Add the terminator in the try block.
4075 NewTryTerminatedBlock->setTerminator(Terminator);
4077 bool HasCatchAll = false;
4078 for (ObjCAtCatchStmt *CS : Terminator->catch_stmts()) {
4079 // The code after the try is the implicit successor.
4080 Succ = TrySuccessor;
4081 if (CS->hasEllipsis()) {
4082 HasCatchAll = true;
4084 Block = nullptr;
4085 CFGBlock *CatchBlock = VisitObjCAtCatchStmt(CS);
4086 if (!CatchBlock)
4087 return nullptr;
4088 // Add this block to the list of successors for the block with the try
4089 // statement.
4090 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4093 // FIXME: This needs updating when @finally support is added.
4094 if (!HasCatchAll) {
4095 if (PrevTryTerminatedBlock)
4096 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4097 else
4098 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4101 // The code after the try is the implicit successor.
4102 Succ = TrySuccessor;
4104 // Save the current "try" context.
4105 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4106 cfg->addTryDispatchBlock(TryTerminatedBlock);
4108 assert(Terminator->getTryBody() && "try must contain a non-NULL body");
4109 Block = nullptr;
4110 return addStmt(Terminator->getTryBody());
4113 CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
4114 AddStmtChoice asc) {
4115 findConstructionContextsForArguments(ME);
4117 autoCreateBlock();
4118 appendObjCMessage(Block, ME);
4120 return VisitChildren(ME);
4123 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
4124 // If we were in the middle of a block we stop processing that block.
4125 if (badCFG)
4126 return nullptr;
4128 // Create the new block.
4129 Block = createBlock(false);
4131 if (TryTerminatedBlock)
4132 // The current try statement is the only successor.
4133 addSuccessor(Block, TryTerminatedBlock);
4134 else
4135 // otherwise the Exit block is the only successor.
4136 addSuccessor(Block, &cfg->getExit());
4138 // Add the statement to the block. This may create new blocks if S contains
4139 // control-flow (short-circuit operations).
4140 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
4143 CFGBlock *CFGBuilder::VisitCXXTypeidExpr(CXXTypeidExpr *S, AddStmtChoice asc) {
4144 if (asc.alwaysAdd(*this, S)) {
4145 autoCreateBlock();
4146 appendStmt(Block, S);
4149 // C++ [expr.typeid]p3:
4150 // When typeid is applied to an expression other than an glvalue of a
4151 // polymorphic class type [...] [the] expression is an unevaluated
4152 // operand. [...]
4153 // We add only potentially evaluated statements to the block to avoid
4154 // CFG generation for unevaluated operands.
4155 if (!S->isTypeDependent() && S->isPotentiallyEvaluated())
4156 return VisitChildren(S);
4158 // Return block without CFG for unevaluated operands.
4159 return Block;
4162 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
4163 CFGBlock *LoopSuccessor = nullptr;
4165 addLoopExit(D);
4167 // "do...while" is a control-flow statement. Thus we stop processing the
4168 // current block.
4169 if (Block) {
4170 if (badCFG)
4171 return nullptr;
4172 LoopSuccessor = Block;
4173 } else
4174 LoopSuccessor = Succ;
4176 // Because of short-circuit evaluation, the condition of the loop can span
4177 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
4178 // evaluate the condition.
4179 CFGBlock *ExitConditionBlock = createBlock(false);
4180 CFGBlock *EntryConditionBlock = ExitConditionBlock;
4182 // Set the terminator for the "exit" condition block.
4183 ExitConditionBlock->setTerminator(D);
4185 // Now add the actual condition to the condition block. Because the condition
4186 // itself may contain control-flow, new blocks may be created.
4187 if (Stmt *C = D->getCond()) {
4188 Block = ExitConditionBlock;
4189 EntryConditionBlock = addStmt(C);
4190 if (Block) {
4191 if (badCFG)
4192 return nullptr;
4196 // The condition block is the implicit successor for the loop body.
4197 Succ = EntryConditionBlock;
4199 // See if this is a known constant.
4200 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
4202 // Process the loop body.
4203 CFGBlock *BodyBlock = nullptr;
4205 assert(D->getBody());
4207 // Save the current values for Block, Succ, and continue and break targets
4208 SaveAndRestore save_Block(Block), save_Succ(Succ);
4209 SaveAndRestore save_continue(ContinueJumpTarget),
4210 save_break(BreakJumpTarget);
4212 // All continues within this loop should go to the condition block
4213 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
4215 // All breaks should go to the code following the loop.
4216 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4218 // NULL out Block to force lazy instantiation of blocks for the body.
4219 Block = nullptr;
4221 // If body is not a compound statement create implicit scope
4222 // and add destructors.
4223 if (!isa<CompoundStmt>(D->getBody()))
4224 addLocalScopeAndDtors(D->getBody());
4226 // Create the body. The returned block is the entry to the loop body.
4227 BodyBlock = addStmt(D->getBody());
4229 if (!BodyBlock)
4230 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
4231 else if (Block) {
4232 if (badCFG)
4233 return nullptr;
4236 // Add an intermediate block between the BodyBlock and the
4237 // ExitConditionBlock to represent the "loop back" transition. Create an
4238 // empty block to represent the transition block for looping back to the
4239 // head of the loop.
4240 // FIXME: Can we do this more efficiently without adding another block?
4241 Block = nullptr;
4242 Succ = BodyBlock;
4243 CFGBlock *LoopBackBlock = createBlock();
4244 LoopBackBlock->setLoopTarget(D);
4246 if (!KnownVal.isFalse())
4247 // Add the loop body entry as a successor to the condition.
4248 addSuccessor(ExitConditionBlock, LoopBackBlock);
4249 else
4250 addSuccessor(ExitConditionBlock, nullptr);
4253 // Link up the condition block with the code that follows the loop.
4254 // (the false branch).
4255 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4257 // There can be no more statements in the body block(s) since we loop back to
4258 // the body. NULL out Block to force lazy creation of another block.
4259 Block = nullptr;
4261 // Return the loop body, which is the dominating block for the loop.
4262 Succ = BodyBlock;
4263 return BodyBlock;
4266 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
4267 // "continue" is a control-flow statement. Thus we stop processing the
4268 // current block.
4269 if (badCFG)
4270 return nullptr;
4272 // Now create a new block that ends with the continue statement.
4273 Block = createBlock(false);
4274 Block->setTerminator(C);
4276 // If there is no target for the continue, then we are looking at an
4277 // incomplete AST. This means the CFG cannot be constructed.
4278 if (ContinueJumpTarget.block) {
4279 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
4280 addSuccessor(Block, ContinueJumpTarget.block);
4281 } else
4282 badCFG = true;
4284 return Block;
4287 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
4288 AddStmtChoice asc) {
4289 if (asc.alwaysAdd(*this, E)) {
4290 autoCreateBlock();
4291 appendStmt(Block, E);
4294 // VLA types have expressions that must be evaluated.
4295 // Evaluation is done only for `sizeof`.
4297 if (E->getKind() != UETT_SizeOf)
4298 return Block;
4300 CFGBlock *lastBlock = Block;
4302 if (E->isArgumentType()) {
4303 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
4304 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
4305 lastBlock = addStmt(VA->getSizeExpr());
4307 return lastBlock;
4310 /// VisitStmtExpr - Utility method to handle (nested) statement
4311 /// expressions (a GCC extension).
4312 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
4313 if (asc.alwaysAdd(*this, SE)) {
4314 autoCreateBlock();
4315 appendStmt(Block, SE);
4317 return VisitCompoundStmt(SE->getSubStmt(), /*ExternallyDestructed=*/true);
4320 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
4321 // "switch" is a control-flow statement. Thus we stop processing the current
4322 // block.
4323 CFGBlock *SwitchSuccessor = nullptr;
4325 // Save local scope position because in case of condition variable ScopePos
4326 // won't be restored when traversing AST.
4327 SaveAndRestore save_scope_pos(ScopePos);
4329 // Create local scope for C++17 switch init-stmt if one exists.
4330 if (Stmt *Init = Terminator->getInit())
4331 addLocalScopeForStmt(Init);
4333 // Create local scope for possible condition variable.
4334 // Store scope position. Add implicit destructor.
4335 if (VarDecl *VD = Terminator->getConditionVariable())
4336 addLocalScopeForVarDecl(VD);
4338 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
4340 if (Block) {
4341 if (badCFG)
4342 return nullptr;
4343 SwitchSuccessor = Block;
4344 } else SwitchSuccessor = Succ;
4346 // Save the current "switch" context.
4347 SaveAndRestore save_switch(SwitchTerminatedBlock),
4348 save_default(DefaultCaseBlock);
4349 SaveAndRestore save_break(BreakJumpTarget);
4351 // Set the "default" case to be the block after the switch statement. If the
4352 // switch statement contains a "default:", this value will be overwritten with
4353 // the block for that code.
4354 DefaultCaseBlock = SwitchSuccessor;
4356 // Create a new block that will contain the switch statement.
4357 SwitchTerminatedBlock = createBlock(false);
4359 // Now process the switch body. The code after the switch is the implicit
4360 // successor.
4361 Succ = SwitchSuccessor;
4362 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
4364 // When visiting the body, the case statements should automatically get linked
4365 // up to the switch. We also don't keep a pointer to the body, since all
4366 // control-flow from the switch goes to case/default statements.
4367 assert(Terminator->getBody() && "switch must contain a non-NULL body");
4368 Block = nullptr;
4370 // For pruning unreachable case statements, save the current state
4371 // for tracking the condition value.
4372 SaveAndRestore save_switchExclusivelyCovered(switchExclusivelyCovered, false);
4374 // Determine if the switch condition can be explicitly evaluated.
4375 assert(Terminator->getCond() && "switch condition must be non-NULL");
4376 Expr::EvalResult result;
4377 bool b = tryEvaluate(Terminator->getCond(), result);
4378 SaveAndRestore save_switchCond(switchCond, b ? &result : nullptr);
4380 // If body is not a compound statement create implicit scope
4381 // and add destructors.
4382 if (!isa<CompoundStmt>(Terminator->getBody()))
4383 addLocalScopeAndDtors(Terminator->getBody());
4385 addStmt(Terminator->getBody());
4386 if (Block) {
4387 if (badCFG)
4388 return nullptr;
4391 // If we have no "default:" case, the default transition is to the code
4392 // following the switch body. Moreover, take into account if all the
4393 // cases of a switch are covered (e.g., switching on an enum value).
4395 // Note: We add a successor to a switch that is considered covered yet has no
4396 // case statements if the enumeration has no enumerators.
4397 bool SwitchAlwaysHasSuccessor = false;
4398 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
4399 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
4400 Terminator->getSwitchCaseList();
4401 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
4402 !SwitchAlwaysHasSuccessor);
4404 // Add the terminator and condition in the switch block.
4405 SwitchTerminatedBlock->setTerminator(Terminator);
4406 Block = SwitchTerminatedBlock;
4407 CFGBlock *LastBlock = addStmt(Terminator->getCond());
4409 // If the SwitchStmt contains a condition variable, add both the
4410 // SwitchStmt and the condition variable initialization to the CFG.
4411 if (VarDecl *VD = Terminator->getConditionVariable()) {
4412 if (Expr *Init = VD->getInit()) {
4413 autoCreateBlock();
4414 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
4415 LastBlock = addStmt(Init);
4416 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
4420 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4421 if (Stmt *Init = Terminator->getInit()) {
4422 autoCreateBlock();
4423 LastBlock = addStmt(Init);
4426 return LastBlock;
4429 static bool shouldAddCase(bool &switchExclusivelyCovered,
4430 const Expr::EvalResult *switchCond,
4431 const CaseStmt *CS,
4432 ASTContext &Ctx) {
4433 if (!switchCond)
4434 return true;
4436 bool addCase = false;
4438 if (!switchExclusivelyCovered) {
4439 if (switchCond->Val.isInt()) {
4440 // Evaluate the LHS of the case value.
4441 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
4442 const llvm::APSInt &condInt = switchCond->Val.getInt();
4444 if (condInt == lhsInt) {
4445 addCase = true;
4446 switchExclusivelyCovered = true;
4448 else if (condInt > lhsInt) {
4449 if (const Expr *RHS = CS->getRHS()) {
4450 // Evaluate the RHS of the case value.
4451 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
4452 if (V2 >= condInt) {
4453 addCase = true;
4454 switchExclusivelyCovered = true;
4459 else
4460 addCase = true;
4462 return addCase;
4465 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
4466 // CaseStmts are essentially labels, so they are the first statement in a
4467 // block.
4468 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
4470 if (Stmt *Sub = CS->getSubStmt()) {
4471 // For deeply nested chains of CaseStmts, instead of doing a recursion
4472 // (which can blow out the stack), manually unroll and create blocks
4473 // along the way.
4474 while (isa<CaseStmt>(Sub)) {
4475 CFGBlock *currentBlock = createBlock(false);
4476 currentBlock->setLabel(CS);
4478 if (TopBlock)
4479 addSuccessor(LastBlock, currentBlock);
4480 else
4481 TopBlock = currentBlock;
4483 addSuccessor(SwitchTerminatedBlock,
4484 shouldAddCase(switchExclusivelyCovered, switchCond,
4485 CS, *Context)
4486 ? currentBlock : nullptr);
4488 LastBlock = currentBlock;
4489 CS = cast<CaseStmt>(Sub);
4490 Sub = CS->getSubStmt();
4493 addStmt(Sub);
4496 CFGBlock *CaseBlock = Block;
4497 if (!CaseBlock)
4498 CaseBlock = createBlock();
4500 // Cases statements partition blocks, so this is the top of the basic block we
4501 // were processing (the "case XXX:" is the label).
4502 CaseBlock->setLabel(CS);
4504 if (badCFG)
4505 return nullptr;
4507 // Add this block to the list of successors for the block with the switch
4508 // statement.
4509 assert(SwitchTerminatedBlock);
4510 addSuccessor(SwitchTerminatedBlock, CaseBlock,
4511 shouldAddCase(switchExclusivelyCovered, switchCond,
4512 CS, *Context));
4514 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4515 Block = nullptr;
4517 if (TopBlock) {
4518 addSuccessor(LastBlock, CaseBlock);
4519 Succ = TopBlock;
4520 } else {
4521 // This block is now the implicit successor of other blocks.
4522 Succ = CaseBlock;
4525 return Succ;
4528 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
4529 if (Terminator->getSubStmt())
4530 addStmt(Terminator->getSubStmt());
4532 DefaultCaseBlock = Block;
4534 if (!DefaultCaseBlock)
4535 DefaultCaseBlock = createBlock();
4537 // Default statements partition blocks, so this is the top of the basic block
4538 // we were processing (the "default:" is the label).
4539 DefaultCaseBlock->setLabel(Terminator);
4541 if (badCFG)
4542 return nullptr;
4544 // Unlike case statements, we don't add the default block to the successors
4545 // for the switch statement immediately. This is done when we finish
4546 // processing the switch statement. This allows for the default case
4547 // (including a fall-through to the code after the switch statement) to always
4548 // be the last successor of a switch-terminated block.
4550 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4551 Block = nullptr;
4553 // This block is now the implicit successor of other blocks.
4554 Succ = DefaultCaseBlock;
4556 return DefaultCaseBlock;
4559 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4560 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4561 // current block.
4562 CFGBlock *TrySuccessor = nullptr;
4564 if (Block) {
4565 if (badCFG)
4566 return nullptr;
4567 TrySuccessor = Block;
4568 } else
4569 TrySuccessor = Succ;
4571 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
4573 // Create a new block that will contain the try statement.
4574 CFGBlock *NewTryTerminatedBlock = createBlock(false);
4575 // Add the terminator in the try block.
4576 NewTryTerminatedBlock->setTerminator(Terminator);
4578 bool HasCatchAll = false;
4579 for (unsigned I = 0, E = Terminator->getNumHandlers(); I != E; ++I) {
4580 // The code after the try is the implicit successor.
4581 Succ = TrySuccessor;
4582 CXXCatchStmt *CS = Terminator->getHandler(I);
4583 if (CS->getExceptionDecl() == nullptr) {
4584 HasCatchAll = true;
4586 Block = nullptr;
4587 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
4588 if (!CatchBlock)
4589 return nullptr;
4590 // Add this block to the list of successors for the block with the try
4591 // statement.
4592 addSuccessor(NewTryTerminatedBlock, CatchBlock);
4594 if (!HasCatchAll) {
4595 if (PrevTryTerminatedBlock)
4596 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
4597 else
4598 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
4601 // The code after the try is the implicit successor.
4602 Succ = TrySuccessor;
4604 // Save the current "try" context.
4605 SaveAndRestore SaveTry(TryTerminatedBlock, NewTryTerminatedBlock);
4606 cfg->addTryDispatchBlock(TryTerminatedBlock);
4608 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
4609 Block = nullptr;
4610 return addStmt(Terminator->getTryBlock());
4613 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
4614 // CXXCatchStmt are treated like labels, so they are the first statement in a
4615 // block.
4617 // Save local scope position because in case of exception variable ScopePos
4618 // won't be restored when traversing AST.
4619 SaveAndRestore save_scope_pos(ScopePos);
4621 // Create local scope for possible exception variable.
4622 // Store scope position. Add implicit destructor.
4623 if (VarDecl *VD = CS->getExceptionDecl()) {
4624 LocalScope::const_iterator BeginScopePos = ScopePos;
4625 addLocalScopeForVarDecl(VD);
4626 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
4629 if (CS->getHandlerBlock())
4630 addStmt(CS->getHandlerBlock());
4632 CFGBlock *CatchBlock = Block;
4633 if (!CatchBlock)
4634 CatchBlock = createBlock();
4636 // CXXCatchStmt is more than just a label. They have semantic meaning
4637 // as well, as they implicitly "initialize" the catch variable. Add
4638 // it to the CFG as a CFGElement so that the control-flow of these
4639 // semantics gets captured.
4640 appendStmt(CatchBlock, CS);
4642 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4643 // labels.
4644 CatchBlock->setLabel(CS);
4646 // Bail out if the CFG is bad.
4647 if (badCFG)
4648 return nullptr;
4650 // We set Block to NULL to allow lazy creation of a new block (if necessary).
4651 Block = nullptr;
4653 return CatchBlock;
4656 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4657 // C++0x for-range statements are specified as [stmt.ranged]:
4659 // {
4660 // auto && __range = range-init;
4661 // for ( auto __begin = begin-expr,
4662 // __end = end-expr;
4663 // __begin != __end;
4664 // ++__begin ) {
4665 // for-range-declaration = *__begin;
4666 // statement
4667 // }
4668 // }
4670 // Save local scope position before the addition of the implicit variables.
4671 SaveAndRestore save_scope_pos(ScopePos);
4673 // Create local scopes and destructors for range, begin and end variables.
4674 if (Stmt *Range = S->getRangeStmt())
4675 addLocalScopeForStmt(Range);
4676 if (Stmt *Begin = S->getBeginStmt())
4677 addLocalScopeForStmt(Begin);
4678 if (Stmt *End = S->getEndStmt())
4679 addLocalScopeForStmt(End);
4680 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
4682 LocalScope::const_iterator ContinueScopePos = ScopePos;
4684 // "for" is a control-flow statement. Thus we stop processing the current
4685 // block.
4686 CFGBlock *LoopSuccessor = nullptr;
4687 if (Block) {
4688 if (badCFG)
4689 return nullptr;
4690 LoopSuccessor = Block;
4691 } else
4692 LoopSuccessor = Succ;
4694 // Save the current value for the break targets.
4695 // All breaks should go to the code following the loop.
4696 SaveAndRestore save_break(BreakJumpTarget);
4697 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4699 // The block for the __begin != __end expression.
4700 CFGBlock *ConditionBlock = createBlock(false);
4701 ConditionBlock->setTerminator(S);
4703 // Now add the actual condition to the condition block.
4704 if (Expr *C = S->getCond()) {
4705 Block = ConditionBlock;
4706 CFGBlock *BeginConditionBlock = addStmt(C);
4707 if (badCFG)
4708 return nullptr;
4709 assert(BeginConditionBlock == ConditionBlock &&
4710 "condition block in for-range was unexpectedly complex");
4711 (void)BeginConditionBlock;
4714 // The condition block is the implicit successor for the loop body as well as
4715 // any code above the loop.
4716 Succ = ConditionBlock;
4718 // See if this is a known constant.
4719 TryResult KnownVal(true);
4721 if (S->getCond())
4722 KnownVal = tryEvaluateBool(S->getCond());
4724 // Now create the loop body.
4726 assert(S->getBody());
4728 // Save the current values for Block, Succ, and continue targets.
4729 SaveAndRestore save_Block(Block), save_Succ(Succ);
4730 SaveAndRestore save_continue(ContinueJumpTarget);
4732 // Generate increment code in its own basic block. This is the target of
4733 // continue statements.
4734 Block = nullptr;
4735 Succ = addStmt(S->getInc());
4736 if (badCFG)
4737 return nullptr;
4738 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4740 // The starting block for the loop increment is the block that should
4741 // represent the 'loop target' for looping back to the start of the loop.
4742 ContinueJumpTarget.block->setLoopTarget(S);
4744 // Finish up the increment block and prepare to start the loop body.
4745 assert(Block);
4746 if (badCFG)
4747 return nullptr;
4748 Block = nullptr;
4750 // Add implicit scope and dtors for loop variable.
4751 addLocalScopeAndDtors(S->getLoopVarStmt());
4753 // If body is not a compound statement create implicit scope
4754 // and add destructors.
4755 if (!isa<CompoundStmt>(S->getBody()))
4756 addLocalScopeAndDtors(S->getBody());
4758 // Populate a new block to contain the loop body and loop variable.
4759 addStmt(S->getBody());
4761 if (badCFG)
4762 return nullptr;
4763 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
4764 if (badCFG)
4765 return nullptr;
4767 // This new body block is a successor to our condition block.
4768 addSuccessor(ConditionBlock,
4769 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
4772 // Link up the condition block with the code that follows the loop (the
4773 // false branch).
4774 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
4776 // Add the initialization statements.
4777 Block = createBlock();
4778 addStmt(S->getBeginStmt());
4779 addStmt(S->getEndStmt());
4780 CFGBlock *Head = addStmt(S->getRangeStmt());
4781 if (S->getInit())
4782 Head = addStmt(S->getInit());
4783 return Head;
4786 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
4787 AddStmtChoice asc, bool ExternallyDestructed) {
4788 if (BuildOpts.AddTemporaryDtors) {
4789 // If adding implicit destructors visit the full expression for adding
4790 // destructors of temporaries.
4791 TempDtorContext Context;
4792 VisitForTemporaryDtors(E->getSubExpr(), ExternallyDestructed, Context);
4794 // Full expression has to be added as CFGStmt so it will be sequenced
4795 // before destructors of it's temporaries.
4796 asc = asc.withAlwaysAdd(true);
4798 return Visit(E->getSubExpr(), asc);
4801 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4802 AddStmtChoice asc) {
4803 if (asc.alwaysAdd(*this, E)) {
4804 autoCreateBlock();
4805 appendStmt(Block, E);
4807 findConstructionContexts(
4808 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
4809 E->getSubExpr());
4811 // We do not want to propagate the AlwaysAdd property.
4812 asc = asc.withAlwaysAdd(false);
4814 return Visit(E->getSubExpr(), asc);
4817 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4818 AddStmtChoice asc) {
4819 // If the constructor takes objects as arguments by value, we need to properly
4820 // construct these objects. Construction contexts we find here aren't for the
4821 // constructor C, they're for its arguments only.
4822 findConstructionContextsForArguments(C);
4824 autoCreateBlock();
4825 appendConstructor(Block, C);
4827 return VisitChildren(C);
4830 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4831 AddStmtChoice asc) {
4832 autoCreateBlock();
4833 appendStmt(Block, NE);
4835 findConstructionContexts(
4836 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
4837 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
4839 if (NE->getInitializer())
4840 Block = Visit(NE->getInitializer());
4842 if (BuildOpts.AddCXXNewAllocator)
4843 appendNewAllocator(Block, NE);
4845 if (NE->isArray() && *NE->getArraySize())
4846 Block = Visit(*NE->getArraySize());
4848 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4849 E = NE->placement_arg_end(); I != E; ++I)
4850 Block = Visit(*I);
4852 return Block;
4855 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4856 AddStmtChoice asc) {
4857 autoCreateBlock();
4858 appendStmt(Block, DE);
4859 QualType DTy = DE->getDestroyedType();
4860 if (!DTy.isNull()) {
4861 DTy = DTy.getNonReferenceType();
4862 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4863 if (RD) {
4864 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4865 appendDeleteDtor(Block, RD, DE);
4869 return VisitChildren(DE);
4872 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4873 AddStmtChoice asc) {
4874 if (asc.alwaysAdd(*this, E)) {
4875 autoCreateBlock();
4876 appendStmt(Block, E);
4877 // We do not want to propagate the AlwaysAdd property.
4878 asc = asc.withAlwaysAdd(false);
4880 return Visit(E->getSubExpr(), asc);
4883 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4884 AddStmtChoice asc) {
4885 // If the constructor takes objects as arguments by value, we need to properly
4886 // construct these objects. Construction contexts we find here aren't for the
4887 // constructor C, they're for its arguments only.
4888 findConstructionContextsForArguments(C);
4890 autoCreateBlock();
4891 appendConstructor(Block, C);
4892 return VisitChildren(C);
4895 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4896 AddStmtChoice asc) {
4897 if (asc.alwaysAdd(*this, E)) {
4898 autoCreateBlock();
4899 appendStmt(Block, E);
4902 if (E->getCastKind() == CK_IntegralToBoolean)
4903 tryEvaluateBool(E->getSubExpr()->IgnoreParens());
4905 return Visit(E->getSubExpr(), AddStmtChoice());
4908 CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4909 return Visit(E->getSubExpr(), AddStmtChoice());
4912 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4913 // Lazily create the indirect-goto dispatch block if there isn't one already.
4914 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
4916 if (!IBlock) {
4917 IBlock = createBlock(false);
4918 cfg->setIndirectGotoBlock(IBlock);
4921 // IndirectGoto is a control-flow statement. Thus we stop processing the
4922 // current block and create a new one.
4923 if (badCFG)
4924 return nullptr;
4926 Block = createBlock(false);
4927 Block->setTerminator(I);
4928 addSuccessor(Block, IBlock);
4929 return addStmt(I->getTarget());
4932 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool ExternallyDestructed,
4933 TempDtorContext &Context) {
4934 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4936 tryAgain:
4937 if (!E) {
4938 badCFG = true;
4939 return nullptr;
4941 switch (E->getStmtClass()) {
4942 default:
4943 return VisitChildrenForTemporaryDtors(E, false, Context);
4945 case Stmt::InitListExprClass:
4946 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
4948 case Stmt::BinaryOperatorClass:
4949 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4950 ExternallyDestructed,
4951 Context);
4953 case Stmt::CXXBindTemporaryExprClass:
4954 return VisitCXXBindTemporaryExprForTemporaryDtors(
4955 cast<CXXBindTemporaryExpr>(E), ExternallyDestructed, Context);
4957 case Stmt::BinaryConditionalOperatorClass:
4958 case Stmt::ConditionalOperatorClass:
4959 return VisitConditionalOperatorForTemporaryDtors(
4960 cast<AbstractConditionalOperator>(E), ExternallyDestructed, Context);
4962 case Stmt::ImplicitCastExprClass:
4963 // For implicit cast we want ExternallyDestructed to be passed further.
4964 E = cast<CastExpr>(E)->getSubExpr();
4965 goto tryAgain;
4967 case Stmt::CXXFunctionalCastExprClass:
4968 // For functional cast we want ExternallyDestructed to be passed further.
4969 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4970 goto tryAgain;
4972 case Stmt::ConstantExprClass:
4973 E = cast<ConstantExpr>(E)->getSubExpr();
4974 goto tryAgain;
4976 case Stmt::ParenExprClass:
4977 E = cast<ParenExpr>(E)->getSubExpr();
4978 goto tryAgain;
4980 case Stmt::MaterializeTemporaryExprClass: {
4981 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4982 ExternallyDestructed = (MTE->getStorageDuration() != SD_FullExpression);
4983 SmallVector<const Expr *, 2> CommaLHSs;
4984 SmallVector<SubobjectAdjustment, 2> Adjustments;
4985 // Find the expression whose lifetime needs to be extended.
4986 E = const_cast<Expr *>(
4987 cast<MaterializeTemporaryExpr>(E)
4988 ->getSubExpr()
4989 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4990 // Visit the skipped comma operator left-hand sides for other temporaries.
4991 for (const Expr *CommaLHS : CommaLHSs) {
4992 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
4993 /*ExternallyDestructed=*/false, Context);
4995 goto tryAgain;
4998 case Stmt::BlockExprClass:
4999 // Don't recurse into blocks; their subexpressions don't get evaluated
5000 // here.
5001 return Block;
5003 case Stmt::LambdaExprClass: {
5004 // For lambda expressions, only recurse into the capture initializers,
5005 // and not the body.
5006 auto *LE = cast<LambdaExpr>(E);
5007 CFGBlock *B = Block;
5008 for (Expr *Init : LE->capture_inits()) {
5009 if (Init) {
5010 if (CFGBlock *R = VisitForTemporaryDtors(
5011 Init, /*ExternallyDestructed=*/true, Context))
5012 B = R;
5015 return B;
5018 case Stmt::StmtExprClass:
5019 // Don't recurse into statement expressions; any cleanups inside them
5020 // will be wrapped in their own ExprWithCleanups.
5021 return Block;
5023 case Stmt::CXXDefaultArgExprClass:
5024 E = cast<CXXDefaultArgExpr>(E)->getExpr();
5025 goto tryAgain;
5027 case Stmt::CXXDefaultInitExprClass:
5028 E = cast<CXXDefaultInitExpr>(E)->getExpr();
5029 goto tryAgain;
5033 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
5034 bool ExternallyDestructed,
5035 TempDtorContext &Context) {
5036 if (isa<LambdaExpr>(E)) {
5037 // Do not visit the children of lambdas; they have their own CFGs.
5038 return Block;
5041 // When visiting children for destructors we want to visit them in reverse
5042 // order that they will appear in the CFG. Because the CFG is built
5043 // bottom-up, this means we visit them in their natural order, which
5044 // reverses them in the CFG.
5045 CFGBlock *B = Block;
5046 for (Stmt *Child : E->children())
5047 if (Child)
5048 if (CFGBlock *R = VisitForTemporaryDtors(Child, ExternallyDestructed, Context))
5049 B = R;
5051 return B;
5054 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
5055 BinaryOperator *E, bool ExternallyDestructed, TempDtorContext &Context) {
5056 if (E->isCommaOp()) {
5057 // For the comma operator, the LHS expression is evaluated before the RHS
5058 // expression, so prepend temporary destructors for the LHS first.
5059 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5060 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), ExternallyDestructed, Context);
5061 return RHSBlock ? RHSBlock : LHSBlock;
5064 if (E->isLogicalOp()) {
5065 VisitForTemporaryDtors(E->getLHS(), false, Context);
5066 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
5067 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
5068 RHSExecuted.negate();
5070 // We do not know at CFG-construction time whether the right-hand-side was
5071 // executed, thus we add a branch node that depends on the temporary
5072 // constructor call.
5073 TempDtorContext RHSContext(
5074 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
5075 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
5076 InsertTempDtorDecisionBlock(RHSContext);
5078 return Block;
5081 if (E->isAssignmentOp()) {
5082 // For assignment operators, the RHS expression is evaluated before the LHS
5083 // expression, so prepend temporary destructors for the RHS first.
5084 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
5085 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
5086 return LHSBlock ? LHSBlock : RHSBlock;
5089 // Any other operator is visited normally.
5090 return VisitChildrenForTemporaryDtors(E, ExternallyDestructed, Context);
5093 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
5094 CXXBindTemporaryExpr *E, bool ExternallyDestructed, TempDtorContext &Context) {
5095 // First add destructors for temporaries in subexpression.
5096 // Because VisitCXXBindTemporaryExpr calls setDestructed:
5097 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), true, Context);
5098 if (!ExternallyDestructed) {
5099 // If lifetime of temporary is not prolonged (by assigning to constant
5100 // reference) add destructor for it.
5102 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
5104 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
5105 // If the destructor is marked as a no-return destructor, we need to
5106 // create a new block for the destructor which does not have as a
5107 // successor anything built thus far. Control won't flow out of this
5108 // block.
5109 if (B) Succ = B;
5110 Block = createNoReturnBlock();
5111 } else if (Context.needsTempDtorBranch()) {
5112 // If we need to introduce a branch, we add a new block that we will hook
5113 // up to a decision block later.
5114 if (B) Succ = B;
5115 Block = createBlock();
5116 } else {
5117 autoCreateBlock();
5119 if (Context.needsTempDtorBranch()) {
5120 Context.setDecisionPoint(Succ, E);
5122 appendTemporaryDtor(Block, E);
5124 B = Block;
5126 return B;
5129 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
5130 CFGBlock *FalseSucc) {
5131 if (!Context.TerminatorExpr) {
5132 // If no temporary was found, we do not need to insert a decision point.
5133 return;
5135 assert(Context.TerminatorExpr);
5136 CFGBlock *Decision = createBlock(false);
5137 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
5138 CFGTerminator::TemporaryDtorsBranch));
5139 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
5140 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
5141 !Context.KnownExecuted.isTrue());
5142 Block = Decision;
5145 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
5146 AbstractConditionalOperator *E, bool ExternallyDestructed,
5147 TempDtorContext &Context) {
5148 VisitForTemporaryDtors(E->getCond(), false, Context);
5149 CFGBlock *ConditionBlock = Block;
5150 CFGBlock *ConditionSucc = Succ;
5151 TryResult ConditionVal = tryEvaluateBool(E->getCond());
5152 TryResult NegatedVal = ConditionVal;
5153 if (NegatedVal.isKnown()) NegatedVal.negate();
5155 TempDtorContext TrueContext(
5156 bothKnownTrue(Context.KnownExecuted, ConditionVal));
5157 VisitForTemporaryDtors(E->getTrueExpr(), ExternallyDestructed, TrueContext);
5158 CFGBlock *TrueBlock = Block;
5160 Block = ConditionBlock;
5161 Succ = ConditionSucc;
5162 TempDtorContext FalseContext(
5163 bothKnownTrue(Context.KnownExecuted, NegatedVal));
5164 VisitForTemporaryDtors(E->getFalseExpr(), ExternallyDestructed, FalseContext);
5166 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
5167 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
5168 } else if (TrueContext.TerminatorExpr) {
5169 Block = TrueBlock;
5170 InsertTempDtorDecisionBlock(TrueContext);
5171 } else {
5172 InsertTempDtorDecisionBlock(FalseContext);
5174 return Block;
5177 CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
5178 AddStmtChoice asc) {
5179 if (asc.alwaysAdd(*this, D)) {
5180 autoCreateBlock();
5181 appendStmt(Block, D);
5184 // Iterate over all used expression in clauses.
5185 CFGBlock *B = Block;
5187 // Reverse the elements to process them in natural order. Iterators are not
5188 // bidirectional, so we need to create temp vector.
5189 SmallVector<Stmt *, 8> Used(
5190 OMPExecutableDirective::used_clauses_children(D->clauses()));
5191 for (Stmt *S : llvm::reverse(Used)) {
5192 assert(S && "Expected non-null used-in-clause child.");
5193 if (CFGBlock *R = Visit(S))
5194 B = R;
5196 // Visit associated structured block if any.
5197 if (!D->isStandaloneDirective()) {
5198 Stmt *S = D->getRawStmt();
5199 if (!isa<CompoundStmt>(S))
5200 addLocalScopeAndDtors(S);
5201 if (CFGBlock *R = addStmt(S))
5202 B = R;
5205 return B;
5208 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
5209 /// no successors or predecessors. If this is the first block created in the
5210 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
5211 CFGBlock *CFG::createBlock() {
5212 bool first_block = begin() == end();
5214 // Create the block.
5215 CFGBlock *Mem = new (getAllocator()) CFGBlock(NumBlockIDs++, BlkBVC, this);
5216 Blocks.push_back(Mem, BlkBVC);
5218 // If this is the first block, set it as the Entry and Exit.
5219 if (first_block)
5220 Entry = Exit = &back();
5222 // Return the block.
5223 return &back();
5226 /// buildCFG - Constructs a CFG from an AST.
5227 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
5228 ASTContext *C, const BuildOptions &BO) {
5229 CFGBuilder Builder(C, BO);
5230 return Builder.buildCFG(D, Statement);
5233 bool CFG::isLinear() const {
5234 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
5235 // in between, then we have no room for control flow.
5236 if (size() <= 3)
5237 return true;
5239 // Traverse the CFG until we find a branch.
5240 // TODO: While this should still be very fast,
5241 // maybe we should cache the answer.
5242 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
5243 const CFGBlock *B = Entry;
5244 while (B != Exit) {
5245 auto IteratorAndFlag = Visited.insert(B);
5246 if (!IteratorAndFlag.second) {
5247 // We looped back to a block that we've already visited. Not linear.
5248 return false;
5251 // Iterate over reachable successors.
5252 const CFGBlock *FirstReachableB = nullptr;
5253 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
5254 if (!AB.isReachable())
5255 continue;
5257 if (FirstReachableB == nullptr) {
5258 FirstReachableB = &*AB;
5259 } else {
5260 // We've encountered a branch. It's not a linear CFG.
5261 return false;
5265 if (!FirstReachableB) {
5266 // We reached a dead end. EXIT is unreachable. This is linear enough.
5267 return true;
5270 // There's only one way to move forward. Proceed.
5271 B = FirstReachableB;
5274 // We reached EXIT and found no branches.
5275 return true;
5278 const CXXDestructorDecl *
5279 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
5280 switch (getKind()) {
5281 case CFGElement::Initializer:
5282 case CFGElement::NewAllocator:
5283 case CFGElement::LoopExit:
5284 case CFGElement::LifetimeEnds:
5285 case CFGElement::Statement:
5286 case CFGElement::Constructor:
5287 case CFGElement::CXXRecordTypedCall:
5288 case CFGElement::ScopeBegin:
5289 case CFGElement::ScopeEnd:
5290 llvm_unreachable("getDestructorDecl should only be used with "
5291 "ImplicitDtors");
5292 case CFGElement::AutomaticObjectDtor: {
5293 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
5294 QualType ty = var->getType();
5296 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
5298 // Lifetime-extending constructs are handled here. This works for a single
5299 // temporary in an initializer expression.
5300 if (ty->isReferenceType()) {
5301 if (const Expr *Init = var->getInit()) {
5302 ty = getReferenceInitTemporaryType(Init);
5306 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5307 ty = arrayType->getElementType();
5310 // The situation when the type of the lifetime-extending reference
5311 // does not correspond to the type of the object is supposed
5312 // to be handled by now. In particular, 'ty' is now the unwrapped
5313 // record type.
5314 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5315 assert(classDecl);
5316 return classDecl->getDestructor();
5318 case CFGElement::DeleteDtor: {
5319 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
5320 QualType DTy = DE->getDestroyedType();
5321 DTy = DTy.getNonReferenceType();
5322 const CXXRecordDecl *classDecl =
5323 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
5324 return classDecl->getDestructor();
5326 case CFGElement::TemporaryDtor: {
5327 const CXXBindTemporaryExpr *bindExpr =
5328 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5329 const CXXTemporary *temp = bindExpr->getTemporary();
5330 return temp->getDestructor();
5332 case CFGElement::MemberDtor: {
5333 const FieldDecl *field = castAs<CFGMemberDtor>().getFieldDecl();
5334 QualType ty = field->getType();
5336 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
5337 ty = arrayType->getElementType();
5340 const CXXRecordDecl *classDecl = ty->getAsCXXRecordDecl();
5341 assert(classDecl);
5342 return classDecl->getDestructor();
5344 case CFGElement::BaseDtor:
5345 // Not yet supported.
5346 return nullptr;
5348 llvm_unreachable("getKind() returned bogus value");
5351 //===----------------------------------------------------------------------===//
5352 // CFGBlock operations.
5353 //===----------------------------------------------------------------------===//
5355 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
5356 : ReachableBlock(IsReachable ? B : nullptr),
5357 UnreachableBlock(!IsReachable ? B : nullptr,
5358 B && IsReachable ? AB_Normal : AB_Unreachable) {}
5360 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
5361 : ReachableBlock(B),
5362 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
5363 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
5365 void CFGBlock::addSuccessor(AdjacentBlock Succ,
5366 BumpVectorContext &C) {
5367 if (CFGBlock *B = Succ.getReachableBlock())
5368 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
5370 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
5371 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
5373 Succs.push_back(Succ, C);
5376 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
5377 const CFGBlock *From, const CFGBlock *To) {
5378 if (F.IgnoreNullPredecessors && !From)
5379 return true;
5381 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
5382 // If the 'To' has no label or is labeled but the label isn't a
5383 // CaseStmt then filter this edge.
5384 if (const SwitchStmt *S =
5385 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
5386 if (S->isAllEnumCasesCovered()) {
5387 const Stmt *L = To->getLabel();
5388 if (!L || !isa<CaseStmt>(L))
5389 return true;
5394 return false;
5397 //===----------------------------------------------------------------------===//
5398 // CFG pretty printing
5399 //===----------------------------------------------------------------------===//
5401 namespace {
5403 class StmtPrinterHelper : public PrinterHelper {
5404 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
5405 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
5407 StmtMapTy StmtMap;
5408 DeclMapTy DeclMap;
5409 signed currentBlock = 0;
5410 unsigned currStmt = 0;
5411 const LangOptions &LangOpts;
5413 public:
5414 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
5415 : LangOpts(LO) {
5416 if (!cfg)
5417 return;
5418 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
5419 unsigned j = 1;
5420 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
5421 BI != BEnd; ++BI, ++j ) {
5422 if (std::optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
5423 const Stmt *stmt= SE->getStmt();
5424 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
5425 StmtMap[stmt] = P;
5427 switch (stmt->getStmtClass()) {
5428 case Stmt::DeclStmtClass:
5429 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
5430 break;
5431 case Stmt::IfStmtClass: {
5432 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
5433 if (var)
5434 DeclMap[var] = P;
5435 break;
5437 case Stmt::ForStmtClass: {
5438 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
5439 if (var)
5440 DeclMap[var] = P;
5441 break;
5443 case Stmt::WhileStmtClass: {
5444 const VarDecl *var =
5445 cast<WhileStmt>(stmt)->getConditionVariable();
5446 if (var)
5447 DeclMap[var] = P;
5448 break;
5450 case Stmt::SwitchStmtClass: {
5451 const VarDecl *var =
5452 cast<SwitchStmt>(stmt)->getConditionVariable();
5453 if (var)
5454 DeclMap[var] = P;
5455 break;
5457 case Stmt::CXXCatchStmtClass: {
5458 const VarDecl *var =
5459 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5460 if (var)
5461 DeclMap[var] = P;
5462 break;
5464 default:
5465 break;
5472 ~StmtPrinterHelper() override = default;
5474 const LangOptions &getLangOpts() const { return LangOpts; }
5475 void setBlockID(signed i) { currentBlock = i; }
5476 void setStmtID(unsigned i) { currStmt = i; }
5478 bool handledStmt(Stmt *S, raw_ostream &OS) override {
5479 StmtMapTy::iterator I = StmtMap.find(S);
5481 if (I == StmtMap.end())
5482 return false;
5484 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5485 && I->second.second == currStmt) {
5486 return false;
5489 OS << "[B" << I->second.first << "." << I->second.second << "]";
5490 return true;
5493 bool handleDecl(const Decl *D, raw_ostream &OS) {
5494 DeclMapTy::iterator I = DeclMap.find(D);
5496 if (I == DeclMap.end())
5497 return false;
5499 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
5500 && I->second.second == currStmt) {
5501 return false;
5504 OS << "[B" << I->second.first << "." << I->second.second << "]";
5505 return true;
5509 class CFGBlockTerminatorPrint
5510 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
5511 raw_ostream &OS;
5512 StmtPrinterHelper* Helper;
5513 PrintingPolicy Policy;
5515 public:
5516 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
5517 const PrintingPolicy &Policy)
5518 : OS(os), Helper(helper), Policy(Policy) {
5519 this->Policy.IncludeNewlines = false;
5522 void VisitIfStmt(IfStmt *I) {
5523 OS << "if ";
5524 if (Stmt *C = I->getCond())
5525 C->printPretty(OS, Helper, Policy);
5528 // Default case.
5529 void VisitStmt(Stmt *Terminator) {
5530 Terminator->printPretty(OS, Helper, Policy);
5533 void VisitDeclStmt(DeclStmt *DS) {
5534 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5535 OS << "static init " << VD->getName();
5538 void VisitForStmt(ForStmt *F) {
5539 OS << "for (" ;
5540 if (F->getInit())
5541 OS << "...";
5542 OS << "; ";
5543 if (Stmt *C = F->getCond())
5544 C->printPretty(OS, Helper, Policy);
5545 OS << "; ";
5546 if (F->getInc())
5547 OS << "...";
5548 OS << ")";
5551 void VisitWhileStmt(WhileStmt *W) {
5552 OS << "while " ;
5553 if (Stmt *C = W->getCond())
5554 C->printPretty(OS, Helper, Policy);
5557 void VisitDoStmt(DoStmt *D) {
5558 OS << "do ... while ";
5559 if (Stmt *C = D->getCond())
5560 C->printPretty(OS, Helper, Policy);
5563 void VisitSwitchStmt(SwitchStmt *Terminator) {
5564 OS << "switch ";
5565 Terminator->getCond()->printPretty(OS, Helper, Policy);
5568 void VisitCXXTryStmt(CXXTryStmt *) { OS << "try ..."; }
5570 void VisitObjCAtTryStmt(ObjCAtTryStmt *) { OS << "@try ..."; }
5572 void VisitSEHTryStmt(SEHTryStmt *CS) { OS << "__try ..."; }
5574 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
5575 if (Stmt *Cond = C->getCond())
5576 Cond->printPretty(OS, Helper, Policy);
5577 OS << " ? ... : ...";
5580 void VisitChooseExpr(ChooseExpr *C) {
5581 OS << "__builtin_choose_expr( ";
5582 if (Stmt *Cond = C->getCond())
5583 Cond->printPretty(OS, Helper, Policy);
5584 OS << " )";
5587 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
5588 OS << "goto *";
5589 if (Stmt *T = I->getTarget())
5590 T->printPretty(OS, Helper, Policy);
5593 void VisitBinaryOperator(BinaryOperator* B) {
5594 if (!B->isLogicalOp()) {
5595 VisitExpr(B);
5596 return;
5599 if (B->getLHS())
5600 B->getLHS()->printPretty(OS, Helper, Policy);
5602 switch (B->getOpcode()) {
5603 case BO_LOr:
5604 OS << " || ...";
5605 return;
5606 case BO_LAnd:
5607 OS << " && ...";
5608 return;
5609 default:
5610 llvm_unreachable("Invalid logical operator.");
5614 void VisitExpr(Expr *E) {
5615 E->printPretty(OS, Helper, Policy);
5618 public:
5619 void print(CFGTerminator T) {
5620 switch (T.getKind()) {
5621 case CFGTerminator::StmtBranch:
5622 Visit(T.getStmt());
5623 break;
5624 case CFGTerminator::TemporaryDtorsBranch:
5625 OS << "(Temp Dtor) ";
5626 Visit(T.getStmt());
5627 break;
5628 case CFGTerminator::VirtualBaseBranch:
5629 OS << "(See if most derived ctor has already initialized vbases)";
5630 break;
5635 } // namespace
5637 static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5638 const CXXCtorInitializer *I) {
5639 if (I->isBaseInitializer())
5640 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5641 else if (I->isDelegatingInitializer())
5642 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5643 else
5644 OS << I->getAnyMember()->getName();
5645 OS << "(";
5646 if (Expr *IE = I->getInit())
5647 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5648 OS << ")";
5650 if (I->isBaseInitializer())
5651 OS << " (Base initializer)";
5652 else if (I->isDelegatingInitializer())
5653 OS << " (Delegating initializer)";
5654 else
5655 OS << " (Member initializer)";
5658 static void print_construction_context(raw_ostream &OS,
5659 StmtPrinterHelper &Helper,
5660 const ConstructionContext *CC) {
5661 SmallVector<const Stmt *, 3> Stmts;
5662 switch (CC->getKind()) {
5663 case ConstructionContext::SimpleConstructorInitializerKind: {
5664 OS << ", ";
5665 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5666 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5667 return;
5669 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5670 OS << ", ";
5671 const auto *CICC =
5672 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5673 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
5674 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
5675 break;
5677 case ConstructionContext::SimpleVariableKind: {
5678 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
5679 Stmts.push_back(SDSCC->getDeclStmt());
5680 break;
5682 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5683 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
5684 Stmts.push_back(CDSCC->getDeclStmt());
5685 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
5686 break;
5688 case ConstructionContext::NewAllocatedObjectKind: {
5689 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
5690 Stmts.push_back(NECC->getCXXNewExpr());
5691 break;
5693 case ConstructionContext::SimpleReturnedValueKind: {
5694 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
5695 Stmts.push_back(RSCC->getReturnStmt());
5696 break;
5698 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5699 const auto *RSCC =
5700 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
5701 Stmts.push_back(RSCC->getReturnStmt());
5702 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
5703 break;
5705 case ConstructionContext::SimpleTemporaryObjectKind: {
5706 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5707 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5708 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5709 break;
5711 case ConstructionContext::ElidedTemporaryObjectKind: {
5712 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5713 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5714 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5715 Stmts.push_back(TOCC->getConstructorAfterElision());
5716 break;
5718 case ConstructionContext::LambdaCaptureKind: {
5719 const auto *LCC = cast<LambdaCaptureConstructionContext>(CC);
5720 Helper.handledStmt(const_cast<LambdaExpr *>(LCC->getLambdaExpr()), OS);
5721 OS << "+" << LCC->getIndex();
5722 return;
5724 case ConstructionContext::ArgumentKind: {
5725 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5726 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5727 OS << ", ";
5728 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5730 OS << ", ";
5731 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5732 OS << "+" << ACC->getIndex();
5733 return;
5736 for (auto I: Stmts)
5737 if (I) {
5738 OS << ", ";
5739 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5743 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5744 const CFGElement &E);
5746 void CFGElement::dumpToStream(llvm::raw_ostream &OS) const {
5747 LangOptions LangOpts;
5748 StmtPrinterHelper Helper(nullptr, LangOpts);
5749 print_elem(OS, Helper, *this);
5752 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
5753 const CFGElement &E) {
5754 switch (E.getKind()) {
5755 case CFGElement::Kind::Statement:
5756 case CFGElement::Kind::CXXRecordTypedCall:
5757 case CFGElement::Kind::Constructor: {
5758 CFGStmt CS = E.castAs<CFGStmt>();
5759 const Stmt *S = CS.getStmt();
5760 assert(S != nullptr && "Expecting non-null Stmt");
5762 // special printing for statement-expressions.
5763 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5764 const CompoundStmt *Sub = SE->getSubStmt();
5766 auto Children = Sub->children();
5767 if (Children.begin() != Children.end()) {
5768 OS << "({ ... ; ";
5769 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5770 OS << " })\n";
5771 return;
5774 // special printing for comma expressions.
5775 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5776 if (B->getOpcode() == BO_Comma) {
5777 OS << "... , ";
5778 Helper.handledStmt(B->getRHS(),OS);
5779 OS << '\n';
5780 return;
5783 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5785 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5786 if (isa<CXXOperatorCallExpr>(S))
5787 OS << " (OperatorCall)";
5788 OS << " (CXXRecordTypedCall";
5789 print_construction_context(OS, Helper, VTC->getConstructionContext());
5790 OS << ")";
5791 } else if (isa<CXXOperatorCallExpr>(S)) {
5792 OS << " (OperatorCall)";
5793 } else if (isa<CXXBindTemporaryExpr>(S)) {
5794 OS << " (BindTemporary)";
5795 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
5796 OS << " (CXXConstructExpr";
5797 if (std::optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
5798 print_construction_context(OS, Helper, CE->getConstructionContext());
5800 OS << ", " << CCE->getType() << ")";
5801 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
5802 OS << " (" << CE->getStmtClassName() << ", " << CE->getCastKindName()
5803 << ", " << CE->getType() << ")";
5806 // Expressions need a newline.
5807 if (isa<Expr>(S))
5808 OS << '\n';
5810 break;
5813 case CFGElement::Kind::Initializer:
5814 print_initializer(OS, Helper, E.castAs<CFGInitializer>().getInitializer());
5815 OS << '\n';
5816 break;
5818 case CFGElement::Kind::AutomaticObjectDtor: {
5819 CFGAutomaticObjDtor DE = E.castAs<CFGAutomaticObjDtor>();
5820 const VarDecl *VD = DE.getVarDecl();
5821 Helper.handleDecl(VD, OS);
5823 QualType T = VD->getType();
5824 if (T->isReferenceType())
5825 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5827 OS << ".~";
5828 T.getUnqualifiedType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5829 OS << "() (Implicit destructor)\n";
5830 break;
5833 case CFGElement::Kind::LifetimeEnds:
5834 Helper.handleDecl(E.castAs<CFGLifetimeEnds>().getVarDecl(), OS);
5835 OS << " (Lifetime ends)\n";
5836 break;
5838 case CFGElement::Kind::LoopExit:
5839 OS << E.castAs<CFGLoopExit>().getLoopStmt()->getStmtClassName() << " (LoopExit)\n";
5840 break;
5842 case CFGElement::Kind::ScopeBegin:
5843 OS << "CFGScopeBegin(";
5844 if (const VarDecl *VD = E.castAs<CFGScopeBegin>().getVarDecl())
5845 OS << VD->getQualifiedNameAsString();
5846 OS << ")\n";
5847 break;
5849 case CFGElement::Kind::ScopeEnd:
5850 OS << "CFGScopeEnd(";
5851 if (const VarDecl *VD = E.castAs<CFGScopeEnd>().getVarDecl())
5852 OS << VD->getQualifiedNameAsString();
5853 OS << ")\n";
5854 break;
5856 case CFGElement::Kind::NewAllocator:
5857 OS << "CFGNewAllocator(";
5858 if (const CXXNewExpr *AllocExpr = E.castAs<CFGNewAllocator>().getAllocatorExpr())
5859 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5860 OS << ")\n";
5861 break;
5863 case CFGElement::Kind::DeleteDtor: {
5864 CFGDeleteDtor DE = E.castAs<CFGDeleteDtor>();
5865 const CXXRecordDecl *RD = DE.getCXXRecordDecl();
5866 if (!RD)
5867 return;
5868 CXXDeleteExpr *DelExpr =
5869 const_cast<CXXDeleteExpr*>(DE.getDeleteExpr());
5870 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
5871 OS << "->~" << RD->getName().str() << "()";
5872 OS << " (Implicit destructor)\n";
5873 break;
5876 case CFGElement::Kind::BaseDtor: {
5877 const CXXBaseSpecifier *BS = E.castAs<CFGBaseDtor>().getBaseSpecifier();
5878 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
5879 OS << " (Base object destructor)\n";
5880 break;
5883 case CFGElement::Kind::MemberDtor: {
5884 const FieldDecl *FD = E.castAs<CFGMemberDtor>().getFieldDecl();
5885 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
5886 OS << "this->" << FD->getName();
5887 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
5888 OS << " (Member object destructor)\n";
5889 break;
5892 case CFGElement::Kind::TemporaryDtor: {
5893 const CXXBindTemporaryExpr *BT =
5894 E.castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
5895 OS << "~";
5896 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5897 OS << "() (Temporary object destructor)\n";
5898 break;
5903 static void print_block(raw_ostream &OS, const CFG* cfg,
5904 const CFGBlock &B,
5905 StmtPrinterHelper &Helper, bool print_edges,
5906 bool ShowColors) {
5907 Helper.setBlockID(B.getBlockID());
5909 // Print the header.
5910 if (ShowColors)
5911 OS.changeColor(raw_ostream::YELLOW, true);
5913 OS << "\n [B" << B.getBlockID();
5915 if (&B == &cfg->getEntry())
5916 OS << " (ENTRY)]\n";
5917 else if (&B == &cfg->getExit())
5918 OS << " (EXIT)]\n";
5919 else if (&B == cfg->getIndirectGotoBlock())
5920 OS << " (INDIRECT GOTO DISPATCH)]\n";
5921 else if (B.hasNoReturnElement())
5922 OS << " (NORETURN)]\n";
5923 else
5924 OS << "]\n";
5926 if (ShowColors)
5927 OS.resetColor();
5929 // Print the label of this block.
5930 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
5931 if (print_edges)
5932 OS << " ";
5934 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
5935 OS << L->getName();
5936 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
5937 OS << "case ";
5938 if (const Expr *LHS = C->getLHS())
5939 LHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5940 if (const Expr *RHS = C->getRHS()) {
5941 OS << " ... ";
5942 RHS->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5944 } else if (isa<DefaultStmt>(Label))
5945 OS << "default";
5946 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
5947 OS << "catch (";
5948 if (const VarDecl *ED = CS->getExceptionDecl())
5949 ED->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
5950 else
5951 OS << "...";
5952 OS << ")";
5953 } else if (ObjCAtCatchStmt *CS = dyn_cast<ObjCAtCatchStmt>(Label)) {
5954 OS << "@catch (";
5955 if (const VarDecl *PD = CS->getCatchParamDecl())
5956 PD->print(OS, PrintingPolicy(Helper.getLangOpts()), 0);
5957 else
5958 OS << "...";
5959 OS << ")";
5960 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5961 OS << "__except (";
5962 ES->getFilterExpr()->printPretty(OS, &Helper,
5963 PrintingPolicy(Helper.getLangOpts()), 0);
5964 OS << ")";
5965 } else
5966 llvm_unreachable("Invalid label statement in CFGBlock.");
5968 OS << ":\n";
5971 // Iterate through the statements in the block and print them.
5972 unsigned j = 1;
5974 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5975 I != E ; ++I, ++j ) {
5976 // Print the statement # in the basic block and the statement itself.
5977 if (print_edges)
5978 OS << " ";
5980 OS << llvm::format("%3d", j) << ": ";
5982 Helper.setStmtID(j);
5984 print_elem(OS, Helper, *I);
5987 // Print the terminator of this block.
5988 if (B.getTerminator().isValid()) {
5989 if (ShowColors)
5990 OS.changeColor(raw_ostream::GREEN);
5992 OS << " T: ";
5994 Helper.setBlockID(-1);
5996 PrintingPolicy PP(Helper.getLangOpts());
5997 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
5998 TPrinter.print(B.getTerminator());
5999 OS << '\n';
6001 if (ShowColors)
6002 OS.resetColor();
6005 if (print_edges) {
6006 // Print the predecessors of this block.
6007 if (!B.pred_empty()) {
6008 const raw_ostream::Colors Color = raw_ostream::BLUE;
6009 if (ShowColors)
6010 OS.changeColor(Color);
6011 OS << " Preds " ;
6012 if (ShowColors)
6013 OS.resetColor();
6014 OS << '(' << B.pred_size() << "):";
6015 unsigned i = 0;
6017 if (ShowColors)
6018 OS.changeColor(Color);
6020 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
6021 I != E; ++I, ++i) {
6022 if (i % 10 == 8)
6023 OS << "\n ";
6025 CFGBlock *B = *I;
6026 bool Reachable = true;
6027 if (!B) {
6028 Reachable = false;
6029 B = I->getPossiblyUnreachableBlock();
6032 OS << " B" << B->getBlockID();
6033 if (!Reachable)
6034 OS << "(Unreachable)";
6037 if (ShowColors)
6038 OS.resetColor();
6040 OS << '\n';
6043 // Print the successors of this block.
6044 if (!B.succ_empty()) {
6045 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
6046 if (ShowColors)
6047 OS.changeColor(Color);
6048 OS << " Succs ";
6049 if (ShowColors)
6050 OS.resetColor();
6051 OS << '(' << B.succ_size() << "):";
6052 unsigned i = 0;
6054 if (ShowColors)
6055 OS.changeColor(Color);
6057 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
6058 I != E; ++I, ++i) {
6059 if (i % 10 == 8)
6060 OS << "\n ";
6062 CFGBlock *B = *I;
6064 bool Reachable = true;
6065 if (!B) {
6066 Reachable = false;
6067 B = I->getPossiblyUnreachableBlock();
6070 if (B) {
6071 OS << " B" << B->getBlockID();
6072 if (!Reachable)
6073 OS << "(Unreachable)";
6075 else {
6076 OS << " NULL";
6080 if (ShowColors)
6081 OS.resetColor();
6082 OS << '\n';
6087 /// dump - A simple pretty printer of a CFG that outputs to stderr.
6088 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
6089 print(llvm::errs(), LO, ShowColors);
6092 /// print - A simple pretty printer of a CFG that outputs to an ostream.
6093 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
6094 StmtPrinterHelper Helper(this, LO);
6096 // Print the entry block.
6097 print_block(OS, this, getEntry(), Helper, true, ShowColors);
6099 // Iterate through the CFGBlocks and print them one by one.
6100 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
6101 // Skip the entry block, because we already printed it.
6102 if (&(**I) == &getEntry() || &(**I) == &getExit())
6103 continue;
6105 print_block(OS, this, **I, Helper, true, ShowColors);
6108 // Print the exit block.
6109 print_block(OS, this, getExit(), Helper, true, ShowColors);
6110 OS << '\n';
6111 OS.flush();
6114 size_t CFGBlock::getIndexInCFG() const {
6115 return llvm::find(*getParent(), this) - getParent()->begin();
6118 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
6119 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
6120 bool ShowColors) const {
6121 print(llvm::errs(), cfg, LO, ShowColors);
6124 LLVM_DUMP_METHOD void CFGBlock::dump() const {
6125 dump(getParent(), LangOptions(), false);
6128 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
6129 /// Generally this will only be called from CFG::print.
6130 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
6131 const LangOptions &LO, bool ShowColors) const {
6132 StmtPrinterHelper Helper(cfg, LO);
6133 print_block(OS, cfg, *this, Helper, true, ShowColors);
6134 OS << '\n';
6137 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
6138 void CFGBlock::printTerminator(raw_ostream &OS,
6139 const LangOptions &LO) const {
6140 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
6141 TPrinter.print(getTerminator());
6144 /// printTerminatorJson - Pretty-prints the terminator in JSON format.
6145 void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
6146 bool AddQuotes) const {
6147 std::string Buf;
6148 llvm::raw_string_ostream TempOut(Buf);
6150 printTerminator(TempOut, LO);
6152 Out << JsonFormat(TempOut.str(), AddQuotes);
6155 // Returns true if by simply looking at the block, we can be sure that it
6156 // results in a sink during analysis. This is useful to know when the analysis
6157 // was interrupted, and we try to figure out if it would sink eventually.
6158 // There may be many more reasons why a sink would appear during analysis
6159 // (eg. checkers may generate sinks arbitrarily), but here we only consider
6160 // sinks that would be obvious by looking at the CFG.
6161 static bool isImmediateSinkBlock(const CFGBlock *Blk) {
6162 if (Blk->hasNoReturnElement())
6163 return true;
6165 // FIXME: Throw-expressions are currently generating sinks during analysis:
6166 // they're not supported yet, and also often used for actually terminating
6167 // the program. So we should treat them as sinks in this analysis as well,
6168 // at least for now, but once we have better support for exceptions,
6169 // we'd need to carefully handle the case when the throw is being
6170 // immediately caught.
6171 if (llvm::any_of(*Blk, [](const CFGElement &Elm) {
6172 if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
6173 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
6174 return true;
6175 return false;
6177 return true;
6179 return false;
6182 bool CFGBlock::isInevitablySinking() const {
6183 const CFG &Cfg = *getParent();
6185 const CFGBlock *StartBlk = this;
6186 if (isImmediateSinkBlock(StartBlk))
6187 return true;
6189 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
6190 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
6192 DFSWorkList.push_back(StartBlk);
6193 while (!DFSWorkList.empty()) {
6194 const CFGBlock *Blk = DFSWorkList.back();
6195 DFSWorkList.pop_back();
6196 Visited.insert(Blk);
6198 // If at least one path reaches the CFG exit, it means that control is
6199 // returned to the caller. For now, say that we are not sure what
6200 // happens next. If necessary, this can be improved to analyze
6201 // the parent StackFrameContext's call site in a similar manner.
6202 if (Blk == &Cfg.getExit())
6203 return false;
6205 for (const auto &Succ : Blk->succs()) {
6206 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
6207 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
6208 // If the block has reachable child blocks that aren't no-return,
6209 // add them to the worklist.
6210 DFSWorkList.push_back(SuccBlk);
6216 // Nothing reached the exit. It can only mean one thing: there's no return.
6217 return true;
6220 const Expr *CFGBlock::getLastCondition() const {
6221 // If the terminator is a temporary dtor or a virtual base, etc, we can't
6222 // retrieve a meaningful condition, bail out.
6223 if (Terminator.getKind() != CFGTerminator::StmtBranch)
6224 return nullptr;
6226 // Also, if this method was called on a block that doesn't have 2 successors,
6227 // this block doesn't have retrievable condition.
6228 if (succ_size() < 2)
6229 return nullptr;
6231 // FIXME: Is there a better condition expression we can return in this case?
6232 if (size() == 0)
6233 return nullptr;
6235 auto StmtElem = rbegin()->getAs<CFGStmt>();
6236 if (!StmtElem)
6237 return nullptr;
6239 const Stmt *Cond = StmtElem->getStmt();
6240 if (isa<ObjCForCollectionStmt>(Cond) || isa<DeclStmt>(Cond))
6241 return nullptr;
6243 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
6244 // the cast<>.
6245 return cast<Expr>(Cond)->IgnoreParens();
6248 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
6249 Stmt *Terminator = getTerminatorStmt();
6250 if (!Terminator)
6251 return nullptr;
6253 Expr *E = nullptr;
6255 switch (Terminator->getStmtClass()) {
6256 default:
6257 break;
6259 case Stmt::CXXForRangeStmtClass:
6260 E = cast<CXXForRangeStmt>(Terminator)->getCond();
6261 break;
6263 case Stmt::ForStmtClass:
6264 E = cast<ForStmt>(Terminator)->getCond();
6265 break;
6267 case Stmt::WhileStmtClass:
6268 E = cast<WhileStmt>(Terminator)->getCond();
6269 break;
6271 case Stmt::DoStmtClass:
6272 E = cast<DoStmt>(Terminator)->getCond();
6273 break;
6275 case Stmt::IfStmtClass:
6276 E = cast<IfStmt>(Terminator)->getCond();
6277 break;
6279 case Stmt::ChooseExprClass:
6280 E = cast<ChooseExpr>(Terminator)->getCond();
6281 break;
6283 case Stmt::IndirectGotoStmtClass:
6284 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
6285 break;
6287 case Stmt::SwitchStmtClass:
6288 E = cast<SwitchStmt>(Terminator)->getCond();
6289 break;
6291 case Stmt::BinaryConditionalOperatorClass:
6292 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
6293 break;
6295 case Stmt::ConditionalOperatorClass:
6296 E = cast<ConditionalOperator>(Terminator)->getCond();
6297 break;
6299 case Stmt::BinaryOperatorClass: // '&&' and '||'
6300 E = cast<BinaryOperator>(Terminator)->getLHS();
6301 break;
6303 case Stmt::ObjCForCollectionStmtClass:
6304 return Terminator;
6307 if (!StripParens)
6308 return E;
6310 return E ? E->IgnoreParens() : nullptr;
6313 //===----------------------------------------------------------------------===//
6314 // CFG Graphviz Visualization
6315 //===----------------------------------------------------------------------===//
6317 static StmtPrinterHelper *GraphHelper;
6319 void CFG::viewCFG(const LangOptions &LO) const {
6320 StmtPrinterHelper H(this, LO);
6321 GraphHelper = &H;
6322 llvm::ViewGraph(this,"CFG");
6323 GraphHelper = nullptr;
6326 namespace llvm {
6328 template<>
6329 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
6330 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6332 static std::string getNodeLabel(const CFGBlock *Node, const CFG *Graph) {
6333 std::string OutSStr;
6334 llvm::raw_string_ostream Out(OutSStr);
6335 print_block(Out,Graph, *Node, *GraphHelper, false, false);
6336 std::string& OutStr = Out.str();
6338 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6340 // Process string output to make it nicer...
6341 for (unsigned i = 0; i != OutStr.length(); ++i)
6342 if (OutStr[i] == '\n') { // Left justify
6343 OutStr[i] = '\\';
6344 OutStr.insert(OutStr.begin()+i+1, 'l');
6347 return OutStr;
6351 } // namespace llvm