1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Analysis/CFG.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/GraphWriter.h"
29 #include "llvm/Support/SaveAndRestore.h"
31 using namespace clang;
35 static SourceLocation GetEndLoc(Decl *D) {
36 if (VarDecl *VD = dyn_cast<VarDecl>(D))
37 if (Expr *Ex = VD->getInit())
38 return Ex->getSourceRange().getEnd();
39 return D->getLocation();
42 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
43 /// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
44 const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
45 E = E->IgnoreParens();
46 if (isa<IntegerLiteral>(E))
48 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
49 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
53 /// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
54 /// an integer literal or an enum constant.
56 /// If this fails, at least one of the returned DeclRefExpr or Expr will be
58 static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
59 tryNormalizeBinaryOperator(const BinaryOperator *B) {
60 BinaryOperatorKind Op = B->getOpcode();
62 const Expr *MaybeDecl = B->getLHS();
63 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
64 // Expr looked like `0 == Foo` instead of `Foo == 0`
65 if (Constant == nullptr) {
76 MaybeDecl = B->getRHS();
77 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
80 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
81 return std::make_tuple(D, Op, Constant);
84 /// For an expression `x == Foo && x == Bar`, this determines whether the
85 /// `Foo` and `Bar` are either of the same enumeration type, or both integer
88 /// It's an error to pass this arguments that are not either IntegerLiterals
89 /// or DeclRefExprs (that have decls of type EnumConstantDecl)
90 static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
91 // User intent isn't clear if they're mixing int literals with enum
93 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
96 // Integer literal comparisons, regardless of literal type, are acceptable.
97 if (isa<IntegerLiteral>(E1))
100 // IntegerLiterals are handled above and only EnumConstantDecls are expected
102 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
103 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
104 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
106 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
107 const DeclContext *DC1 = Decl1->getDeclContext();
108 const DeclContext *DC2 = Decl2->getDeclContext();
110 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
116 /// The CFG builder uses a recursive algorithm to build the CFG. When
117 /// we process an expression, sometimes we know that we must add the
118 /// subexpressions as block-level expressions. For example:
122 /// When processing the '||' expression, we know that exp1 and exp2
123 /// need to be added as block-level expressions, even though they
124 /// might not normally need to be. AddStmtChoice records this
125 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
126 /// the builder has an option not to add a subexpression as a
127 /// block-level expression.
129 class AddStmtChoice {
131 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
133 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
135 bool alwaysAdd(CFGBuilder &builder,
136 const Stmt *stmt) const;
138 /// Return a copy of this object, except with the 'always-add' bit
139 /// set as specified.
140 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
141 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
148 /// LocalScope - Node in tree of local scopes created for C++ implicit
149 /// destructor calls generation. It contains list of automatic variables
150 /// declared in the scope and link to position in previous scope this scope
153 /// The process of creating local scopes is as follows:
154 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
155 /// - Before processing statements in scope (e.g. CompoundStmt) create
156 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
157 /// and set CFGBuilder::ScopePos to the end of new scope,
158 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
160 /// - For every normal (without jump) end of scope add to CFGBlock destructors
161 /// for objects in the current scope,
162 /// - For every jump add to CFGBlock destructors for objects
163 /// between CFGBuilder::ScopePos and local scope position saved for jump
164 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
165 /// jump target position will be on the path to root from CFGBuilder::ScopePos
166 /// (adding any variable that doesn't need constructor to be called to
167 /// LocalScope can break this assumption),
171 typedef BumpVector<VarDecl*> AutomaticVarsTy;
173 /// const_iterator - Iterates local scope backwards and jumps to previous
174 /// scope on reaching the beginning of currently iterated scope.
175 class const_iterator {
176 const LocalScope* Scope;
178 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
179 /// Invalid iterator (with null Scope) has VarIter equal to 0.
183 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
184 /// Incrementing invalid iterator is allowed and will result in invalid
187 : Scope(nullptr), VarIter(0) {}
189 /// Create valid iterator. In case when S.Prev is an invalid iterator and
190 /// I is equal to 0, this will create invalid iterator.
191 const_iterator(const LocalScope& S, unsigned I)
192 : Scope(&S), VarIter(I) {
193 // Iterator to "end" of scope is not allowed. Handle it by going up
194 // in scopes tree possibly up to invalid iterator in the root.
195 if (VarIter == 0 && Scope)
199 VarDecl *const* operator->() const {
200 assert (Scope && "Dereferencing invalid iterator is not allowed");
201 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
202 return &Scope->Vars[VarIter - 1];
204 VarDecl *operator*() const {
205 return *this->operator->();
208 const_iterator &operator++() {
212 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
218 const_iterator operator++(int) {
219 const_iterator P = *this;
224 bool operator==(const const_iterator &rhs) const {
225 return Scope == rhs.Scope && VarIter == rhs.VarIter;
227 bool operator!=(const const_iterator &rhs) const {
228 return !(*this == rhs);
231 explicit operator bool() const {
232 return *this != const_iterator();
235 int distance(const_iterator L);
238 friend class const_iterator;
241 BumpVectorContext ctx;
243 /// Automatic variables in order of declaration.
244 AutomaticVarsTy Vars;
245 /// Iterator to variable in previous scope that was declared just before
246 /// begin of this scope.
250 /// Constructs empty scope linked to previous scope in specified place.
251 LocalScope(BumpVectorContext ctx, const_iterator P)
252 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
254 /// Begin of scope in direction of CFG building (backwards).
255 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
257 void addVar(VarDecl *VD) {
258 Vars.push_back(VD, ctx);
262 /// distance - Calculates distance from this to L. L must be reachable from this
263 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
264 /// number of scopes between this and L.
265 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
267 const_iterator F = *this;
268 while (F.Scope != L.Scope) {
269 assert (F != const_iterator()
270 && "L iterator is not reachable from F iterator.");
274 D += F.VarIter - L.VarIter;
278 /// Structure for specifying position in CFG during its build process. It
279 /// consists of CFGBlock that specifies position in CFG and
280 /// LocalScope::const_iterator that specifies position in LocalScope graph.
281 struct BlockScopePosPair {
282 BlockScopePosPair() : block(nullptr) {}
283 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
284 : block(b), scopePosition(scopePos) {}
287 LocalScope::const_iterator scopePosition;
290 /// TryResult - a class representing a variant over the values
291 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
292 /// and is used by the CFGBuilder to decide if a branch condition
293 /// can be decided up front during CFG construction.
297 TryResult(bool b) : X(b ? 1 : 0) {}
298 TryResult() : X(-1) {}
300 bool isTrue() const { return X == 1; }
301 bool isFalse() const { return X == 0; }
302 bool isKnown() const { return X >= 0; }
309 TryResult bothKnownTrue(TryResult R1, TryResult R2) {
310 if (!R1.isKnown() || !R2.isKnown())
312 return TryResult(R1.isTrue() && R2.isTrue());
315 class reverse_children {
316 llvm::SmallVector<Stmt *, 12> childrenBuf;
317 ArrayRef<Stmt*> children;
319 reverse_children(Stmt *S);
321 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
322 iterator begin() const { return children.rbegin(); }
323 iterator end() const { return children.rend(); }
327 reverse_children::reverse_children(Stmt *S) {
328 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
329 children = CE->getRawSubExprs();
332 switch (S->getStmtClass()) {
333 // Note: Fill in this switch with more cases we want to optimize.
334 case Stmt::InitListExprClass: {
335 InitListExpr *IE = cast<InitListExpr>(S);
336 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
344 // Default case for all other statements.
345 for (Stmt *SubStmt : S->children())
346 childrenBuf.push_back(SubStmt);
348 // This needs to be done *after* childrenBuf has been populated.
349 children = childrenBuf;
352 /// CFGBuilder - This class implements CFG construction from an AST.
353 /// The builder is stateful: an instance of the builder should be used to only
354 /// construct a single CFG.
358 /// CFGBuilder builder;
359 /// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
361 /// CFG construction is done via a recursive walk of an AST. We actually parse
362 /// the AST in reverse order so that the successor of a basic block is
363 /// constructed prior to its predecessor. This allows us to nicely capture
364 /// implicit fall-throughs without extra basic blocks.
367 typedef BlockScopePosPair JumpTarget;
368 typedef BlockScopePosPair JumpSource;
371 std::unique_ptr<CFG> cfg;
375 JumpTarget ContinueJumpTarget;
376 JumpTarget BreakJumpTarget;
377 CFGBlock *SwitchTerminatedBlock;
378 CFGBlock *DefaultCaseBlock;
379 CFGBlock *TryTerminatedBlock;
381 // Current position in local scope.
382 LocalScope::const_iterator ScopePos;
384 // LabelMap records the mapping from Label expressions to their jump targets.
385 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
388 // A list of blocks that end with a "goto" that must be backpatched to their
389 // resolved targets upon completion of CFG construction.
390 typedef std::vector<JumpSource> BackpatchBlocksTy;
391 BackpatchBlocksTy BackpatchBlocks;
393 // A list of labels whose address has been taken (for indirect gotos).
394 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
395 LabelSetTy AddressTakenLabels;
398 const CFG::BuildOptions &BuildOpts;
400 // State to track for building switch statements.
401 bool switchExclusivelyCovered;
402 Expr::EvalResult *switchCond;
404 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
405 const Stmt *lastLookup;
407 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
408 // during construction of branches for chained logical operators.
409 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
410 CachedBoolEvalsTy CachedBoolEvals;
413 explicit CFGBuilder(ASTContext *astContext,
414 const CFG::BuildOptions &buildOpts)
415 : Context(astContext), cfg(new CFG()), // crew a new CFG
416 Block(nullptr), Succ(nullptr),
417 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
418 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
419 switchExclusivelyCovered(false), switchCond(nullptr),
420 cachedEntry(nullptr), lastLookup(nullptr) {}
422 // buildCFG - Used by external clients to construct the CFG.
423 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
425 bool alwaysAdd(const Stmt *stmt);
428 // Visitors to walk an AST and construct the CFG.
429 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
430 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
431 CFGBlock *VisitBreakStmt(BreakStmt *B);
432 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
433 CFGBlock *VisitCaseStmt(CaseStmt *C);
434 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
435 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
436 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
438 CFGBlock *VisitContinueStmt(ContinueStmt *C);
439 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
441 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
442 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
443 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
444 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
445 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
446 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
448 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
450 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
451 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
452 CFGBlock *VisitDeclStmt(DeclStmt *DS);
453 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
454 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
455 CFGBlock *VisitDoStmt(DoStmt *D);
456 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
457 CFGBlock *VisitForStmt(ForStmt *F);
458 CFGBlock *VisitGotoStmt(GotoStmt *G);
459 CFGBlock *VisitIfStmt(IfStmt *I);
460 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
461 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
462 CFGBlock *VisitLabelStmt(LabelStmt *L);
463 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
464 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
465 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
466 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
469 CFGBlock *FalseBlock);
470 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
471 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
472 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
473 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
474 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
475 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
476 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
477 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
478 CFGBlock *VisitReturnStmt(ReturnStmt *R);
479 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
480 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
481 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
483 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
484 CFGBlock *VisitWhileStmt(WhileStmt *W);
486 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
487 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
488 CFGBlock *VisitChildren(Stmt *S);
489 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
491 /// When creating the CFG for temporary destructors, we want to mirror the
492 /// branch structure of the corresponding constructor calls.
493 /// Thus, while visiting a statement for temporary destructors, we keep a
494 /// context to keep track of the following information:
495 /// - whether a subexpression is executed unconditionally
496 /// - if a subexpression is executed conditionally, the first
497 /// CXXBindTemporaryExpr we encounter in that subexpression (which
498 /// corresponds to the last temporary destructor we have to call for this
499 /// subexpression) and the CFG block at that point (which will become the
500 /// successor block when inserting the decision point).
502 /// That way, we can build the branch structure for temporary destructors as
504 /// 1. If a subexpression is executed unconditionally, we add the temporary
505 /// destructor calls to the current block.
506 /// 2. If a subexpression is executed conditionally, when we encounter a
507 /// CXXBindTemporaryExpr:
508 /// a) If it is the first temporary destructor call in the subexpression,
509 /// we remember the CXXBindTemporaryExpr and the current block in the
510 /// TempDtorContext; we start a new block, and insert the temporary
512 /// b) Otherwise, add the temporary destructor call to the current block.
513 /// 3. When we finished visiting a conditionally executed subexpression,
514 /// and we found at least one temporary constructor during the visitation
515 /// (2.a has executed), we insert a decision block that uses the
516 /// CXXBindTemporaryExpr as terminator, and branches to the current block
517 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
518 /// branches to the stored successor.
519 struct TempDtorContext {
521 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
522 TerminatorExpr(nullptr) {}
524 TempDtorContext(TryResult KnownExecuted)
525 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
526 TerminatorExpr(nullptr) {}
528 /// Returns whether we need to start a new branch for a temporary destructor
529 /// call. This is the case when the temporary destructor is
530 /// conditionally executed, and it is the first one we encounter while
531 /// visiting a subexpression - other temporary destructors at the same level
532 /// will be added to the same block and are executed under the same
534 bool needsTempDtorBranch() const {
535 return IsConditional && !TerminatorExpr;
538 /// Remember the successor S of a temporary destructor decision branch for
539 /// the corresponding CXXBindTemporaryExpr E.
540 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
545 const bool IsConditional;
546 const TryResult KnownExecuted;
548 CXXBindTemporaryExpr *TerminatorExpr;
551 // Visitors to walk an AST and generate destructors of temporaries in
553 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
554 TempDtorContext &Context);
555 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
556 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
557 TempDtorContext &Context);
558 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
559 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
560 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
561 AbstractConditionalOperator *E, bool BindToTemporary,
562 TempDtorContext &Context);
563 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
564 CFGBlock *FalseSucc = nullptr);
566 // NYS == Not Yet Supported
572 void autoCreateBlock() { if (!Block) Block = createBlock(); }
573 CFGBlock *createBlock(bool add_successor = true);
574 CFGBlock *createNoReturnBlock();
576 CFGBlock *addStmt(Stmt *S) {
577 return Visit(S, AddStmtChoice::AlwaysAdd);
579 CFGBlock *addInitializer(CXXCtorInitializer *I);
580 void addAutomaticObjDtors(LocalScope::const_iterator B,
581 LocalScope::const_iterator E, Stmt *S);
582 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
584 // Local scopes creation.
585 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
587 void addLocalScopeForStmt(Stmt *S);
588 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
589 LocalScope* Scope = nullptr);
590 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
592 void addLocalScopeAndDtors(Stmt *S);
594 // Interface to CFGBlock - adding CFGElements.
595 void appendStmt(CFGBlock *B, const Stmt *S) {
596 if (alwaysAdd(S) && cachedEntry)
597 cachedEntry->second = B;
599 // All block-level expressions should have already been IgnoreParens()ed.
600 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
601 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
603 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
604 B->appendInitializer(I, cfg->getBumpVectorContext());
606 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
607 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
609 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
610 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
612 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
613 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
615 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
616 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
618 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
619 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
622 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
623 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
626 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
627 LocalScope::const_iterator B, LocalScope::const_iterator E);
629 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
630 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
631 cfg->getBumpVectorContext());
634 /// Add a reachable successor to a block, with the alternate variant that is
636 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
637 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
638 cfg->getBumpVectorContext());
641 /// \brief Find a relational comparison with an expression evaluating to a
642 /// boolean and a constant other than 0 and 1.
643 /// e.g. if ((x < y) == 10)
644 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
645 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
646 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
648 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
649 const Expr *BoolExpr = RHSExpr;
650 bool IntFirst = true;
652 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
657 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
660 llvm::APInt IntValue = IntLiteral->getValue();
661 if ((IntValue == 1) || (IntValue == 0))
664 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
665 !IntValue.isNegative();
667 BinaryOperatorKind Bok = B->getOpcode();
668 if (Bok == BO_GT || Bok == BO_GE) {
669 // Always true for 10 > bool and bool > -1
670 // Always false for -1 > bool and bool > 10
671 return TryResult(IntFirst == IntLarger);
673 // Always true for -1 < bool and bool < 10
674 // Always false for 10 < bool and bool < -1
675 return TryResult(IntFirst != IntLarger);
679 /// Find an incorrect equality comparison. Either with an expression
680 /// evaluating to a boolean and a constant other than 0 and 1.
681 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
682 /// true/false e.q. (x & 8) == 4.
683 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
684 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
685 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
687 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
688 const Expr *BoolExpr = RHSExpr;
691 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
698 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
699 if (BitOp && (BitOp->getOpcode() == BO_And ||
700 BitOp->getOpcode() == BO_Or)) {
701 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
702 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
704 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
707 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
712 llvm::APInt L1 = IntLiteral->getValue();
713 llvm::APInt L2 = IntLiteral2->getValue();
714 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
715 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
716 if (BuildOpts.Observer)
717 BuildOpts.Observer->compareBitwiseEquality(B,
718 B->getOpcode() != BO_EQ);
719 TryResult(B->getOpcode() != BO_EQ);
721 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
722 llvm::APInt IntValue = IntLiteral->getValue();
723 if ((IntValue == 1) || (IntValue == 0)) {
726 return TryResult(B->getOpcode() != BO_EQ);
732 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
733 const llvm::APSInt &Value1,
734 const llvm::APSInt &Value2) {
735 assert(Value1.isSigned() == Value2.isSigned());
740 return TryResult(Value1 == Value2);
742 return TryResult(Value1 != Value2);
744 return TryResult(Value1 < Value2);
746 return TryResult(Value1 <= Value2);
748 return TryResult(Value1 > Value2);
750 return TryResult(Value1 >= Value2);
754 /// \brief Find a pair of comparison expressions with or without parentheses
755 /// with a shared variable and constants and a logical operator between them
756 /// that always evaluates to either true or false.
757 /// e.g. if (x != 3 || x != 4)
758 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
759 assert(B->isLogicalOp());
760 const BinaryOperator *LHS =
761 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
762 const BinaryOperator *RHS =
763 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
767 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
770 const DeclRefExpr *Decl1;
772 BinaryOperatorKind BO1;
773 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
775 if (!Decl1 || !Expr1)
778 const DeclRefExpr *Decl2;
780 BinaryOperatorKind BO2;
781 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
783 if (!Decl2 || !Expr2)
786 // Check that it is the same variable on both sides.
787 if (Decl1->getDecl() != Decl2->getDecl())
790 // Make sure the user's intent is clear (e.g. they're comparing against two
791 // int literals, or two things from the same enum)
792 if (!areExprTypesCompatible(Expr1, Expr2))
797 if (!Expr1->EvaluateAsInt(L1, *Context) ||
798 !Expr2->EvaluateAsInt(L2, *Context))
801 // Can't compare signed with unsigned or with different bit width.
802 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
805 // Values that will be used to determine if result of logical
806 // operator is always true/false
807 const llvm::APSInt Values[] = {
808 // Value less than both Value1 and Value2
809 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
812 // Value between Value1 and Value2
813 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
817 // Value greater than both Value1 and Value2
818 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
821 // Check whether expression is always true/false by evaluating the following
822 // * variable x is less than the smallest literal.
823 // * variable x is equal to the smallest literal.
824 // * Variable x is between smallest and largest literal.
825 // * Variable x is equal to the largest literal.
826 // * Variable x is greater than largest literal.
827 bool AlwaysTrue = true, AlwaysFalse = true;
828 for (const llvm::APSInt &Value : Values) {
829 TryResult Res1, Res2;
830 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
831 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
833 if (!Res1.isKnown() || !Res2.isKnown())
836 if (B->getOpcode() == BO_LAnd) {
837 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
838 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
840 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
841 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
845 if (AlwaysTrue || AlwaysFalse) {
846 if (BuildOpts.Observer)
847 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
848 return TryResult(AlwaysTrue);
853 /// Try and evaluate an expression to an integer constant.
854 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
855 if (!BuildOpts.PruneTriviallyFalseEdges)
857 return !S->isTypeDependent() &&
858 !S->isValueDependent() &&
859 S->EvaluateAsRValue(outResult, *Context);
862 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
863 /// if we can evaluate to a known value, otherwise return -1.
864 TryResult tryEvaluateBool(Expr *S) {
865 if (!BuildOpts.PruneTriviallyFalseEdges ||
866 S->isTypeDependent() || S->isValueDependent())
869 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
870 if (Bop->isLogicalOp()) {
871 // Check the cache first.
872 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
873 if (I != CachedBoolEvals.end())
874 return I->second; // already in map;
876 // Retrieve result at first, or the map might be updated.
877 TryResult Result = evaluateAsBooleanConditionNoCache(S);
878 CachedBoolEvals[S] = Result; // update or insert
882 switch (Bop->getOpcode()) {
884 // For 'x & 0' and 'x * 0', we can determine that
885 // the value is always false.
888 // If either operand is zero, we know the value
891 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
892 if (!IntVal.getBoolValue()) {
893 return TryResult(false);
896 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
897 if (!IntVal.getBoolValue()) {
898 return TryResult(false);
907 return evaluateAsBooleanConditionNoCache(S);
910 /// \brief Evaluate as boolean \param E without using the cache.
911 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
912 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
913 if (Bop->isLogicalOp()) {
914 TryResult LHS = tryEvaluateBool(Bop->getLHS());
916 // We were able to evaluate the LHS, see if we can get away with not
917 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
918 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
921 TryResult RHS = tryEvaluateBool(Bop->getRHS());
923 if (Bop->getOpcode() == BO_LOr)
924 return LHS.isTrue() || RHS.isTrue();
926 return LHS.isTrue() && RHS.isTrue();
929 TryResult RHS = tryEvaluateBool(Bop->getRHS());
931 // We can't evaluate the LHS; however, sometimes the result
932 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
933 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
936 TryResult BopRes = checkIncorrectLogicOperator(Bop);
937 if (BopRes.isKnown())
938 return BopRes.isTrue();
943 } else if (Bop->isEqualityOp()) {
944 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
945 if (BopRes.isKnown())
946 return BopRes.isTrue();
947 } else if (Bop->isRelationalOp()) {
948 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
949 if (BopRes.isKnown())
950 return BopRes.isTrue();
955 if (E->EvaluateAsBooleanCondition(Result, *Context))
963 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
964 const Stmt *stmt) const {
965 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
968 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
969 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
971 if (!BuildOpts.forcedBlkExprs)
974 if (lastLookup == stmt) {
976 assert(cachedEntry->first == stmt);
984 // Perform the lookup!
985 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
988 // No need to update 'cachedEntry', since it will always be null.
989 assert(!cachedEntry);
993 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
994 if (itr == fb->end()) {
995 cachedEntry = nullptr;
1003 // FIXME: Add support for dependent-sized array types in C++?
1004 // Does it even make sense to build a CFG for an uninstantiated template?
1005 static const VariableArrayType *FindVA(const Type *t) {
1006 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1007 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
1008 if (vat->getSizeExpr())
1011 t = vt->getElementType().getTypePtr();
1017 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1018 /// arbitrary statement. Examples include a single expression or a function
1019 /// body (compound statement). The ownership of the returned CFG is
1020 /// transferred to the caller. If CFG construction fails, this method returns
1022 std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
1027 // Create an empty block that will serve as the exit block for the CFG. Since
1028 // this is the first block added to the CFG, it will be implicitly registered
1029 // as the exit block.
1030 Succ = createBlock();
1031 assert(Succ == &cfg->getExit());
1032 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
1034 if (BuildOpts.AddImplicitDtors)
1035 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1036 addImplicitDtorsForDestructor(DD);
1038 // Visit the statements and create the CFG.
1039 CFGBlock *B = addStmt(Statement);
1044 // For C++ constructor add initializers to CFG.
1045 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1046 for (auto *I : llvm::reverse(CD->inits())) {
1047 B = addInitializer(I);
1056 // Backpatch the gotos whose label -> block mappings we didn't know when we
1057 // encountered them.
1058 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1059 E = BackpatchBlocks.end(); I != E; ++I ) {
1061 CFGBlock *B = I->block;
1062 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
1063 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1065 // If there is no target for the goto, then we are looking at an
1066 // incomplete AST. Handle this by not registering a successor.
1067 if (LI == LabelMap.end()) continue;
1069 JumpTarget JT = LI->second;
1070 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1072 addSuccessor(B, JT.block);
1075 // Add successors to the Indirect Goto Dispatch block (if we have one).
1076 if (CFGBlock *B = cfg->getIndirectGotoBlock())
1077 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1078 E = AddressTakenLabels.end(); I != E; ++I ) {
1080 // Lookup the target block.
1081 LabelMapTy::iterator LI = LabelMap.find(*I);
1083 // If there is no target block that contains label, then we are looking
1084 // at an incomplete AST. Handle this by not registering a successor.
1085 if (LI == LabelMap.end()) continue;
1087 addSuccessor(B, LI->second.block);
1090 // Create an empty entry block that has no predecessors.
1091 cfg->setEntry(createBlock());
1093 return std::move(cfg);
1096 /// createBlock - Used to lazily create blocks that are connected
1097 /// to the current (global) succcessor.
1098 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1099 CFGBlock *B = cfg->createBlock();
1100 if (add_successor && Succ)
1101 addSuccessor(B, Succ);
1105 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1106 /// CFG. It is *not* connected to the current (global) successor, and instead
1107 /// directly tied to the exit block in order to be reachable.
1108 CFGBlock *CFGBuilder::createNoReturnBlock() {
1109 CFGBlock *B = createBlock(false);
1110 B->setHasNoReturnElement();
1111 addSuccessor(B, &cfg->getExit(), Succ);
1115 /// addInitializer - Add C++ base or member initializer element to CFG.
1116 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
1117 if (!BuildOpts.AddInitializers)
1120 bool HasTemporaries = false;
1122 // Destructors of temporaries in initialization expression should be called
1123 // after initialization finishes.
1124 Expr *Init = I->getInit();
1126 HasTemporaries = isa<ExprWithCleanups>(Init);
1128 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1129 // Generate destructors for temporaries in initialization expression.
1130 TempDtorContext Context;
1131 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1132 /*BindToTemporary=*/false, Context);
1137 appendInitializer(Block, I);
1140 if (HasTemporaries) {
1141 // For expression with temporaries go directly to subexpression to omit
1142 // generating destructors for the second time.
1143 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1145 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1146 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1147 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1148 // may cause the same Expr to appear more than once in the CFG. Doing it
1149 // here is safe because there's only one initializer per field.
1151 appendStmt(Block, Default);
1152 if (Stmt *Child = Default->getExpr())
1153 if (CFGBlock *R = Visit(Child))
1164 /// \brief Retrieve the type of the temporary object whose lifetime was
1165 /// extended by a local reference with the given initializer.
1166 static QualType getReferenceInitTemporaryType(ASTContext &Context,
1168 bool *FoundMTE = nullptr) {
1170 // Skip parentheses.
1171 Init = Init->IgnoreParens();
1173 // Skip through cleanups.
1174 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1175 Init = EWC->getSubExpr();
1179 // Skip through the temporary-materialization expression.
1180 if (const MaterializeTemporaryExpr *MTE
1181 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1182 Init = MTE->GetTemporaryExpr();
1188 // Skip derived-to-base and no-op casts.
1189 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1190 if ((CE->getCastKind() == CK_DerivedToBase ||
1191 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1192 CE->getCastKind() == CK_NoOp) &&
1193 Init->getType()->isRecordType()) {
1194 Init = CE->getSubExpr();
1199 // Skip member accesses into rvalues.
1200 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1201 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1202 Init = ME->getBase();
1210 return Init->getType();
1213 /// addAutomaticObjDtors - Add to current block automatic objects destructors
1214 /// for objects in range of local scope positions. Use S as trigger statement
1215 /// for destructors.
1216 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
1217 LocalScope::const_iterator E, Stmt *S) {
1218 if (!BuildOpts.AddImplicitDtors)
1224 // We need to append the destructors in reverse order, but any one of them
1225 // may be a no-return destructor which changes the CFG. As a result, buffer
1226 // this sequence up and replay them in reverse order when appending onto the
1228 SmallVector<VarDecl*, 10> Decls;
1229 Decls.reserve(B.distance(E));
1230 for (LocalScope::const_iterator I = B; I != E; ++I)
1231 Decls.push_back(*I);
1233 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1236 // If this destructor is marked as a no-return destructor, we need to
1237 // create a new block for the destructor which does not have as a successor
1238 // anything built thus far: control won't flow out of this block.
1239 QualType Ty = (*I)->getType();
1240 if (Ty->isReferenceType()) {
1241 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
1243 Ty = Context->getBaseElementType(Ty);
1245 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
1246 Block = createNoReturnBlock();
1250 appendAutomaticObjDtor(Block, *I, S);
1254 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
1255 /// base and member objects in destructor.
1256 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1257 assert (BuildOpts.AddImplicitDtors
1258 && "Can be called only when dtors should be added");
1259 const CXXRecordDecl *RD = DD->getParent();
1261 // At the end destroy virtual base objects.
1262 for (const auto &VI : RD->vbases()) {
1263 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
1264 if (!CD->hasTrivialDestructor()) {
1266 appendBaseDtor(Block, &VI);
1270 // Before virtual bases destroy direct base objects.
1271 for (const auto &BI : RD->bases()) {
1272 if (!BI.isVirtual()) {
1273 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
1274 if (!CD->hasTrivialDestructor()) {
1276 appendBaseDtor(Block, &BI);
1281 // First destroy member objects.
1282 for (auto *FI : RD->fields()) {
1283 // Check for constant size array. Set type to array element type.
1284 QualType QT = FI->getType();
1285 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1286 if (AT->getSize() == 0)
1288 QT = AT->getElementType();
1291 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1292 if (!CD->hasTrivialDestructor()) {
1294 appendMemberDtor(Block, FI);
1299 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1300 /// way return valid LocalScope object.
1301 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1304 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1305 return new (alloc.Allocate<LocalScope>())
1306 LocalScope(BumpVectorContext(alloc), ScopePos);
1309 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
1310 /// that should create implicit scope (e.g. if/else substatements).
1311 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
1312 if (!BuildOpts.AddImplicitDtors)
1315 LocalScope *Scope = nullptr;
1317 // For compound statement we will be creating explicit scope.
1318 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
1319 for (auto *BI : CS->body()) {
1320 Stmt *SI = BI->stripLabelLikeStatements();
1321 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
1322 Scope = addLocalScopeForDeclStmt(DS, Scope);
1327 // For any other statement scope will be implicit and as such will be
1328 // interesting only for DeclStmt.
1329 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
1330 addLocalScopeForDeclStmt(DS);
1333 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1334 /// reuse Scope if not NULL.
1335 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
1336 LocalScope* Scope) {
1337 if (!BuildOpts.AddImplicitDtors)
1340 for (auto *DI : DS->decls())
1341 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
1342 Scope = addLocalScopeForVarDecl(VD, Scope);
1346 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1347 /// create add scope for automatic objects and temporary objects bound to
1348 /// const reference. Will reuse Scope if not NULL.
1349 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
1350 LocalScope* Scope) {
1351 if (!BuildOpts.AddImplicitDtors)
1354 // Check if variable is local.
1355 switch (VD->getStorageClass()) {
1360 default: return Scope;
1363 // Check for const references bound to temporary. Set type to pointee.
1364 QualType QT = VD->getType();
1365 if (QT.getTypePtr()->isReferenceType()) {
1366 // Attempt to determine whether this declaration lifetime-extends a
1369 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1370 // temporaries, and a single declaration can extend multiple temporaries.
1371 // We should look at the storage duration on each nested
1372 // MaterializeTemporaryExpr instead.
1373 const Expr *Init = VD->getInit();
1377 // Lifetime-extending a temporary.
1378 bool FoundMTE = false;
1379 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1384 // Check for constant size array. Set type to array element type.
1385 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1386 if (AT->getSize() == 0)
1388 QT = AT->getElementType();
1391 // Check if type is a C++ class with non-trivial destructor.
1392 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1393 if (!CD->hasTrivialDestructor()) {
1394 // Add the variable to scope
1395 Scope = createOrReuseLocalScope(Scope);
1397 ScopePos = Scope->begin();
1402 /// addLocalScopeAndDtors - For given statement add local scope for it and
1403 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1404 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1405 if (!BuildOpts.AddImplicitDtors)
1408 LocalScope::const_iterator scopeBeginPos = ScopePos;
1409 addLocalScopeForStmt(S);
1410 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1413 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1414 /// variables with automatic storage duration to CFGBlock's elements vector.
1415 /// Elements will be prepended to physical beginning of the vector which
1416 /// happens to be logical end. Use blocks terminator as statement that specifies
1417 /// destructors call site.
1418 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1419 /// no-return destructors properly.
1420 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1421 LocalScope::const_iterator B, LocalScope::const_iterator E) {
1422 BumpVectorContext &C = cfg->getBumpVectorContext();
1423 CFGBlock::iterator InsertPos
1424 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1425 for (LocalScope::const_iterator I = B; I != E; ++I)
1426 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1427 Blk->getTerminator());
1430 /// Visit - Walk the subtree of a statement and add extra
1431 /// blocks for ternary operators, &&, and ||. We also process "," and
1432 /// DeclStmts (which may contain nested control-flow).
1433 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1439 if (Expr *E = dyn_cast<Expr>(S))
1440 S = E->IgnoreParens();
1442 switch (S->getStmtClass()) {
1444 return VisitStmt(S, asc);
1446 case Stmt::AddrLabelExprClass:
1447 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1449 case Stmt::BinaryConditionalOperatorClass:
1450 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1452 case Stmt::BinaryOperatorClass:
1453 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1455 case Stmt::BlockExprClass:
1456 return VisitBlockExpr(cast<BlockExpr>(S), asc);
1458 case Stmt::BreakStmtClass:
1459 return VisitBreakStmt(cast<BreakStmt>(S));
1461 case Stmt::CallExprClass:
1462 case Stmt::CXXOperatorCallExprClass:
1463 case Stmt::CXXMemberCallExprClass:
1464 case Stmt::UserDefinedLiteralClass:
1465 return VisitCallExpr(cast<CallExpr>(S), asc);
1467 case Stmt::CaseStmtClass:
1468 return VisitCaseStmt(cast<CaseStmt>(S));
1470 case Stmt::ChooseExprClass:
1471 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1473 case Stmt::CompoundStmtClass:
1474 return VisitCompoundStmt(cast<CompoundStmt>(S));
1476 case Stmt::ConditionalOperatorClass:
1477 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1479 case Stmt::ContinueStmtClass:
1480 return VisitContinueStmt(cast<ContinueStmt>(S));
1482 case Stmt::CXXCatchStmtClass:
1483 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1485 case Stmt::ExprWithCleanupsClass:
1486 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1488 case Stmt::CXXDefaultArgExprClass:
1489 case Stmt::CXXDefaultInitExprClass:
1490 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1491 // called function's declaration, not by the caller. If we simply add
1492 // this expression to the CFG, we could end up with the same Expr
1493 // appearing multiple times.
1494 // PR13385 / <rdar://problem/12156507>
1496 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1497 // expression to be used in the same function (through aggregate
1499 return VisitStmt(S, asc);
1501 case Stmt::CXXBindTemporaryExprClass:
1502 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1504 case Stmt::CXXConstructExprClass:
1505 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1507 case Stmt::CXXNewExprClass:
1508 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1510 case Stmt::CXXDeleteExprClass:
1511 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1513 case Stmt::CXXFunctionalCastExprClass:
1514 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1516 case Stmt::CXXTemporaryObjectExprClass:
1517 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1519 case Stmt::CXXThrowExprClass:
1520 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1522 case Stmt::CXXTryStmtClass:
1523 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1525 case Stmt::CXXForRangeStmtClass:
1526 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1528 case Stmt::DeclStmtClass:
1529 return VisitDeclStmt(cast<DeclStmt>(S));
1531 case Stmt::DefaultStmtClass:
1532 return VisitDefaultStmt(cast<DefaultStmt>(S));
1534 case Stmt::DoStmtClass:
1535 return VisitDoStmt(cast<DoStmt>(S));
1537 case Stmt::ForStmtClass:
1538 return VisitForStmt(cast<ForStmt>(S));
1540 case Stmt::GotoStmtClass:
1541 return VisitGotoStmt(cast<GotoStmt>(S));
1543 case Stmt::IfStmtClass:
1544 return VisitIfStmt(cast<IfStmt>(S));
1546 case Stmt::ImplicitCastExprClass:
1547 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1549 case Stmt::IndirectGotoStmtClass:
1550 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1552 case Stmt::LabelStmtClass:
1553 return VisitLabelStmt(cast<LabelStmt>(S));
1555 case Stmt::LambdaExprClass:
1556 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1558 case Stmt::MemberExprClass:
1559 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1561 case Stmt::NullStmtClass:
1564 case Stmt::ObjCAtCatchStmtClass:
1565 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1567 case Stmt::ObjCAutoreleasePoolStmtClass:
1568 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1570 case Stmt::ObjCAtSynchronizedStmtClass:
1571 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1573 case Stmt::ObjCAtThrowStmtClass:
1574 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1576 case Stmt::ObjCAtTryStmtClass:
1577 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1579 case Stmt::ObjCForCollectionStmtClass:
1580 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1582 case Stmt::OpaqueValueExprClass:
1585 case Stmt::PseudoObjectExprClass:
1586 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1588 case Stmt::ReturnStmtClass:
1589 return VisitReturnStmt(cast<ReturnStmt>(S));
1591 case Stmt::UnaryExprOrTypeTraitExprClass:
1592 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1595 case Stmt::StmtExprClass:
1596 return VisitStmtExpr(cast<StmtExpr>(S), asc);
1598 case Stmt::SwitchStmtClass:
1599 return VisitSwitchStmt(cast<SwitchStmt>(S));
1601 case Stmt::UnaryOperatorClass:
1602 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1604 case Stmt::WhileStmtClass:
1605 return VisitWhileStmt(cast<WhileStmt>(S));
1609 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1610 if (asc.alwaysAdd(*this, S)) {
1612 appendStmt(Block, S);
1615 return VisitChildren(S);
1618 /// VisitChildren - Visit the children of a Stmt.
1619 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1620 CFGBlock *B = Block;
1622 // Visit the children in their reverse order so that they appear in
1623 // left-to-right (natural) order in the CFG.
1624 reverse_children RChildren(S);
1625 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1627 if (Stmt *Child = *I)
1628 if (CFGBlock *R = Visit(Child))
1634 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1635 AddStmtChoice asc) {
1636 AddressTakenLabels.insert(A->getLabel());
1638 if (asc.alwaysAdd(*this, A)) {
1640 appendStmt(Block, A);
1646 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1647 AddStmtChoice asc) {
1648 if (asc.alwaysAdd(*this, U)) {
1650 appendStmt(Block, U);
1653 return Visit(U->getSubExpr(), AddStmtChoice());
1656 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1657 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1658 appendStmt(ConfluenceBlock, B);
1663 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1664 ConfluenceBlock).first;
1667 std::pair<CFGBlock*, CFGBlock*>
1668 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1670 CFGBlock *TrueBlock,
1671 CFGBlock *FalseBlock) {
1673 // Introspect the RHS. If it is a nested logical operation, we recursively
1674 // build the CFG using this function. Otherwise, resort to default
1675 // CFG construction behavior.
1676 Expr *RHS = B->getRHS()->IgnoreParens();
1677 CFGBlock *RHSBlock, *ExitBlock;
1680 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1681 if (B_RHS->isLogicalOp()) {
1682 std::tie(RHSBlock, ExitBlock) =
1683 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1687 // The RHS is not a nested logical operation. Don't push the terminator
1688 // down further, but instead visit RHS and construct the respective
1689 // pieces of the CFG, and link up the RHSBlock with the terminator
1690 // we have been provided.
1691 ExitBlock = RHSBlock = createBlock(false);
1694 assert(TrueBlock == FalseBlock);
1695 addSuccessor(RHSBlock, TrueBlock);
1698 RHSBlock->setTerminator(Term);
1699 TryResult KnownVal = tryEvaluateBool(RHS);
1700 if (!KnownVal.isKnown())
1701 KnownVal = tryEvaluateBool(B);
1702 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1703 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
1707 RHSBlock = addStmt(RHS);
1712 return std::make_pair(nullptr, nullptr);
1714 // Generate the blocks for evaluating the LHS.
1715 Expr *LHS = B->getLHS()->IgnoreParens();
1717 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1718 if (B_LHS->isLogicalOp()) {
1719 if (B->getOpcode() == BO_LOr)
1720 FalseBlock = RHSBlock;
1722 TrueBlock = RHSBlock;
1724 // For the LHS, treat 'B' as the terminator that we want to sink
1725 // into the nested branch. The RHS always gets the top-most
1727 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1730 // Create the block evaluating the LHS.
1731 // This contains the '&&' or '||' as the terminator.
1732 CFGBlock *LHSBlock = createBlock(false);
1733 LHSBlock->setTerminator(B);
1736 CFGBlock *EntryLHSBlock = addStmt(LHS);
1739 return std::make_pair(nullptr, nullptr);
1741 // See if this is a known constant.
1742 TryResult KnownVal = tryEvaluateBool(LHS);
1744 // Now link the LHSBlock with RHSBlock.
1745 if (B->getOpcode() == BO_LOr) {
1746 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1747 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
1749 assert(B->getOpcode() == BO_LAnd);
1750 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1751 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
1754 return std::make_pair(EntryLHSBlock, ExitBlock);
1758 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1759 AddStmtChoice asc) {
1761 if (B->isLogicalOp())
1762 return VisitLogicalOperator(B);
1764 if (B->getOpcode() == BO_Comma) { // ,
1766 appendStmt(Block, B);
1767 addStmt(B->getRHS());
1768 return addStmt(B->getLHS());
1771 if (B->isAssignmentOp()) {
1772 if (asc.alwaysAdd(*this, B)) {
1774 appendStmt(Block, B);
1777 return Visit(B->getRHS());
1780 if (asc.alwaysAdd(*this, B)) {
1782 appendStmt(Block, B);
1785 CFGBlock *RBlock = Visit(B->getRHS());
1786 CFGBlock *LBlock = Visit(B->getLHS());
1787 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1788 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1789 // return RBlock. Otherwise we'll incorrectly return NULL.
1790 return (LBlock ? LBlock : RBlock);
1793 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1794 if (asc.alwaysAdd(*this, E)) {
1796 appendStmt(Block, E);
1801 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1802 // "break" is a control-flow statement. Thus we stop processing the current
1807 // Now create a new block that ends with the break statement.
1808 Block = createBlock(false);
1809 Block->setTerminator(B);
1811 // If there is no target for the break, then we are looking at an incomplete
1812 // AST. This means that the CFG cannot be constructed.
1813 if (BreakJumpTarget.block) {
1814 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1815 addSuccessor(Block, BreakJumpTarget.block);
1823 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1824 QualType Ty = E->getType();
1825 if (Ty->isFunctionPointerType())
1826 Ty = Ty->getAs<PointerType>()->getPointeeType();
1827 else if (Ty->isBlockPointerType())
1828 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1830 const FunctionType *FT = Ty->getAs<FunctionType>();
1832 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1833 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1834 Proto->isNothrow(Ctx))
1840 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1841 // Compute the callee type.
1842 QualType calleeType = C->getCallee()->getType();
1843 if (calleeType == Context->BoundMemberTy) {
1844 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1846 // We should only get a null bound type if processing a dependent
1847 // CFG. Recover by assuming nothing.
1848 if (!boundType.isNull()) calleeType = boundType;
1851 // If this is a call to a no-return function, this stops the block here.
1852 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1854 bool AddEHEdge = false;
1856 // Languages without exceptions are assumed to not throw.
1857 if (Context->getLangOpts().Exceptions) {
1858 if (BuildOpts.AddEHEdges)
1862 // If this is a call to a builtin function, it might not actually evaluate
1863 // its arguments. Don't add them to the CFG if this is the case.
1864 bool OmitArguments = false;
1866 if (FunctionDecl *FD = C->getDirectCallee()) {
1867 if (FD->isNoReturn())
1869 if (FD->hasAttr<NoThrowAttr>())
1871 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1872 OmitArguments = true;
1875 if (!CanThrow(C->getCallee(), *Context))
1878 if (OmitArguments) {
1879 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1880 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1882 appendStmt(Block, C);
1883 return Visit(C->getCallee());
1886 if (!NoReturn && !AddEHEdge) {
1887 return VisitStmt(C, asc.withAlwaysAdd(true));
1897 Block = createNoReturnBlock();
1899 Block = createBlock();
1901 appendStmt(Block, C);
1904 // Add exceptional edges.
1905 if (TryTerminatedBlock)
1906 addSuccessor(Block, TryTerminatedBlock);
1908 addSuccessor(Block, &cfg->getExit());
1911 return VisitChildren(C);
1914 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1915 AddStmtChoice asc) {
1916 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1917 appendStmt(ConfluenceBlock, C);
1921 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1922 Succ = ConfluenceBlock;
1924 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
1928 Succ = ConfluenceBlock;
1930 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
1934 Block = createBlock(false);
1935 // See if this is a known constant.
1936 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1937 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1938 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
1939 Block->setTerminator(C);
1940 return addStmt(C->getCond());
1944 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
1945 LocalScope::const_iterator scopeBeginPos = ScopePos;
1946 if (BuildOpts.AddImplicitDtors) {
1947 addLocalScopeForStmt(C);
1949 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
1950 // If the body ends with a ReturnStmt, the dtors will be added in
1952 addAutomaticObjDtors(ScopePos, scopeBeginPos, C);
1955 CFGBlock *LastBlock = Block;
1957 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1959 // If we hit a segment of code just containing ';' (NullStmts), we can
1960 // get a null block back. In such cases, just use the LastBlock
1961 if (CFGBlock *newBlock = addStmt(*I))
1962 LastBlock = newBlock;
1971 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1972 AddStmtChoice asc) {
1973 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1974 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
1976 // Create the confluence block that will "merge" the results of the ternary
1978 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1979 appendStmt(ConfluenceBlock, C);
1983 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1985 // Create a block for the LHS expression if there is an LHS expression. A
1986 // GCC extension allows LHS to be NULL, causing the condition to be the
1987 // value that is returned instead.
1988 // e.g: x ?: y is shorthand for: x ? x : y;
1989 Succ = ConfluenceBlock;
1991 CFGBlock *LHSBlock = nullptr;
1992 const Expr *trueExpr = C->getTrueExpr();
1993 if (trueExpr != opaqueValue) {
1994 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
2000 LHSBlock = ConfluenceBlock;
2002 // Create the block for the RHS expression.
2003 Succ = ConfluenceBlock;
2004 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
2008 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2009 if (BinaryOperator *Cond =
2010 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2011 if (Cond->isLogicalOp())
2012 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2014 // Create the block that will contain the condition.
2015 Block = createBlock(false);
2017 // See if this is a known constant.
2018 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
2019 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2020 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
2021 Block->setTerminator(C);
2022 Expr *condExpr = C->getCond();
2025 // Run the condition expression if it's not trivially expressed in
2026 // terms of the opaque value (or if there is no opaque value).
2027 if (condExpr != opaqueValue)
2030 // Before that, run the common subexpression if there was one.
2031 // At least one of this or the above will be run.
2032 return addStmt(BCO->getCommon());
2035 return addStmt(condExpr);
2038 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
2039 // Check if the Decl is for an __label__. If so, elide it from the
2041 if (isa<LabelDecl>(*DS->decl_begin()))
2044 // This case also handles static_asserts.
2045 if (DS->isSingleDecl())
2046 return VisitDeclSubExpr(DS);
2048 CFGBlock *B = nullptr;
2050 // Build an individual DeclStmt for each decl.
2051 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2052 E = DS->decl_rend();
2054 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
2055 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
2057 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2058 // automatically freed with the CFG.
2059 DeclGroupRef DG(*I);
2061 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
2062 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
2063 cfg->addSyntheticDeclStmt(DSNew, DS);
2065 // Append the fake DeclStmt to block.
2066 B = VisitDeclSubExpr(DSNew);
2072 /// VisitDeclSubExpr - Utility method to add block-level expressions for
2073 /// DeclStmts and initializers in them.
2074 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
2075 assert(DS->isSingleDecl() && "Can handle single declarations only.");
2076 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
2079 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2080 // runtime semantics.
2084 bool HasTemporaries = false;
2086 // Guard static initializers under a branch.
2087 CFGBlock *blockAfterStaticInit = nullptr;
2089 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2090 // For static variables, we need to create a branch to track
2091 // whether or not they are initialized.
2098 blockAfterStaticInit = Succ;
2101 // Destructors of temporaries in initialization expression should be called
2102 // after initialization finishes.
2103 Expr *Init = VD->getInit();
2105 HasTemporaries = isa<ExprWithCleanups>(Init);
2107 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
2108 // Generate destructors for temporaries in initialization expression.
2109 TempDtorContext Context;
2110 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2111 /*BindToTemporary=*/false, Context);
2116 appendStmt(Block, DS);
2118 // Keep track of the last non-null block, as 'Block' can be nulled out
2119 // if the initializer expression is something like a 'while' in a
2120 // statement-expression.
2121 CFGBlock *LastBlock = Block;
2124 if (HasTemporaries) {
2125 // For expression with temporaries go directly to subexpression to omit
2126 // generating destructors for the second time.
2127 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2128 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2129 LastBlock = newBlock;
2132 if (CFGBlock *newBlock = Visit(Init))
2133 LastBlock = newBlock;
2137 // If the type of VD is a VLA, then we must process its size expressions.
2138 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
2139 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
2140 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2141 LastBlock = newBlock;
2144 // Remove variable from local scope.
2145 if (ScopePos && VD == *ScopePos)
2148 CFGBlock *B = LastBlock;
2149 if (blockAfterStaticInit) {
2151 Block = createBlock(false);
2152 Block->setTerminator(DS);
2153 addSuccessor(Block, blockAfterStaticInit);
2154 addSuccessor(Block, B);
2161 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
2162 // We may see an if statement in the middle of a basic block, or it may be the
2163 // first statement we are processing. In either case, we create a new basic
2164 // block. First, we create the blocks for the then...else statements, and
2165 // then we create the block containing the if statement. If we were in the
2166 // middle of a block, we stop processing that block. That block is then the
2167 // implicit successor for the "then" and "else" clauses.
2169 // Save local scope position because in case of condition variable ScopePos
2170 // won't be restored when traversing AST.
2171 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2173 // Create local scope for C++17 if init-stmt if one exists.
2174 if (Stmt *Init = I->getInit()) {
2175 LocalScope::const_iterator BeginScopePos = ScopePos;
2176 addLocalScopeForStmt(Init);
2177 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2180 // Create local scope for possible condition variable.
2181 // Store scope position. Add implicit destructor.
2182 if (VarDecl *VD = I->getConditionVariable()) {
2183 LocalScope::const_iterator BeginScopePos = ScopePos;
2184 addLocalScopeForVarDecl(VD);
2185 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2188 // The block we were processing is now finished. Make it the successor
2196 // Process the false branch.
2197 CFGBlock *ElseBlock = Succ;
2199 if (Stmt *Else = I->getElse()) {
2200 SaveAndRestore<CFGBlock*> sv(Succ);
2202 // NULL out Block so that the recursive call to Visit will
2203 // create a new basic block.
2206 // If branch is not a compound statement create implicit scope
2207 // and add destructors.
2208 if (!isa<CompoundStmt>(Else))
2209 addLocalScopeAndDtors(Else);
2211 ElseBlock = addStmt(Else);
2213 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2214 ElseBlock = sv.get();
2221 // Process the true branch.
2222 CFGBlock *ThenBlock;
2224 Stmt *Then = I->getThen();
2226 SaveAndRestore<CFGBlock*> sv(Succ);
2229 // If branch is not a compound statement create implicit scope
2230 // and add destructors.
2231 if (!isa<CompoundStmt>(Then))
2232 addLocalScopeAndDtors(Then);
2234 ThenBlock = addStmt(Then);
2237 // We can reach here if the "then" body has all NullStmts.
2238 // Create an empty block so we can distinguish between true and false
2239 // branches in path-sensitive analyses.
2240 ThenBlock = createBlock(false);
2241 addSuccessor(ThenBlock, sv.get());
2248 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2249 // having these handle the actual control-flow jump. Note that
2250 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2251 // we resort to the old control-flow behavior. This special handling
2252 // removes infeasible paths from the control-flow graph by having the
2253 // control-flow transfer of '&&' or '||' go directly into the then/else
2255 if (!I->getConditionVariable())
2256 if (BinaryOperator *Cond =
2257 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
2258 if (Cond->isLogicalOp())
2259 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2261 // Now create a new block containing the if statement.
2262 Block = createBlock(false);
2264 // Set the terminator of the new block to the If statement.
2265 Block->setTerminator(I);
2267 // See if this is a known constant.
2268 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
2270 // Add the successors. If we know that specific branches are
2271 // unreachable, inform addSuccessor() of that knowledge.
2272 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2273 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
2275 // Add the condition as the last statement in the new block. This may create
2276 // new blocks as the condition may contain control-flow. Any newly created
2277 // blocks will be pointed to be "Block".
2278 CFGBlock *LastBlock = addStmt(I->getCond());
2280 // If the IfStmt contains a condition variable, add it and its
2281 // initializer to the CFG.
2282 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2284 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2287 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2288 if (Stmt *Init = I->getInit()) {
2290 LastBlock = addStmt(Init);
2297 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
2298 // If we were in the middle of a block we stop processing that block.
2300 // NOTE: If a "return" appears in the middle of a block, this means that the
2301 // code afterwards is DEAD (unreachable). We still keep a basic block
2302 // for that code; a simple "mark-and-sweep" from the entry block will be
2303 // able to report such dead blocks.
2305 // Create the new block.
2306 Block = createBlock(false);
2308 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
2310 // If the one of the destructors does not return, we already have the Exit
2311 // block as a successor.
2312 if (!Block->hasNoReturnElement())
2313 addSuccessor(Block, &cfg->getExit());
2315 // Add the return statement to the block. This may create new blocks if R
2316 // contains control-flow (short-circuit operations).
2317 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
2320 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
2321 // Get the block of the labeled statement. Add it to our map.
2322 addStmt(L->getSubStmt());
2323 CFGBlock *LabelBlock = Block;
2325 if (!LabelBlock) // This can happen when the body is empty, i.e.
2326 LabelBlock = createBlock(); // scopes that only contains NullStmts.
2328 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2329 "label already in map");
2330 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
2332 // Labels partition blocks, so this is the end of the basic block we were
2333 // processing (L is the block's label). Because this is label (and we have
2334 // already processed the substatement) there is no extra control-flow to worry
2336 LabelBlock->setLabel(L);
2340 // We set Block to NULL to allow lazy creation of a new block (if necessary);
2343 // This block is now the implicit successor of other blocks.
2349 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2350 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2351 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2352 if (Expr *CopyExpr = CI.getCopyExpr()) {
2353 CFGBlock *Tmp = Visit(CopyExpr);
2361 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2362 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2363 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2364 et = E->capture_init_end(); it != et; ++it) {
2365 if (Expr *Init = *it) {
2366 CFGBlock *Tmp = Visit(Init);
2374 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
2375 // Goto is a control-flow statement. Thus we stop processing the current
2376 // block and create a new one.
2378 Block = createBlock(false);
2379 Block->setTerminator(G);
2381 // If we already know the mapping to the label block add the successor now.
2382 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
2384 if (I == LabelMap.end())
2385 // We will need to backpatch this block later.
2386 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2388 JumpTarget JT = I->second;
2389 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2390 addSuccessor(Block, JT.block);
2396 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
2397 CFGBlock *LoopSuccessor = nullptr;
2399 // Save local scope position because in case of condition variable ScopePos
2400 // won't be restored when traversing AST.
2401 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2403 // Create local scope for init statement and possible condition variable.
2404 // Add destructor for init statement and condition variable.
2405 // Store scope position for continue statement.
2406 if (Stmt *Init = F->getInit())
2407 addLocalScopeForStmt(Init);
2408 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2410 if (VarDecl *VD = F->getConditionVariable())
2411 addLocalScopeForVarDecl(VD);
2412 LocalScope::const_iterator ContinueScopePos = ScopePos;
2414 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2416 // "for" is a control-flow statement. Thus we stop processing the current
2421 LoopSuccessor = Block;
2423 LoopSuccessor = Succ;
2425 // Save the current value for the break targets.
2426 // All breaks should go to the code following the loop.
2427 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2428 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2430 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2432 // Now create the loop body.
2434 assert(F->getBody());
2436 // Save the current values for Block, Succ, continue and break targets.
2437 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2438 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2440 // Create an empty block to represent the transition block for looping back
2441 // to the head of the loop. If we have increment code, it will
2442 // go in this block as well.
2443 Block = Succ = TransitionBlock = createBlock(false);
2444 TransitionBlock->setLoopTarget(F);
2446 if (Stmt *I = F->getInc()) {
2447 // Generate increment code in its own basic block. This is the target of
2448 // continue statements.
2452 // Finish up the increment (or empty) block if it hasn't been already.
2454 assert(Block == Succ);
2460 // The starting block for the loop increment is the block that should
2461 // represent the 'loop target' for looping back to the start of the loop.
2462 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2463 ContinueJumpTarget.block->setLoopTarget(F);
2465 // Loop body should end with destructor of Condition variable (if any).
2466 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
2468 // If body is not a compound statement create implicit scope
2469 // and add destructors.
2470 if (!isa<CompoundStmt>(F->getBody()))
2471 addLocalScopeAndDtors(F->getBody());
2473 // Now populate the body block, and in the process create new blocks as we
2474 // walk the body of the loop.
2475 BodyBlock = addStmt(F->getBody());
2478 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2479 // Use the continue jump target as the proxy for the body.
2480 BodyBlock = ContinueJumpTarget.block;
2486 // Because of short-circuit evaluation, the condition of the loop can span
2487 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2488 // evaluate the condition.
2489 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2492 Expr *C = F->getCond();
2494 // Specially handle logical operators, which have a slightly
2495 // more optimal CFG representation.
2496 if (BinaryOperator *Cond =
2497 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
2498 if (Cond->isLogicalOp()) {
2499 std::tie(EntryConditionBlock, ExitConditionBlock) =
2500 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2504 // The default case when not handling logical operators.
2505 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2506 ExitConditionBlock->setTerminator(F);
2508 // See if this is a known constant.
2509 TryResult KnownVal(true);
2512 // Now add the actual condition to the condition block.
2513 // Because the condition itself may contain control-flow, new blocks may
2514 // be created. Thus we update "Succ" after adding the condition.
2515 Block = ExitConditionBlock;
2516 EntryConditionBlock = addStmt(C);
2518 // If this block contains a condition variable, add both the condition
2519 // variable and initializer to the CFG.
2520 if (VarDecl *VD = F->getConditionVariable()) {
2521 if (Expr *Init = VD->getInit()) {
2523 appendStmt(Block, F->getConditionVariableDeclStmt());
2524 EntryConditionBlock = addStmt(Init);
2525 assert(Block == EntryConditionBlock);
2529 if (Block && badCFG)
2532 KnownVal = tryEvaluateBool(C);
2535 // Add the loop body entry as a successor to the condition.
2536 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2537 // Link up the condition block with the code that follows the loop. (the
2539 addSuccessor(ExitConditionBlock,
2540 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2544 // Link up the loop-back block to the entry condition block.
2545 addSuccessor(TransitionBlock, EntryConditionBlock);
2547 // The condition block is the implicit successor for any code above the loop.
2548 Succ = EntryConditionBlock;
2550 // If the loop contains initialization, create a new block for those
2551 // statements. This block can also contain statements that precede the loop.
2552 if (Stmt *I = F->getInit()) {
2553 Block = createBlock();
2557 // There is no loop initialization. We are thus basically a while loop.
2558 // NULL out Block to force lazy block construction.
2560 Succ = EntryConditionBlock;
2561 return EntryConditionBlock;
2564 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2565 if (asc.alwaysAdd(*this, M)) {
2567 appendStmt(Block, M);
2569 return Visit(M->getBase());
2572 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2573 // Objective-C fast enumeration 'for' statements:
2574 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2576 // for ( Type newVariable in collection_expression ) { statements }
2581 // 1. collection_expression
2582 // T. jump to loop_entry
2584 // 1. side-effects of element expression
2585 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2586 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2589 // T. jump to loop_entry
2595 // Type existingItem;
2596 // for ( existingItem in expression ) { statements }
2600 // the same with newVariable replaced with existingItem; the binding works
2601 // the same except that for one ObjCForCollectionStmt::getElement() returns
2602 // a DeclStmt and the other returns a DeclRefExpr.
2605 CFGBlock *LoopSuccessor = nullptr;
2610 LoopSuccessor = Block;
2613 LoopSuccessor = Succ;
2615 // Build the condition blocks.
2616 CFGBlock *ExitConditionBlock = createBlock(false);
2618 // Set the terminator for the "exit" condition block.
2619 ExitConditionBlock->setTerminator(S);
2621 // The last statement in the block should be the ObjCForCollectionStmt, which
2622 // performs the actual binding to 'element' and determines if there are any
2623 // more items in the collection.
2624 appendStmt(ExitConditionBlock, S);
2625 Block = ExitConditionBlock;
2627 // Walk the 'element' expression to see if there are any side-effects. We
2628 // generate new blocks as necessary. We DON'T add the statement by default to
2629 // the CFG unless it contains control-flow.
2630 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2631 AddStmtChoice::NotAlwaysAdd);
2638 // The condition block is the implicit successor for the loop body as well as
2639 // any code above the loop.
2640 Succ = EntryConditionBlock;
2642 // Now create the true branch.
2644 // Save the current values for Succ, continue and break targets.
2645 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2646 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2647 save_break(BreakJumpTarget);
2649 // Add an intermediate block between the BodyBlock and the
2650 // EntryConditionBlock to represent the "loop back" transition, for looping
2651 // back to the head of the loop.
2652 CFGBlock *LoopBackBlock = nullptr;
2653 Succ = LoopBackBlock = createBlock();
2654 LoopBackBlock->setLoopTarget(S);
2656 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2657 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2659 CFGBlock *BodyBlock = addStmt(S->getBody());
2662 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2668 // This new body block is a successor to our "exit" condition block.
2669 addSuccessor(ExitConditionBlock, BodyBlock);
2672 // Link up the condition block with the code that follows the loop.
2673 // (the false branch).
2674 addSuccessor(ExitConditionBlock, LoopSuccessor);
2676 // Now create a prologue block to contain the collection expression.
2677 Block = createBlock();
2678 return addStmt(S->getCollection());
2681 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2683 return addStmt(S->getSubStmt());
2684 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2687 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2688 // FIXME: Add locking 'primitives' to CFG for @synchronized.
2691 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2693 // The sync body starts its own basic block. This makes it a little easier
2694 // for diagnostic clients.
2703 // Add the @synchronized to the CFG.
2705 appendStmt(Block, S);
2707 // Inline the sync expression.
2708 return addStmt(S->getSynchExpr());
2711 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2716 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2719 // Add the PseudoObject as the last thing.
2720 appendStmt(Block, E);
2722 CFGBlock *lastBlock = Block;
2724 // Before that, evaluate all of the semantics in order. In
2725 // CFG-land, that means appending them in reverse order.
2726 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2727 Expr *Semantic = E->getSemanticExpr(--i);
2729 // If the semantic is an opaque value, we're being asked to bind
2730 // it to its source expression.
2731 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2732 Semantic = OVE->getSourceExpr();
2734 if (CFGBlock *B = Visit(Semantic))
2741 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2742 CFGBlock *LoopSuccessor = nullptr;
2744 // Save local scope position because in case of condition variable ScopePos
2745 // won't be restored when traversing AST.
2746 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2748 // Create local scope for possible condition variable.
2749 // Store scope position for continue statement.
2750 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2751 if (VarDecl *VD = W->getConditionVariable()) {
2752 addLocalScopeForVarDecl(VD);
2753 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2756 // "while" is a control-flow statement. Thus we stop processing the current
2761 LoopSuccessor = Block;
2764 LoopSuccessor = Succ;
2767 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
2769 // Process the loop body.
2771 assert(W->getBody());
2773 // Save the current values for Block, Succ, continue and break targets.
2774 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2775 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2776 save_break(BreakJumpTarget);
2778 // Create an empty block to represent the transition block for looping back
2779 // to the head of the loop.
2780 Succ = TransitionBlock = createBlock(false);
2781 TransitionBlock->setLoopTarget(W);
2782 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2784 // All breaks should go to the code following the loop.
2785 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2787 // Loop body should end with destructor of Condition variable (if any).
2788 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2790 // If body is not a compound statement create implicit scope
2791 // and add destructors.
2792 if (!isa<CompoundStmt>(W->getBody()))
2793 addLocalScopeAndDtors(W->getBody());
2795 // Create the body. The returned block is the entry to the loop body.
2796 BodyBlock = addStmt(W->getBody());
2799 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2800 else if (Block && badCFG)
2804 // Because of short-circuit evaluation, the condition of the loop can span
2805 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2806 // evaluate the condition.
2807 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
2810 Expr *C = W->getCond();
2812 // Specially handle logical operators, which have a slightly
2813 // more optimal CFG representation.
2814 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2815 if (Cond->isLogicalOp()) {
2816 std::tie(EntryConditionBlock, ExitConditionBlock) =
2817 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
2821 // The default case when not handling logical operators.
2822 ExitConditionBlock = createBlock(false);
2823 ExitConditionBlock->setTerminator(W);
2825 // Now add the actual condition to the condition block.
2826 // Because the condition itself may contain control-flow, new blocks may
2827 // be created. Thus we update "Succ" after adding the condition.
2828 Block = ExitConditionBlock;
2829 Block = EntryConditionBlock = addStmt(C);
2831 // If this block contains a condition variable, add both the condition
2832 // variable and initializer to the CFG.
2833 if (VarDecl *VD = W->getConditionVariable()) {
2834 if (Expr *Init = VD->getInit()) {
2836 appendStmt(Block, W->getConditionVariableDeclStmt());
2837 EntryConditionBlock = addStmt(Init);
2838 assert(Block == EntryConditionBlock);
2842 if (Block && badCFG)
2845 // See if this is a known constant.
2846 const TryResult& KnownVal = tryEvaluateBool(C);
2848 // Add the loop body entry as a successor to the condition.
2849 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
2850 // Link up the condition block with the code that follows the loop. (the
2852 addSuccessor(ExitConditionBlock,
2853 KnownVal.isTrue() ? nullptr : LoopSuccessor);
2857 // Link up the loop-back block to the entry condition block.
2858 addSuccessor(TransitionBlock, EntryConditionBlock);
2860 // There can be no more statements in the condition block since we loop back
2861 // to this block. NULL out Block to force lazy creation of another block.
2864 // Return the condition block, which is the dominating block for the loop.
2865 Succ = EntryConditionBlock;
2866 return EntryConditionBlock;
2870 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
2871 // FIXME: For now we pretend that @catch and the code it contains does not
2876 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
2877 // FIXME: This isn't complete. We basically treat @throw like a return
2880 // If we were in the middle of a block we stop processing that block.
2884 // Create the new block.
2885 Block = createBlock(false);
2887 // The Exit block is the only successor.
2888 addSuccessor(Block, &cfg->getExit());
2890 // Add the statement to the block. This may create new blocks if S contains
2891 // control-flow (short-circuit operations).
2892 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
2895 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
2896 // If we were in the middle of a block we stop processing that block.
2900 // Create the new block.
2901 Block = createBlock(false);
2903 if (TryTerminatedBlock)
2904 // The current try statement is the only successor.
2905 addSuccessor(Block, TryTerminatedBlock);
2907 // otherwise the Exit block is the only successor.
2908 addSuccessor(Block, &cfg->getExit());
2910 // Add the statement to the block. This may create new blocks if S contains
2911 // control-flow (short-circuit operations).
2912 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
2915 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
2916 CFGBlock *LoopSuccessor = nullptr;
2918 // "do...while" is a control-flow statement. Thus we stop processing the
2923 LoopSuccessor = Block;
2925 LoopSuccessor = Succ;
2927 // Because of short-circuit evaluation, the condition of the loop can span
2928 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2929 // evaluate the condition.
2930 CFGBlock *ExitConditionBlock = createBlock(false);
2931 CFGBlock *EntryConditionBlock = ExitConditionBlock;
2933 // Set the terminator for the "exit" condition block.
2934 ExitConditionBlock->setTerminator(D);
2936 // Now add the actual condition to the condition block. Because the condition
2937 // itself may contain control-flow, new blocks may be created.
2938 if (Stmt *C = D->getCond()) {
2939 Block = ExitConditionBlock;
2940 EntryConditionBlock = addStmt(C);
2947 // The condition block is the implicit successor for the loop body.
2948 Succ = EntryConditionBlock;
2950 // See if this is a known constant.
2951 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2953 // Process the loop body.
2954 CFGBlock *BodyBlock = nullptr;
2956 assert(D->getBody());
2958 // Save the current values for Block, Succ, and continue and break targets
2959 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2960 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2961 save_break(BreakJumpTarget);
2963 // All continues within this loop should go to the condition block
2964 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2966 // All breaks should go to the code following the loop.
2967 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2969 // NULL out Block to force lazy instantiation of blocks for the body.
2972 // If body is not a compound statement create implicit scope
2973 // and add destructors.
2974 if (!isa<CompoundStmt>(D->getBody()))
2975 addLocalScopeAndDtors(D->getBody());
2977 // Create the body. The returned block is the entry to the loop body.
2978 BodyBlock = addStmt(D->getBody());
2981 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2987 // Add an intermediate block between the BodyBlock and the
2988 // ExitConditionBlock to represent the "loop back" transition. Create an
2989 // empty block to represent the transition block for looping back to the
2990 // head of the loop.
2991 // FIXME: Can we do this more efficiently without adding another block?
2994 CFGBlock *LoopBackBlock = createBlock();
2995 LoopBackBlock->setLoopTarget(D);
2997 if (!KnownVal.isFalse())
2998 // Add the loop body entry as a successor to the condition.
2999 addSuccessor(ExitConditionBlock, LoopBackBlock);
3001 addSuccessor(ExitConditionBlock, nullptr);
3004 // Link up the condition block with the code that follows the loop.
3005 // (the false branch).
3006 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3008 // There can be no more statements in the body block(s) since we loop back to
3009 // the body. NULL out Block to force lazy creation of another block.
3012 // Return the loop body, which is the dominating block for the loop.
3017 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
3018 // "continue" is a control-flow statement. Thus we stop processing the
3023 // Now create a new block that ends with the continue statement.
3024 Block = createBlock(false);
3025 Block->setTerminator(C);
3027 // If there is no target for the continue, then we are looking at an
3028 // incomplete AST. This means the CFG cannot be constructed.
3029 if (ContinueJumpTarget.block) {
3030 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
3031 addSuccessor(Block, ContinueJumpTarget.block);
3038 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3039 AddStmtChoice asc) {
3041 if (asc.alwaysAdd(*this, E)) {
3043 appendStmt(Block, E);
3046 // VLA types have expressions that must be evaluated.
3047 CFGBlock *lastBlock = Block;
3049 if (E->isArgumentType()) {
3050 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
3051 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
3052 lastBlock = addStmt(VA->getSizeExpr());
3057 /// VisitStmtExpr - Utility method to handle (nested) statement
3058 /// expressions (a GCC extension).
3059 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
3060 if (asc.alwaysAdd(*this, SE)) {
3062 appendStmt(Block, SE);
3064 return VisitCompoundStmt(SE->getSubStmt());
3067 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
3068 // "switch" is a control-flow statement. Thus we stop processing the current
3070 CFGBlock *SwitchSuccessor = nullptr;
3072 // Save local scope position because in case of condition variable ScopePos
3073 // won't be restored when traversing AST.
3074 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3076 // Create local scope for C++17 switch init-stmt if one exists.
3077 if (Stmt *Init = Terminator->getInit()) {
3078 LocalScope::const_iterator BeginScopePos = ScopePos;
3079 addLocalScopeForStmt(Init);
3080 addAutomaticObjDtors(ScopePos, BeginScopePos, Terminator);
3083 // Create local scope for possible condition variable.
3084 // Store scope position. Add implicit destructor.
3085 if (VarDecl *VD = Terminator->getConditionVariable()) {
3086 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
3087 addLocalScopeForVarDecl(VD);
3088 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
3094 SwitchSuccessor = Block;
3095 } else SwitchSuccessor = Succ;
3097 // Save the current "switch" context.
3098 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
3099 save_default(DefaultCaseBlock);
3100 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3102 // Set the "default" case to be the block after the switch statement. If the
3103 // switch statement contains a "default:", this value will be overwritten with
3104 // the block for that code.
3105 DefaultCaseBlock = SwitchSuccessor;
3107 // Create a new block that will contain the switch statement.
3108 SwitchTerminatedBlock = createBlock(false);
3110 // Now process the switch body. The code after the switch is the implicit
3112 Succ = SwitchSuccessor;
3113 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
3115 // When visiting the body, the case statements should automatically get linked
3116 // up to the switch. We also don't keep a pointer to the body, since all
3117 // control-flow from the switch goes to case/default statements.
3118 assert(Terminator->getBody() && "switch must contain a non-NULL body");
3121 // For pruning unreachable case statements, save the current state
3122 // for tracking the condition value.
3123 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3126 // Determine if the switch condition can be explicitly evaluated.
3127 assert(Terminator->getCond() && "switch condition must be non-NULL");
3128 Expr::EvalResult result;
3129 bool b = tryEvaluate(Terminator->getCond(), result);
3130 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
3131 b ? &result : nullptr);
3133 // If body is not a compound statement create implicit scope
3134 // and add destructors.
3135 if (!isa<CompoundStmt>(Terminator->getBody()))
3136 addLocalScopeAndDtors(Terminator->getBody());
3138 addStmt(Terminator->getBody());
3144 // If we have no "default:" case, the default transition is to the code
3145 // following the switch body. Moreover, take into account if all the
3146 // cases of a switch are covered (e.g., switching on an enum value).
3148 // Note: We add a successor to a switch that is considered covered yet has no
3149 // case statements if the enumeration has no enumerators.
3150 bool SwitchAlwaysHasSuccessor = false;
3151 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3152 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3153 Terminator->getSwitchCaseList();
3154 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3155 !SwitchAlwaysHasSuccessor);
3157 // Add the terminator and condition in the switch block.
3158 SwitchTerminatedBlock->setTerminator(Terminator);
3159 Block = SwitchTerminatedBlock;
3160 CFGBlock *LastBlock = addStmt(Terminator->getCond());
3162 // If the SwitchStmt contains a condition variable, add both the
3163 // SwitchStmt and the condition variable initialization to the CFG.
3164 if (VarDecl *VD = Terminator->getConditionVariable()) {
3165 if (Expr *Init = VD->getInit()) {
3167 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
3168 LastBlock = addStmt(Init);
3172 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3173 if (Stmt *Init = Terminator->getInit()) {
3175 LastBlock = addStmt(Init);
3181 static bool shouldAddCase(bool &switchExclusivelyCovered,
3182 const Expr::EvalResult *switchCond,
3188 bool addCase = false;
3190 if (!switchExclusivelyCovered) {
3191 if (switchCond->Val.isInt()) {
3192 // Evaluate the LHS of the case value.
3193 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
3194 const llvm::APSInt &condInt = switchCond->Val.getInt();
3196 if (condInt == lhsInt) {
3198 switchExclusivelyCovered = true;
3200 else if (condInt > lhsInt) {
3201 if (const Expr *RHS = CS->getRHS()) {
3202 // Evaluate the RHS of the case value.
3203 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3204 if (V2 >= condInt) {
3206 switchExclusivelyCovered = true;
3217 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
3218 // CaseStmts are essentially labels, so they are the first statement in a
3220 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
3222 if (Stmt *Sub = CS->getSubStmt()) {
3223 // For deeply nested chains of CaseStmts, instead of doing a recursion
3224 // (which can blow out the stack), manually unroll and create blocks
3226 while (isa<CaseStmt>(Sub)) {
3227 CFGBlock *currentBlock = createBlock(false);
3228 currentBlock->setLabel(CS);
3231 addSuccessor(LastBlock, currentBlock);
3233 TopBlock = currentBlock;
3235 addSuccessor(SwitchTerminatedBlock,
3236 shouldAddCase(switchExclusivelyCovered, switchCond,
3238 ? currentBlock : nullptr);
3240 LastBlock = currentBlock;
3241 CS = cast<CaseStmt>(Sub);
3242 Sub = CS->getSubStmt();
3248 CFGBlock *CaseBlock = Block;
3250 CaseBlock = createBlock();
3252 // Cases statements partition blocks, so this is the top of the basic block we
3253 // were processing (the "case XXX:" is the label).
3254 CaseBlock->setLabel(CS);
3259 // Add this block to the list of successors for the block with the switch
3261 assert(SwitchTerminatedBlock);
3262 addSuccessor(SwitchTerminatedBlock, CaseBlock,
3263 shouldAddCase(switchExclusivelyCovered, switchCond,
3266 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3270 addSuccessor(LastBlock, CaseBlock);
3273 // This block is now the implicit successor of other blocks.
3280 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
3281 if (Terminator->getSubStmt())
3282 addStmt(Terminator->getSubStmt());
3284 DefaultCaseBlock = Block;
3286 if (!DefaultCaseBlock)
3287 DefaultCaseBlock = createBlock();
3289 // Default statements partition blocks, so this is the top of the basic block
3290 // we were processing (the "default:" is the label).
3291 DefaultCaseBlock->setLabel(Terminator);
3296 // Unlike case statements, we don't add the default block to the successors
3297 // for the switch statement immediately. This is done when we finish
3298 // processing the switch statement. This allows for the default case
3299 // (including a fall-through to the code after the switch statement) to always
3300 // be the last successor of a switch-terminated block.
3302 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3305 // This block is now the implicit successor of other blocks.
3306 Succ = DefaultCaseBlock;
3308 return DefaultCaseBlock;
3311 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3312 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3314 CFGBlock *TrySuccessor = nullptr;
3319 TrySuccessor = Block;
3320 } else TrySuccessor = Succ;
3322 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
3324 // Create a new block that will contain the try statement.
3325 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3326 // Add the terminator in the try block.
3327 NewTryTerminatedBlock->setTerminator(Terminator);
3329 bool HasCatchAll = false;
3330 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3331 // The code after the try is the implicit successor.
3332 Succ = TrySuccessor;
3333 CXXCatchStmt *CS = Terminator->getHandler(h);
3334 if (CS->getExceptionDecl() == nullptr) {
3338 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
3341 // Add this block to the list of successors for the block with the try
3343 addSuccessor(NewTryTerminatedBlock, CatchBlock);
3346 if (PrevTryTerminatedBlock)
3347 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
3349 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3352 // The code after the try is the implicit successor.
3353 Succ = TrySuccessor;
3355 // Save the current "try" context.
3356 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3357 cfg->addTryDispatchBlock(TryTerminatedBlock);
3359 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
3361 return addStmt(Terminator->getTryBlock());
3364 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
3365 // CXXCatchStmt are treated like labels, so they are the first statement in a
3368 // Save local scope position because in case of exception variable ScopePos
3369 // won't be restored when traversing AST.
3370 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3372 // Create local scope for possible exception variable.
3373 // Store scope position. Add implicit destructor.
3374 if (VarDecl *VD = CS->getExceptionDecl()) {
3375 LocalScope::const_iterator BeginScopePos = ScopePos;
3376 addLocalScopeForVarDecl(VD);
3377 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3380 if (CS->getHandlerBlock())
3381 addStmt(CS->getHandlerBlock());
3383 CFGBlock *CatchBlock = Block;
3385 CatchBlock = createBlock();
3387 // CXXCatchStmt is more than just a label. They have semantic meaning
3388 // as well, as they implicitly "initialize" the catch variable. Add
3389 // it to the CFG as a CFGElement so that the control-flow of these
3390 // semantics gets captured.
3391 appendStmt(CatchBlock, CS);
3393 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3395 CatchBlock->setLabel(CS);
3397 // Bail out if the CFG is bad.
3401 // We set Block to NULL to allow lazy creation of a new block (if necessary)
3407 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
3408 // C++0x for-range statements are specified as [stmt.ranged]:
3411 // auto && __range = range-init;
3412 // for ( auto __begin = begin-expr,
3413 // __end = end-expr;
3414 // __begin != __end;
3416 // for-range-declaration = *__begin;
3421 // Save local scope position before the addition of the implicit variables.
3422 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3424 // Create local scopes and destructors for range, begin and end variables.
3425 if (Stmt *Range = S->getRangeStmt())
3426 addLocalScopeForStmt(Range);
3427 if (Stmt *Begin = S->getBeginStmt())
3428 addLocalScopeForStmt(Begin);
3429 if (Stmt *End = S->getEndStmt())
3430 addLocalScopeForStmt(End);
3431 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3433 LocalScope::const_iterator ContinueScopePos = ScopePos;
3435 // "for" is a control-flow statement. Thus we stop processing the current
3437 CFGBlock *LoopSuccessor = nullptr;
3441 LoopSuccessor = Block;
3443 LoopSuccessor = Succ;
3445 // Save the current value for the break targets.
3446 // All breaks should go to the code following the loop.
3447 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3448 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3450 // The block for the __begin != __end expression.
3451 CFGBlock *ConditionBlock = createBlock(false);
3452 ConditionBlock->setTerminator(S);
3454 // Now add the actual condition to the condition block.
3455 if (Expr *C = S->getCond()) {
3456 Block = ConditionBlock;
3457 CFGBlock *BeginConditionBlock = addStmt(C);
3460 assert(BeginConditionBlock == ConditionBlock &&
3461 "condition block in for-range was unexpectedly complex");
3462 (void)BeginConditionBlock;
3465 // The condition block is the implicit successor for the loop body as well as
3466 // any code above the loop.
3467 Succ = ConditionBlock;
3469 // See if this is a known constant.
3470 TryResult KnownVal(true);
3473 KnownVal = tryEvaluateBool(S->getCond());
3475 // Now create the loop body.
3477 assert(S->getBody());
3479 // Save the current values for Block, Succ, and continue targets.
3480 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3481 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3483 // Generate increment code in its own basic block. This is the target of
3484 // continue statements.
3486 Succ = addStmt(S->getInc());
3489 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3491 // The starting block for the loop increment is the block that should
3492 // represent the 'loop target' for looping back to the start of the loop.
3493 ContinueJumpTarget.block->setLoopTarget(S);
3495 // Finish up the increment block and prepare to start the loop body.
3501 // Add implicit scope and dtors for loop variable.
3502 addLocalScopeAndDtors(S->getLoopVarStmt());
3504 // Populate a new block to contain the loop body and loop variable.
3505 addStmt(S->getBody());
3508 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3512 // This new body block is a successor to our condition block.
3513 addSuccessor(ConditionBlock,
3514 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
3517 // Link up the condition block with the code that follows the loop (the
3519 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
3521 // Add the initialization statements.
3522 Block = createBlock();
3523 addStmt(S->getBeginStmt());
3524 addStmt(S->getEndStmt());
3525 return addStmt(S->getRangeStmt());
3528 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3529 AddStmtChoice asc) {
3530 if (BuildOpts.AddTemporaryDtors) {
3531 // If adding implicit destructors visit the full expression for adding
3532 // destructors of temporaries.
3533 TempDtorContext Context;
3534 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3536 // Full expression has to be added as CFGStmt so it will be sequenced
3537 // before destructors of it's temporaries.
3538 asc = asc.withAlwaysAdd(true);
3540 return Visit(E->getSubExpr(), asc);
3543 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3544 AddStmtChoice asc) {
3545 if (asc.alwaysAdd(*this, E)) {
3547 appendStmt(Block, E);
3549 // We do not want to propagate the AlwaysAdd property.
3550 asc = asc.withAlwaysAdd(false);
3552 return Visit(E->getSubExpr(), asc);
3555 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3556 AddStmtChoice asc) {
3558 appendStmt(Block, C);
3560 return VisitChildren(C);
3563 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3564 AddStmtChoice asc) {
3567 appendStmt(Block, NE);
3569 if (NE->getInitializer())
3570 Block = Visit(NE->getInitializer());
3571 if (BuildOpts.AddCXXNewAllocator)
3572 appendNewAllocator(Block, NE);
3574 Block = Visit(NE->getArraySize());
3575 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3576 E = NE->placement_arg_end(); I != E; ++I)
3581 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3582 AddStmtChoice asc) {
3584 appendStmt(Block, DE);
3585 QualType DTy = DE->getDestroyedType();
3586 if (!DTy.isNull()) {
3587 DTy = DTy.getNonReferenceType();
3588 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3590 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3591 appendDeleteDtor(Block, RD, DE);
3595 return VisitChildren(DE);
3598 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3599 AddStmtChoice asc) {
3600 if (asc.alwaysAdd(*this, E)) {
3602 appendStmt(Block, E);
3603 // We do not want to propagate the AlwaysAdd property.
3604 asc = asc.withAlwaysAdd(false);
3606 return Visit(E->getSubExpr(), asc);
3609 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3610 AddStmtChoice asc) {
3612 appendStmt(Block, C);
3613 return VisitChildren(C);
3616 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3617 AddStmtChoice asc) {
3618 if (asc.alwaysAdd(*this, E)) {
3620 appendStmt(Block, E);
3622 return Visit(E->getSubExpr(), AddStmtChoice());
3625 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3626 // Lazily create the indirect-goto dispatch block if there isn't one already.
3627 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3630 IBlock = createBlock(false);
3631 cfg->setIndirectGotoBlock(IBlock);
3634 // IndirectGoto is a control-flow statement. Thus we stop processing the
3635 // current block and create a new one.
3639 Block = createBlock(false);
3640 Block->setTerminator(I);
3641 addSuccessor(Block, IBlock);
3642 return addStmt(I->getTarget());
3645 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3646 TempDtorContext &Context) {
3647 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3654 switch (E->getStmtClass()) {
3656 return VisitChildrenForTemporaryDtors(E, Context);
3658 case Stmt::BinaryOperatorClass:
3659 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3662 case Stmt::CXXBindTemporaryExprClass:
3663 return VisitCXXBindTemporaryExprForTemporaryDtors(
3664 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
3666 case Stmt::BinaryConditionalOperatorClass:
3667 case Stmt::ConditionalOperatorClass:
3668 return VisitConditionalOperatorForTemporaryDtors(
3669 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
3671 case Stmt::ImplicitCastExprClass:
3672 // For implicit cast we want BindToTemporary to be passed further.
3673 E = cast<CastExpr>(E)->getSubExpr();
3676 case Stmt::CXXFunctionalCastExprClass:
3677 // For functional cast we want BindToTemporary to be passed further.
3678 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3681 case Stmt::ParenExprClass:
3682 E = cast<ParenExpr>(E)->getSubExpr();
3685 case Stmt::MaterializeTemporaryExprClass: {
3686 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3687 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3688 SmallVector<const Expr *, 2> CommaLHSs;
3689 SmallVector<SubobjectAdjustment, 2> Adjustments;
3690 // Find the expression whose lifetime needs to be extended.
3691 E = const_cast<Expr *>(
3692 cast<MaterializeTemporaryExpr>(E)
3693 ->GetTemporaryExpr()
3694 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3695 // Visit the skipped comma operator left-hand sides for other temporaries.
3696 for (const Expr *CommaLHS : CommaLHSs) {
3697 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
3698 /*BindToTemporary=*/false, Context);
3703 case Stmt::BlockExprClass:
3704 // Don't recurse into blocks; their subexpressions don't get evaluated
3708 case Stmt::LambdaExprClass: {
3709 // For lambda expressions, only recurse into the capture initializers,
3710 // and not the body.
3711 auto *LE = cast<LambdaExpr>(E);
3712 CFGBlock *B = Block;
3713 for (Expr *Init : LE->capture_inits()) {
3714 if (CFGBlock *R = VisitForTemporaryDtors(
3715 Init, /*BindToTemporary=*/false, Context))
3721 case Stmt::CXXDefaultArgExprClass:
3722 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3725 case Stmt::CXXDefaultInitExprClass:
3726 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3731 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3732 TempDtorContext &Context) {
3733 if (isa<LambdaExpr>(E)) {
3734 // Do not visit the children of lambdas; they have their own CFGs.
3738 // When visiting children for destructors we want to visit them in reverse
3739 // order that they will appear in the CFG. Because the CFG is built
3740 // bottom-up, this means we visit them in their natural order, which
3741 // reverses them in the CFG.
3742 CFGBlock *B = Block;
3743 for (Stmt *Child : E->children())
3745 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
3751 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3752 BinaryOperator *E, TempDtorContext &Context) {
3753 if (E->isLogicalOp()) {
3754 VisitForTemporaryDtors(E->getLHS(), false, Context);
3755 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3756 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3757 RHSExecuted.negate();
3759 // We do not know at CFG-construction time whether the right-hand-side was
3760 // executed, thus we add a branch node that depends on the temporary
3761 // constructor call.
3762 TempDtorContext RHSContext(
3763 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
3764 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
3765 InsertTempDtorDecisionBlock(RHSContext);
3770 if (E->isAssignmentOp()) {
3771 // For assignment operator (=) LHS expression is visited
3772 // before RHS expression. For destructors visit them in reverse order.
3773 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3774 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3775 return LHSBlock ? LHSBlock : RHSBlock;
3778 // For any other binary operator RHS expression is visited before
3779 // LHS expression (order of children). For destructors visit them in reverse
3781 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3782 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3783 return RHSBlock ? RHSBlock : LHSBlock;
3786 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3787 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
3788 // First add destructors for temporaries in subexpression.
3789 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
3790 if (!BindToTemporary) {
3791 // If lifetime of temporary is not prolonged (by assigning to constant
3792 // reference) add destructor for it.
3794 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3796 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
3797 // If the destructor is marked as a no-return destructor, we need to
3798 // create a new block for the destructor which does not have as a
3799 // successor anything built thus far. Control won't flow out of this
3802 Block = createNoReturnBlock();
3803 } else if (Context.needsTempDtorBranch()) {
3804 // If we need to introduce a branch, we add a new block that we will hook
3805 // up to a decision block later.
3807 Block = createBlock();
3811 if (Context.needsTempDtorBranch()) {
3812 Context.setDecisionPoint(Succ, E);
3814 appendTemporaryDtor(Block, E);
3821 void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3822 CFGBlock *FalseSucc) {
3823 if (!Context.TerminatorExpr) {
3824 // If no temporary was found, we do not need to insert a decision point.
3827 assert(Context.TerminatorExpr);
3828 CFGBlock *Decision = createBlock(false);
3829 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
3830 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
3831 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
3832 !Context.KnownExecuted.isTrue());
3836 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3837 AbstractConditionalOperator *E, bool BindToTemporary,
3838 TempDtorContext &Context) {
3839 VisitForTemporaryDtors(E->getCond(), false, Context);
3840 CFGBlock *ConditionBlock = Block;
3841 CFGBlock *ConditionSucc = Succ;
3842 TryResult ConditionVal = tryEvaluateBool(E->getCond());
3843 TryResult NegatedVal = ConditionVal;
3844 if (NegatedVal.isKnown()) NegatedVal.negate();
3846 TempDtorContext TrueContext(
3847 bothKnownTrue(Context.KnownExecuted, ConditionVal));
3848 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
3849 CFGBlock *TrueBlock = Block;
3851 Block = ConditionBlock;
3852 Succ = ConditionSucc;
3853 TempDtorContext FalseContext(
3854 bothKnownTrue(Context.KnownExecuted, NegatedVal));
3855 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
3857 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
3858 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
3859 } else if (TrueContext.TerminatorExpr) {
3861 InsertTempDtorDecisionBlock(TrueContext);
3863 InsertTempDtorDecisionBlock(FalseContext);
3868 } // end anonymous namespace
3870 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3871 /// no successors or predecessors. If this is the first block created in the
3872 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
3873 CFGBlock *CFG::createBlock() {
3874 bool first_block = begin() == end();
3876 // Create the block.
3877 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
3878 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
3879 Blocks.push_back(Mem, BlkBVC);
3881 // If this is the first block, set it as the Entry and Exit.
3883 Entry = Exit = &back();
3885 // Return the block.
3889 /// buildCFG - Constructs a CFG from an AST.
3890 std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3891 ASTContext *C, const BuildOptions &BO) {
3892 CFGBuilder Builder(C, BO);
3893 return Builder.buildCFG(D, Statement);
3896 const CXXDestructorDecl *
3897 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
3898 switch (getKind()) {
3899 case CFGElement::Statement:
3900 case CFGElement::Initializer:
3901 case CFGElement::NewAllocator:
3902 llvm_unreachable("getDestructorDecl should only be used with "
3904 case CFGElement::AutomaticObjectDtor: {
3905 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
3906 QualType ty = var->getType();
3908 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
3910 // Lifetime-extending constructs are handled here. This works for a single
3911 // temporary in an initializer expression.
3912 if (ty->isReferenceType()) {
3913 if (const Expr *Init = var->getInit()) {
3914 ty = getReferenceInitTemporaryType(astContext, Init);
3918 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
3919 ty = arrayType->getElementType();
3921 const RecordType *recordType = ty->getAs<RecordType>();
3922 const CXXRecordDecl *classDecl =
3923 cast<CXXRecordDecl>(recordType->getDecl());
3924 return classDecl->getDestructor();
3926 case CFGElement::DeleteDtor: {
3927 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3928 QualType DTy = DE->getDestroyedType();
3929 DTy = DTy.getNonReferenceType();
3930 const CXXRecordDecl *classDecl =
3931 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3932 return classDecl->getDestructor();
3934 case CFGElement::TemporaryDtor: {
3935 const CXXBindTemporaryExpr *bindExpr =
3936 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
3937 const CXXTemporary *temp = bindExpr->getTemporary();
3938 return temp->getDestructor();
3940 case CFGElement::BaseDtor:
3941 case CFGElement::MemberDtor:
3943 // Not yet supported.
3946 llvm_unreachable("getKind() returned bogus value");
3949 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
3950 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3951 return DD->isNoReturn();
3955 //===----------------------------------------------------------------------===//
3956 // CFGBlock operations.
3957 //===----------------------------------------------------------------------===//
3959 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
3960 : ReachableBlock(IsReachable ? B : nullptr),
3961 UnreachableBlock(!IsReachable ? B : nullptr,
3962 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3964 CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3965 : ReachableBlock(B),
3966 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
3967 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3969 void CFGBlock::addSuccessor(AdjacentBlock Succ,
3970 BumpVectorContext &C) {
3971 if (CFGBlock *B = Succ.getReachableBlock())
3972 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
3974 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
3975 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
3977 Succs.push_back(Succ, C);
3980 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
3981 const CFGBlock *From, const CFGBlock *To) {
3983 if (F.IgnoreNullPredecessors && !From)
3986 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
3987 // If the 'To' has no label or is labeled but the label isn't a
3988 // CaseStmt then filter this edge.
3989 if (const SwitchStmt *S =
3990 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
3991 if (S->isAllEnumCasesCovered()) {
3992 const Stmt *L = To->getLabel();
3993 if (!L || !isa<CaseStmt>(L))
4002 //===----------------------------------------------------------------------===//
4003 // CFG pretty printing
4004 //===----------------------------------------------------------------------===//
4008 class StmtPrinterHelper : public PrinterHelper {
4009 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
4010 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
4013 signed currentBlock;
4015 const LangOptions &LangOpts;
4018 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
4019 : currentBlock(0), currStmt(0), LangOpts(LO)
4021 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4023 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
4024 BI != BEnd; ++BI, ++j ) {
4025 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4026 const Stmt *stmt= SE->getStmt();
4027 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
4030 switch (stmt->getStmtClass()) {
4031 case Stmt::DeclStmtClass:
4032 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4034 case Stmt::IfStmtClass: {
4035 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4040 case Stmt::ForStmtClass: {
4041 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4046 case Stmt::WhileStmtClass: {
4047 const VarDecl *var =
4048 cast<WhileStmt>(stmt)->getConditionVariable();
4053 case Stmt::SwitchStmtClass: {
4054 const VarDecl *var =
4055 cast<SwitchStmt>(stmt)->getConditionVariable();
4060 case Stmt::CXXCatchStmtClass: {
4061 const VarDecl *var =
4062 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4075 ~StmtPrinterHelper() override {}
4077 const LangOptions &getLangOpts() const { return LangOpts; }
4078 void setBlockID(signed i) { currentBlock = i; }
4079 void setStmtID(unsigned i) { currStmt = i; }
4081 bool handledStmt(Stmt *S, raw_ostream &OS) override {
4082 StmtMapTy::iterator I = StmtMap.find(S);
4084 if (I == StmtMap.end())
4087 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4088 && I->second.second == currStmt) {
4092 OS << "[B" << I->second.first << "." << I->second.second << "]";
4096 bool handleDecl(const Decl *D, raw_ostream &OS) {
4097 DeclMapTy::iterator I = DeclMap.find(D);
4099 if (I == DeclMap.end())
4102 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
4103 && I->second.second == currStmt) {
4107 OS << "[B" << I->second.first << "." << I->second.second << "]";
4111 } // end anonymous namespace
4115 class CFGBlockTerminatorPrint
4116 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
4119 StmtPrinterHelper* Helper;
4120 PrintingPolicy Policy;
4122 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
4123 const PrintingPolicy &Policy)
4124 : OS(os), Helper(helper), Policy(Policy) {
4125 this->Policy.IncludeNewlines = false;
4128 void VisitIfStmt(IfStmt *I) {
4130 if (Stmt *C = I->getCond())
4131 C->printPretty(OS, Helper, Policy);
4135 void VisitStmt(Stmt *Terminator) {
4136 Terminator->printPretty(OS, Helper, Policy);
4139 void VisitDeclStmt(DeclStmt *DS) {
4140 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4141 OS << "static init " << VD->getName();
4144 void VisitForStmt(ForStmt *F) {
4149 if (Stmt *C = F->getCond())
4150 C->printPretty(OS, Helper, Policy);
4157 void VisitWhileStmt(WhileStmt *W) {
4159 if (Stmt *C = W->getCond())
4160 C->printPretty(OS, Helper, Policy);
4163 void VisitDoStmt(DoStmt *D) {
4164 OS << "do ... while ";
4165 if (Stmt *C = D->getCond())
4166 C->printPretty(OS, Helper, Policy);
4169 void VisitSwitchStmt(SwitchStmt *Terminator) {
4171 Terminator->getCond()->printPretty(OS, Helper, Policy);
4174 void VisitCXXTryStmt(CXXTryStmt *CS) {
4178 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
4179 if (Stmt *Cond = C->getCond())
4180 Cond->printPretty(OS, Helper, Policy);
4181 OS << " ? ... : ...";
4184 void VisitChooseExpr(ChooseExpr *C) {
4185 OS << "__builtin_choose_expr( ";
4186 if (Stmt *Cond = C->getCond())
4187 Cond->printPretty(OS, Helper, Policy);
4191 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
4193 if (Stmt *T = I->getTarget())
4194 T->printPretty(OS, Helper, Policy);
4197 void VisitBinaryOperator(BinaryOperator* B) {
4198 if (!B->isLogicalOp()) {
4204 B->getLHS()->printPretty(OS, Helper, Policy);
4206 switch (B->getOpcode()) {
4214 llvm_unreachable("Invalid logical operator.");
4218 void VisitExpr(Expr *E) {
4219 E->printPretty(OS, Helper, Policy);
4223 void print(CFGTerminator T) {
4224 if (T.isTemporaryDtorsBranch())
4225 OS << "(Temp Dtor) ";
4229 } // end anonymous namespace
4231 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
4232 const CFGElement &E) {
4233 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4234 const Stmt *S = CS->getStmt();
4235 assert(S != nullptr && "Expecting non-null Stmt");
4237 // special printing for statement-expressions.
4238 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4239 const CompoundStmt *Sub = SE->getSubStmt();
4241 auto Children = Sub->children();
4242 if (Children.begin() != Children.end()) {
4244 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4249 // special printing for comma expressions.
4250 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4251 if (B->getOpcode() == BO_Comma) {
4253 Helper.handledStmt(B->getRHS(),OS);
4258 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4260 if (isa<CXXOperatorCallExpr>(S)) {
4261 OS << " (OperatorCall)";
4263 else if (isa<CXXBindTemporaryExpr>(S)) {
4264 OS << " (BindTemporary)";
4266 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4267 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4269 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4270 OS << " (" << CE->getStmtClassName() << ", "
4271 << CE->getCastKindName()
4272 << ", " << CE->getType().getAsString()
4276 // Expressions need a newline.
4280 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4281 const CXXCtorInitializer *I = IE->getInitializer();
4282 if (I->isBaseInitializer())
4283 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4284 else if (I->isDelegatingInitializer())
4285 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4286 else OS << I->getAnyMember()->getName();
4289 if (Expr *IE = I->getInit())
4290 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4293 if (I->isBaseInitializer())
4294 OS << " (Base initializer)\n";
4295 else if (I->isDelegatingInitializer())
4296 OS << " (Delegating initializer)\n";
4297 else OS << " (Member initializer)\n";
4299 } else if (Optional<CFGAutomaticObjDtor> DE =
4300 E.getAs<CFGAutomaticObjDtor>()) {
4301 const VarDecl *VD = DE->getVarDecl();
4302 Helper.handleDecl(VD, OS);
4304 const Type* T = VD->getType().getTypePtr();
4305 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4306 T = RT->getPointeeType().getTypePtr();
4307 T = T->getBaseElementTypeUnsafe();
4309 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4310 OS << " (Implicit destructor)\n";
4312 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4313 OS << "CFGNewAllocator(";
4314 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4315 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4317 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4318 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4321 CXXDeleteExpr *DelExpr =
4322 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
4323 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
4324 OS << "->~" << RD->getName().str() << "()";
4325 OS << " (Implicit destructor)\n";
4326 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4327 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
4328 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
4329 OS << " (Base object destructor)\n";
4331 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4332 const FieldDecl *FD = ME->getFieldDecl();
4333 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
4334 OS << "this->" << FD->getName();
4335 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
4336 OS << " (Member object destructor)\n";
4338 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4339 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
4341 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4342 OS << "() (Temporary object destructor)\n";
4346 static void print_block(raw_ostream &OS, const CFG* cfg,
4348 StmtPrinterHelper &Helper, bool print_edges,
4351 Helper.setBlockID(B.getBlockID());
4353 // Print the header.
4355 OS.changeColor(raw_ostream::YELLOW, true);
4357 OS << "\n [B" << B.getBlockID();
4359 if (&B == &cfg->getEntry())
4360 OS << " (ENTRY)]\n";
4361 else if (&B == &cfg->getExit())
4363 else if (&B == cfg->getIndirectGotoBlock())
4364 OS << " (INDIRECT GOTO DISPATCH)]\n";
4365 else if (B.hasNoReturnElement())
4366 OS << " (NORETURN)]\n";
4373 // Print the label of this block.
4374 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
4379 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
4381 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
4384 C->getLHS()->printPretty(OS, &Helper,
4385 PrintingPolicy(Helper.getLangOpts()));
4388 C->getRHS()->printPretty(OS, &Helper,
4389 PrintingPolicy(Helper.getLangOpts()));
4391 } else if (isa<DefaultStmt>(Label))
4393 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
4395 if (CS->getExceptionDecl())
4396 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
4403 llvm_unreachable("Invalid label statement in CFGBlock.");
4408 // Iterate through the statements in the block and print them.
4411 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4412 I != E ; ++I, ++j ) {
4414 // Print the statement # in the basic block and the statement itself.
4418 OS << llvm::format("%3d", j) << ": ";
4420 Helper.setStmtID(j);
4422 print_elem(OS, Helper, *I);
4425 // Print the terminator of this block.
4426 if (B.getTerminator()) {
4428 OS.changeColor(raw_ostream::GREEN);
4432 Helper.setBlockID(-1);
4434 PrintingPolicy PP(Helper.getLangOpts());
4435 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
4436 TPrinter.print(B.getTerminator());
4444 // Print the predecessors of this block.
4445 if (!B.pred_empty()) {
4446 const raw_ostream::Colors Color = raw_ostream::BLUE;
4448 OS.changeColor(Color);
4452 OS << '(' << B.pred_size() << "):";
4456 OS.changeColor(Color);
4458 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4465 bool Reachable = true;
4468 B = I->getPossiblyUnreachableBlock();
4471 OS << " B" << B->getBlockID();
4473 OS << "(Unreachable)";
4482 // Print the successors of this block.
4483 if (!B.succ_empty()) {
4484 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4486 OS.changeColor(Color);
4490 OS << '(' << B.succ_size() << "):";
4494 OS.changeColor(Color);
4496 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4504 bool Reachable = true;
4507 B = I->getPossiblyUnreachableBlock();
4511 OS << " B" << B->getBlockID();
4513 OS << "(Unreachable)";
4528 /// dump - A simple pretty printer of a CFG that outputs to stderr.
4529 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4530 print(llvm::errs(), LO, ShowColors);
4533 /// print - A simple pretty printer of a CFG that outputs to an ostream.
4534 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
4535 StmtPrinterHelper Helper(this, LO);
4537 // Print the entry block.
4538 print_block(OS, this, getEntry(), Helper, true, ShowColors);
4540 // Iterate through the CFGBlocks and print them one by one.
4541 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4542 // Skip the entry block, because we already printed it.
4543 if (&(**I) == &getEntry() || &(**I) == &getExit())
4546 print_block(OS, this, **I, Helper, true, ShowColors);
4549 // Print the exit block.
4550 print_block(OS, this, getExit(), Helper, true, ShowColors);
4555 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4556 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4557 bool ShowColors) const {
4558 print(llvm::errs(), cfg, LO, ShowColors);
4561 LLVM_DUMP_METHOD void CFGBlock::dump() const {
4562 dump(getParent(), LangOptions(), false);
4565 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4566 /// Generally this will only be called from CFG::print.
4567 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4568 const LangOptions &LO, bool ShowColors) const {
4569 StmtPrinterHelper Helper(cfg, LO);
4570 print_block(OS, cfg, *this, Helper, true, ShowColors);
4574 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4575 void CFGBlock::printTerminator(raw_ostream &OS,
4576 const LangOptions &LO) const {
4577 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
4578 TPrinter.print(getTerminator());
4581 Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
4582 Stmt *Terminator = this->Terminator;
4588 switch (Terminator->getStmtClass()) {
4592 case Stmt::CXXForRangeStmtClass:
4593 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4596 case Stmt::ForStmtClass:
4597 E = cast<ForStmt>(Terminator)->getCond();
4600 case Stmt::WhileStmtClass:
4601 E = cast<WhileStmt>(Terminator)->getCond();
4604 case Stmt::DoStmtClass:
4605 E = cast<DoStmt>(Terminator)->getCond();
4608 case Stmt::IfStmtClass:
4609 E = cast<IfStmt>(Terminator)->getCond();
4612 case Stmt::ChooseExprClass:
4613 E = cast<ChooseExpr>(Terminator)->getCond();
4616 case Stmt::IndirectGotoStmtClass:
4617 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4620 case Stmt::SwitchStmtClass:
4621 E = cast<SwitchStmt>(Terminator)->getCond();
4624 case Stmt::BinaryConditionalOperatorClass:
4625 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4628 case Stmt::ConditionalOperatorClass:
4629 E = cast<ConditionalOperator>(Terminator)->getCond();
4632 case Stmt::BinaryOperatorClass: // '&&' and '||'
4633 E = cast<BinaryOperator>(Terminator)->getLHS();
4636 case Stmt::ObjCForCollectionStmtClass:
4643 return E ? E->IgnoreParens() : nullptr;
4646 //===----------------------------------------------------------------------===//
4647 // CFG Graphviz Visualization
4648 //===----------------------------------------------------------------------===//
4652 static StmtPrinterHelper* GraphHelper;
4655 void CFG::viewCFG(const LangOptions &LO) const {
4657 StmtPrinterHelper H(this, LO);
4659 llvm::ViewGraph(this,"CFG");
4660 GraphHelper = nullptr;
4666 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4668 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4670 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4673 std::string OutSStr;
4674 llvm::raw_string_ostream Out(OutSStr);
4675 print_block(Out,Graph, *Node, *GraphHelper, false, false);
4676 std::string& OutStr = Out.str();
4678 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4680 // Process string output to make it nicer...
4681 for (unsigned i = 0; i != OutStr.length(); ++i)
4682 if (OutStr[i] == '\n') { // Left justify
4684 OutStr.insert(OutStr.begin()+i+1, 'l');
4693 } // end namespace llvm