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"
24 #include "llvm/ADT/OwningPtr.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();
44 /// The CFG builder uses a recursive algorithm to build the CFG. When
45 /// we process an expression, sometimes we know that we must add the
46 /// subexpressions as block-level expressions. For example:
50 /// When processing the '||' expression, we know that exp1 and exp2
51 /// need to be added as block-level expressions, even though they
52 /// might not normally need to be. AddStmtChoice records this
53 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
54 /// the builder has an option not to add a subexpression as a
55 /// block-level expression.
59 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
61 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
63 bool alwaysAdd(CFGBuilder &builder,
64 const Stmt *stmt) const;
66 /// Return a copy of this object, except with the 'always-add' bit
68 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
69 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
76 /// LocalScope - Node in tree of local scopes created for C++ implicit
77 /// destructor calls generation. It contains list of automatic variables
78 /// declared in the scope and link to position in previous scope this scope
81 /// The process of creating local scopes is as follows:
82 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
83 /// - Before processing statements in scope (e.g. CompoundStmt) create
84 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope
85 /// and set CFGBuilder::ScopePos to the end of new scope,
86 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
88 /// - For every normal (without jump) end of scope add to CFGBlock destructors
89 /// for objects in the current scope,
90 /// - For every jump add to CFGBlock destructors for objects
91 /// between CFGBuilder::ScopePos and local scope position saved for jump
92 /// target. Thanks to C++ restrictions on goto jumps we can be sure that
93 /// jump target position will be on the path to root from CFGBuilder::ScopePos
94 /// (adding any variable that doesn't need constructor to be called to
95 /// LocalScope can break this assumption),
99 typedef BumpVector<VarDecl*> AutomaticVarsTy;
101 /// const_iterator - Iterates local scope backwards and jumps to previous
102 /// scope on reaching the beginning of currently iterated scope.
103 class const_iterator {
104 const LocalScope* Scope;
106 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107 /// Invalid iterator (with null Scope) has VarIter equal to 0.
111 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112 /// Incrementing invalid iterator is allowed and will result in invalid
115 : Scope(NULL), VarIter(0) {}
117 /// Create valid iterator. In case when S.Prev is an invalid iterator and
118 /// I is equal to 0, this will create invalid iterator.
119 const_iterator(const LocalScope& S, unsigned I)
120 : Scope(&S), VarIter(I) {
121 // Iterator to "end" of scope is not allowed. Handle it by going up
122 // in scopes tree possibly up to invalid iterator in the root.
123 if (VarIter == 0 && Scope)
127 VarDecl *const* operator->() const {
128 assert (Scope && "Dereferencing invalid iterator is not allowed");
129 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
130 return &Scope->Vars[VarIter - 1];
132 VarDecl *operator*() const {
133 return *this->operator->();
136 const_iterator &operator++() {
140 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
146 const_iterator operator++(int) {
147 const_iterator P = *this;
152 bool operator==(const const_iterator &rhs) const {
153 return Scope == rhs.Scope && VarIter == rhs.VarIter;
155 bool operator!=(const const_iterator &rhs) const {
156 return !(*this == rhs);
159 LLVM_EXPLICIT operator bool() const {
160 return *this != const_iterator();
163 int distance(const_iterator L);
166 friend class const_iterator;
169 BumpVectorContext ctx;
171 /// Automatic variables in order of declaration.
172 AutomaticVarsTy Vars;
173 /// Iterator to variable in previous scope that was declared just before
174 /// begin of this scope.
178 /// Constructs empty scope linked to previous scope in specified place.
179 LocalScope(BumpVectorContext &ctx, const_iterator P)
180 : ctx(ctx), Vars(ctx, 4), Prev(P) {}
182 /// Begin of scope in direction of CFG building (backwards).
183 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
185 void addVar(VarDecl *VD) {
186 Vars.push_back(VD, ctx);
190 /// distance - Calculates distance from this to L. L must be reachable from this
191 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
192 /// number of scopes between this and L.
193 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
195 const_iterator F = *this;
196 while (F.Scope != L.Scope) {
197 assert (F != const_iterator()
198 && "L iterator is not reachable from F iterator.");
202 D += F.VarIter - L.VarIter;
206 /// BlockScopePosPair - Structure for specifying position in CFG during its
207 /// build process. It consists of CFGBlock that specifies position in CFG graph
208 /// and LocalScope::const_iterator that specifies position in LocalScope graph.
209 struct BlockScopePosPair {
210 BlockScopePosPair() : block(0) {}
211 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
212 : block(b), scopePosition(scopePos) {}
215 LocalScope::const_iterator scopePosition;
218 /// TryResult - a class representing a variant over the values
219 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
220 /// and is used by the CFGBuilder to decide if a branch condition
221 /// can be decided up front during CFG construction.
225 TryResult(bool b) : X(b ? 1 : 0) {}
226 TryResult() : X(-1) {}
228 bool isTrue() const { return X == 1; }
229 bool isFalse() const { return X == 0; }
230 bool isKnown() const { return X >= 0; }
237 class reverse_children {
238 llvm::SmallVector<Stmt *, 12> childrenBuf;
239 ArrayRef<Stmt*> children;
241 reverse_children(Stmt *S);
243 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
244 iterator begin() const { return children.rbegin(); }
245 iterator end() const { return children.rend(); }
249 reverse_children::reverse_children(Stmt *S) {
250 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
251 children = CE->getRawSubExprs();
254 switch (S->getStmtClass()) {
255 // Note: Fill in this switch with more cases we want to optimize.
256 case Stmt::InitListExprClass: {
257 InitListExpr *IE = cast<InitListExpr>(S);
258 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
266 // Default case for all other statements.
267 for (Stmt::child_range I = S->children(); I; ++I) {
268 childrenBuf.push_back(*I);
271 // This needs to be done *after* childrenBuf has been populated.
272 children = childrenBuf;
275 /// CFGBuilder - This class implements CFG construction from an AST.
276 /// The builder is stateful: an instance of the builder should be used to only
277 /// construct a single CFG.
281 /// CFGBuilder builder;
282 /// CFG* cfg = builder.BuildAST(stmt1);
284 /// CFG construction is done via a recursive walk of an AST. We actually parse
285 /// the AST in reverse order so that the successor of a basic block is
286 /// constructed prior to its predecessor. This allows us to nicely capture
287 /// implicit fall-throughs without extra basic blocks.
290 typedef BlockScopePosPair JumpTarget;
291 typedef BlockScopePosPair JumpSource;
298 JumpTarget ContinueJumpTarget;
299 JumpTarget BreakJumpTarget;
300 CFGBlock *SwitchTerminatedBlock;
301 CFGBlock *DefaultCaseBlock;
302 CFGBlock *TryTerminatedBlock;
304 // Current position in local scope.
305 LocalScope::const_iterator ScopePos;
307 // LabelMap records the mapping from Label expressions to their jump targets.
308 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
311 // A list of blocks that end with a "goto" that must be backpatched to their
312 // resolved targets upon completion of CFG construction.
313 typedef std::vector<JumpSource> BackpatchBlocksTy;
314 BackpatchBlocksTy BackpatchBlocks;
316 // A list of labels whose address has been taken (for indirect gotos).
317 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
318 LabelSetTy AddressTakenLabels;
321 const CFG::BuildOptions &BuildOpts;
323 // State to track for building switch statements.
324 bool switchExclusivelyCovered;
325 Expr::EvalResult *switchCond;
327 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
328 const Stmt *lastLookup;
330 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
331 // during construction of branches for chained logical operators.
332 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
333 CachedBoolEvalsTy CachedBoolEvals;
336 explicit CFGBuilder(ASTContext *astContext,
337 const CFG::BuildOptions &buildOpts)
338 : Context(astContext), cfg(new CFG()), // crew a new CFG
339 Block(NULL), Succ(NULL),
340 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
341 TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts),
342 switchExclusivelyCovered(false), switchCond(0),
343 cachedEntry(0), lastLookup(0) {}
345 // buildCFG - Used by external clients to construct the CFG.
346 CFG* buildCFG(const Decl *D, Stmt *Statement);
348 bool alwaysAdd(const Stmt *stmt);
351 // Visitors to walk an AST and construct the CFG.
352 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
353 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
354 CFGBlock *VisitBreakStmt(BreakStmt *B);
355 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
356 CFGBlock *VisitCaseStmt(CaseStmt *C);
357 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
358 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
359 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
361 CFGBlock *VisitContinueStmt(ContinueStmt *C);
362 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
364 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
365 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
366 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
367 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
368 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
370 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
372 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
373 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
374 CFGBlock *VisitDeclStmt(DeclStmt *DS);
375 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
376 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
377 CFGBlock *VisitDoStmt(DoStmt *D);
378 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
379 CFGBlock *VisitForStmt(ForStmt *F);
380 CFGBlock *VisitGotoStmt(GotoStmt *G);
381 CFGBlock *VisitIfStmt(IfStmt *I);
382 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
383 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
384 CFGBlock *VisitLabelStmt(LabelStmt *L);
385 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
386 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
387 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
390 CFGBlock *FalseBlock);
391 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
392 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
393 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
394 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
395 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
396 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
397 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
398 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
399 CFGBlock *VisitReturnStmt(ReturnStmt *R);
400 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
401 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
402 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
404 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
405 CFGBlock *VisitWhileStmt(WhileStmt *W);
407 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
408 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
409 CFGBlock *VisitChildren(Stmt *S);
410 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
412 // Visitors to walk an AST and generate destructors of temporaries in
414 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false);
415 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E);
416 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E);
417 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E,
418 bool BindToTemporary);
420 VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E,
421 bool BindToTemporary);
423 // NYS == Not Yet Supported
429 void autoCreateBlock() { if (!Block) Block = createBlock(); }
430 CFGBlock *createBlock(bool add_successor = true);
431 CFGBlock *createNoReturnBlock();
433 CFGBlock *addStmt(Stmt *S) {
434 return Visit(S, AddStmtChoice::AlwaysAdd);
436 CFGBlock *addInitializer(CXXCtorInitializer *I);
437 void addAutomaticObjDtors(LocalScope::const_iterator B,
438 LocalScope::const_iterator E, Stmt *S);
439 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
441 // Local scopes creation.
442 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
444 void addLocalScopeForStmt(Stmt *S);
445 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL);
446 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL);
448 void addLocalScopeAndDtors(Stmt *S);
450 // Interface to CFGBlock - adding CFGElements.
451 void appendStmt(CFGBlock *B, const Stmt *S) {
452 if (alwaysAdd(S) && cachedEntry)
453 cachedEntry->second = B;
455 // All block-level expressions should have already been IgnoreParens()ed.
456 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
457 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
459 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
460 B->appendInitializer(I, cfg->getBumpVectorContext());
462 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
463 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
465 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
466 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
468 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
469 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
471 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
472 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
475 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
476 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
479 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
480 LocalScope::const_iterator B, LocalScope::const_iterator E);
482 void addSuccessor(CFGBlock *B, CFGBlock *S) {
483 B->addSuccessor(S, cfg->getBumpVectorContext());
486 /// Try and evaluate an expression to an integer constant.
487 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
488 if (!BuildOpts.PruneTriviallyFalseEdges)
490 return !S->isTypeDependent() &&
491 !S->isValueDependent() &&
492 S->EvaluateAsRValue(outResult, *Context);
495 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
496 /// if we can evaluate to a known value, otherwise return -1.
497 TryResult tryEvaluateBool(Expr *S) {
498 if (!BuildOpts.PruneTriviallyFalseEdges ||
499 S->isTypeDependent() || S->isValueDependent())
502 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
503 if (Bop->isLogicalOp()) {
504 // Check the cache first.
505 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
506 if (I != CachedBoolEvals.end())
507 return I->second; // already in map;
509 // Retrieve result at first, or the map might be updated.
510 TryResult Result = evaluateAsBooleanConditionNoCache(S);
511 CachedBoolEvals[S] = Result; // update or insert
515 switch (Bop->getOpcode()) {
517 // For 'x & 0' and 'x * 0', we can determine that
518 // the value is always false.
521 // If either operand is zero, we know the value
524 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
525 if (IntVal.getBoolValue() == false) {
526 return TryResult(false);
529 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
530 if (IntVal.getBoolValue() == false) {
531 return TryResult(false);
540 return evaluateAsBooleanConditionNoCache(S);
543 /// \brief Evaluate as boolean \param E without using the cache.
544 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
545 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
546 if (Bop->isLogicalOp()) {
547 TryResult LHS = tryEvaluateBool(Bop->getLHS());
549 // We were able to evaluate the LHS, see if we can get away with not
550 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
551 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
554 TryResult RHS = tryEvaluateBool(Bop->getRHS());
556 if (Bop->getOpcode() == BO_LOr)
557 return LHS.isTrue() || RHS.isTrue();
559 return LHS.isTrue() && RHS.isTrue();
562 TryResult RHS = tryEvaluateBool(Bop->getRHS());
564 // We can't evaluate the LHS; however, sometimes the result
565 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
566 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
576 if (E->EvaluateAsBooleanCondition(Result, *Context))
584 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
585 const Stmt *stmt) const {
586 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
589 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
590 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
592 if (!BuildOpts.forcedBlkExprs)
595 if (lastLookup == stmt) {
597 assert(cachedEntry->first == stmt);
605 // Perform the lookup!
606 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
609 // No need to update 'cachedEntry', since it will always be null.
610 assert(cachedEntry == 0);
614 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
615 if (itr == fb->end()) {
624 // FIXME: Add support for dependent-sized array types in C++?
625 // Does it even make sense to build a CFG for an uninstantiated template?
626 static const VariableArrayType *FindVA(const Type *t) {
627 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
628 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
629 if (vat->getSizeExpr())
632 t = vt->getElementType().getTypePtr();
638 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
639 /// arbitrary statement. Examples include a single expression or a function
640 /// body (compound statement). The ownership of the returned CFG is
641 /// transferred to the caller. If CFG construction fails, this method returns
643 CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
648 // Create an empty block that will serve as the exit block for the CFG. Since
649 // this is the first block added to the CFG, it will be implicitly registered
650 // as the exit block.
651 Succ = createBlock();
652 assert(Succ == &cfg->getExit());
653 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
655 if (BuildOpts.AddImplicitDtors)
656 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
657 addImplicitDtorsForDestructor(DD);
659 // Visit the statements and create the CFG.
660 CFGBlock *B = addStmt(Statement);
665 // For C++ constructor add initializers to CFG.
666 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
667 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
668 E = CD->init_rend(); I != E; ++I) {
669 B = addInitializer(*I);
678 // Backpatch the gotos whose label -> block mappings we didn't know when we
680 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
681 E = BackpatchBlocks.end(); I != E; ++I ) {
683 CFGBlock *B = I->block;
684 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
685 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
687 // If there is no target for the goto, then we are looking at an
688 // incomplete AST. Handle this by not registering a successor.
689 if (LI == LabelMap.end()) continue;
691 JumpTarget JT = LI->second;
692 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
694 addSuccessor(B, JT.block);
697 // Add successors to the Indirect Goto Dispatch block (if we have one).
698 if (CFGBlock *B = cfg->getIndirectGotoBlock())
699 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
700 E = AddressTakenLabels.end(); I != E; ++I ) {
702 // Lookup the target block.
703 LabelMapTy::iterator LI = LabelMap.find(*I);
705 // If there is no target block that contains label, then we are looking
706 // at an incomplete AST. Handle this by not registering a successor.
707 if (LI == LabelMap.end()) continue;
709 addSuccessor(B, LI->second.block);
712 // Create an empty entry block that has no predecessors.
713 cfg->setEntry(createBlock());
718 /// createBlock - Used to lazily create blocks that are connected
719 /// to the current (global) succcessor.
720 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
721 CFGBlock *B = cfg->createBlock();
722 if (add_successor && Succ)
723 addSuccessor(B, Succ);
727 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
728 /// CFG. It is *not* connected to the current (global) successor, and instead
729 /// directly tied to the exit block in order to be reachable.
730 CFGBlock *CFGBuilder::createNoReturnBlock() {
731 CFGBlock *B = createBlock(false);
732 B->setHasNoReturnElement();
733 addSuccessor(B, &cfg->getExit());
737 /// addInitializer - Add C++ base or member initializer element to CFG.
738 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
739 if (!BuildOpts.AddInitializers)
742 bool IsReference = false;
743 bool HasTemporaries = false;
745 // Destructors of temporaries in initialization expression should be called
746 // after initialization finishes.
747 Expr *Init = I->getInit();
749 if (FieldDecl *FD = I->getAnyMember())
750 IsReference = FD->getType()->isReferenceType();
751 HasTemporaries = isa<ExprWithCleanups>(Init);
753 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
754 // Generate destructors for temporaries in initialization expression.
755 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
761 appendInitializer(Block, I);
764 if (HasTemporaries) {
765 // For expression with temporaries go directly to subexpression to omit
766 // generating destructors for the second time.
767 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
775 /// \brief Retrieve the type of the temporary object whose lifetime was
776 /// extended by a local reference with the given initializer.
777 static QualType getReferenceInitTemporaryType(ASTContext &Context,
781 Init = Init->IgnoreParens();
783 // Skip through cleanups.
784 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
785 Init = EWC->getSubExpr();
789 // Skip through the temporary-materialization expression.
790 if (const MaterializeTemporaryExpr *MTE
791 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
792 Init = MTE->GetTemporaryExpr();
796 // Skip derived-to-base and no-op casts.
797 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
798 if ((CE->getCastKind() == CK_DerivedToBase ||
799 CE->getCastKind() == CK_UncheckedDerivedToBase ||
800 CE->getCastKind() == CK_NoOp) &&
801 Init->getType()->isRecordType()) {
802 Init = CE->getSubExpr();
807 // Skip member accesses into rvalues.
808 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
809 if (!ME->isArrow() && ME->getBase()->isRValue()) {
810 Init = ME->getBase();
818 return Init->getType();
821 /// addAutomaticObjDtors - Add to current block automatic objects destructors
822 /// for objects in range of local scope positions. Use S as trigger statement
824 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
825 LocalScope::const_iterator E, Stmt *S) {
826 if (!BuildOpts.AddImplicitDtors)
832 // We need to append the destructors in reverse order, but any one of them
833 // may be a no-return destructor which changes the CFG. As a result, buffer
834 // this sequence up and replay them in reverse order when appending onto the
836 SmallVector<VarDecl*, 10> Decls;
837 Decls.reserve(B.distance(E));
838 for (LocalScope::const_iterator I = B; I != E; ++I)
841 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
844 // If this destructor is marked as a no-return destructor, we need to
845 // create a new block for the destructor which does not have as a successor
846 // anything built thus far: control won't flow out of this block.
847 QualType Ty = (*I)->getType();
848 if (Ty->isReferenceType()) {
849 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
851 Ty = Context->getBaseElementType(Ty);
853 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
854 if (Dtor->isNoReturn())
855 Block = createNoReturnBlock();
859 appendAutomaticObjDtor(Block, *I, S);
863 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
864 /// base and member objects in destructor.
865 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
866 assert (BuildOpts.AddImplicitDtors
867 && "Can be called only when dtors should be added");
868 const CXXRecordDecl *RD = DD->getParent();
870 // At the end destroy virtual base objects.
871 for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
872 VE = RD->vbases_end(); VI != VE; ++VI) {
873 const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
874 if (!CD->hasTrivialDestructor()) {
876 appendBaseDtor(Block, VI);
880 // Before virtual bases destroy direct base objects.
881 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
882 BE = RD->bases_end(); BI != BE; ++BI) {
883 if (!BI->isVirtual()) {
884 const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
885 if (!CD->hasTrivialDestructor()) {
887 appendBaseDtor(Block, BI);
892 // First destroy member objects.
893 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
894 FE = RD->field_end(); FI != FE; ++FI) {
895 // Check for constant size array. Set type to array element type.
896 QualType QT = FI->getType();
897 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
898 if (AT->getSize() == 0)
900 QT = AT->getElementType();
903 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
904 if (!CD->hasTrivialDestructor()) {
906 appendMemberDtor(Block, *FI);
911 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
912 /// way return valid LocalScope object.
913 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
915 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
916 Scope = alloc.Allocate<LocalScope>();
917 BumpVectorContext ctx(alloc);
918 new (Scope) LocalScope(ctx, ScopePos);
923 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
924 /// that should create implicit scope (e.g. if/else substatements).
925 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
926 if (!BuildOpts.AddImplicitDtors)
929 LocalScope *Scope = 0;
931 // For compound statement we will be creating explicit scope.
932 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
933 for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
935 Stmt *SI = (*BI)->stripLabelLikeStatements();
936 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
937 Scope = addLocalScopeForDeclStmt(DS, Scope);
942 // For any other statement scope will be implicit and as such will be
943 // interesting only for DeclStmt.
944 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
945 addLocalScopeForDeclStmt(DS);
948 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
949 /// reuse Scope if not NULL.
950 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
952 if (!BuildOpts.AddImplicitDtors)
955 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
957 if (VarDecl *VD = dyn_cast<VarDecl>(*DI))
958 Scope = addLocalScopeForVarDecl(VD, Scope);
963 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
964 /// create add scope for automatic objects and temporary objects bound to
965 /// const reference. Will reuse Scope if not NULL.
966 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
968 if (!BuildOpts.AddImplicitDtors)
971 // Check if variable is local.
972 switch (VD->getStorageClass()) {
977 default: return Scope;
980 // Check for const references bound to temporary. Set type to pointee.
981 QualType QT = VD->getType();
982 if (QT.getTypePtr()->isReferenceType()) {
983 // Attempt to determine whether this declaration lifetime-extends a
986 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
987 // temporaries, and a single declaration can extend multiple temporaries.
988 // We should look at the storage duration on each nested
989 // MaterializeTemporaryExpr instead.
990 const Expr *Init = VD->getInit();
993 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
994 Init = EWC->getSubExpr();
995 if (!isa<MaterializeTemporaryExpr>(Init))
998 // Lifetime-extending a temporary.
999 QT = getReferenceInitTemporaryType(*Context, Init);
1002 // Check for constant size array. Set type to array element type.
1003 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1004 if (AT->getSize() == 0)
1006 QT = AT->getElementType();
1009 // Check if type is a C++ class with non-trivial destructor.
1010 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1011 if (!CD->hasTrivialDestructor()) {
1012 // Add the variable to scope
1013 Scope = createOrReuseLocalScope(Scope);
1015 ScopePos = Scope->begin();
1020 /// addLocalScopeAndDtors - For given statement add local scope for it and
1021 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1022 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1023 if (!BuildOpts.AddImplicitDtors)
1026 LocalScope::const_iterator scopeBeginPos = ScopePos;
1027 addLocalScopeForStmt(S);
1028 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1031 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1032 /// variables with automatic storage duration to CFGBlock's elements vector.
1033 /// Elements will be prepended to physical beginning of the vector which
1034 /// happens to be logical end. Use blocks terminator as statement that specifies
1035 /// destructors call site.
1036 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1037 /// no-return destructors properly.
1038 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1039 LocalScope::const_iterator B, LocalScope::const_iterator E) {
1040 BumpVectorContext &C = cfg->getBumpVectorContext();
1041 CFGBlock::iterator InsertPos
1042 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1043 for (LocalScope::const_iterator I = B; I != E; ++I)
1044 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1045 Blk->getTerminator());
1048 /// Visit - Walk the subtree of a statement and add extra
1049 /// blocks for ternary operators, &&, and ||. We also process "," and
1050 /// DeclStmts (which may contain nested control-flow).
1051 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1057 if (Expr *E = dyn_cast<Expr>(S))
1058 S = E->IgnoreParens();
1060 switch (S->getStmtClass()) {
1062 return VisitStmt(S, asc);
1064 case Stmt::AddrLabelExprClass:
1065 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1067 case Stmt::BinaryConditionalOperatorClass:
1068 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1070 case Stmt::BinaryOperatorClass:
1071 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1073 case Stmt::BlockExprClass:
1074 return VisitNoRecurse(cast<Expr>(S), asc);
1076 case Stmt::BreakStmtClass:
1077 return VisitBreakStmt(cast<BreakStmt>(S));
1079 case Stmt::CallExprClass:
1080 case Stmt::CXXOperatorCallExprClass:
1081 case Stmt::CXXMemberCallExprClass:
1082 case Stmt::UserDefinedLiteralClass:
1083 return VisitCallExpr(cast<CallExpr>(S), asc);
1085 case Stmt::CaseStmtClass:
1086 return VisitCaseStmt(cast<CaseStmt>(S));
1088 case Stmt::ChooseExprClass:
1089 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1091 case Stmt::CompoundStmtClass:
1092 return VisitCompoundStmt(cast<CompoundStmt>(S));
1094 case Stmt::ConditionalOperatorClass:
1095 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1097 case Stmt::ContinueStmtClass:
1098 return VisitContinueStmt(cast<ContinueStmt>(S));
1100 case Stmt::CXXCatchStmtClass:
1101 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1103 case Stmt::ExprWithCleanupsClass:
1104 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1106 case Stmt::CXXDefaultArgExprClass:
1107 case Stmt::CXXDefaultInitExprClass:
1108 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1109 // called function's declaration, not by the caller. If we simply add
1110 // this expression to the CFG, we could end up with the same Expr
1111 // appearing multiple times.
1112 // PR13385 / <rdar://problem/12156507>
1114 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1115 // expression to be used in the same function (through aggregate
1117 return VisitStmt(S, asc);
1119 case Stmt::CXXBindTemporaryExprClass:
1120 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1122 case Stmt::CXXConstructExprClass:
1123 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1125 case Stmt::CXXDeleteExprClass:
1126 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1128 case Stmt::CXXFunctionalCastExprClass:
1129 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1131 case Stmt::CXXTemporaryObjectExprClass:
1132 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1134 case Stmt::CXXThrowExprClass:
1135 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1137 case Stmt::CXXTryStmtClass:
1138 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1140 case Stmt::CXXForRangeStmtClass:
1141 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1143 case Stmt::DeclStmtClass:
1144 return VisitDeclStmt(cast<DeclStmt>(S));
1146 case Stmt::DefaultStmtClass:
1147 return VisitDefaultStmt(cast<DefaultStmt>(S));
1149 case Stmt::DoStmtClass:
1150 return VisitDoStmt(cast<DoStmt>(S));
1152 case Stmt::ForStmtClass:
1153 return VisitForStmt(cast<ForStmt>(S));
1155 case Stmt::GotoStmtClass:
1156 return VisitGotoStmt(cast<GotoStmt>(S));
1158 case Stmt::IfStmtClass:
1159 return VisitIfStmt(cast<IfStmt>(S));
1161 case Stmt::ImplicitCastExprClass:
1162 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1164 case Stmt::IndirectGotoStmtClass:
1165 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1167 case Stmt::LabelStmtClass:
1168 return VisitLabelStmt(cast<LabelStmt>(S));
1170 case Stmt::LambdaExprClass:
1171 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1173 case Stmt::MemberExprClass:
1174 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1176 case Stmt::NullStmtClass:
1179 case Stmt::ObjCAtCatchStmtClass:
1180 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1182 case Stmt::ObjCAutoreleasePoolStmtClass:
1183 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1185 case Stmt::ObjCAtSynchronizedStmtClass:
1186 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1188 case Stmt::ObjCAtThrowStmtClass:
1189 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1191 case Stmt::ObjCAtTryStmtClass:
1192 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1194 case Stmt::ObjCForCollectionStmtClass:
1195 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1197 case Stmt::OpaqueValueExprClass:
1200 case Stmt::PseudoObjectExprClass:
1201 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1203 case Stmt::ReturnStmtClass:
1204 return VisitReturnStmt(cast<ReturnStmt>(S));
1206 case Stmt::UnaryExprOrTypeTraitExprClass:
1207 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1210 case Stmt::StmtExprClass:
1211 return VisitStmtExpr(cast<StmtExpr>(S), asc);
1213 case Stmt::SwitchStmtClass:
1214 return VisitSwitchStmt(cast<SwitchStmt>(S));
1216 case Stmt::UnaryOperatorClass:
1217 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1219 case Stmt::WhileStmtClass:
1220 return VisitWhileStmt(cast<WhileStmt>(S));
1224 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1225 if (asc.alwaysAdd(*this, S)) {
1227 appendStmt(Block, S);
1230 return VisitChildren(S);
1233 /// VisitChildren - Visit the children of a Stmt.
1234 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1235 CFGBlock *B = Block;
1237 // Visit the children in their reverse order so that they appear in
1238 // left-to-right (natural) order in the CFG.
1239 reverse_children RChildren(S);
1240 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1242 if (Stmt *Child = *I)
1243 if (CFGBlock *R = Visit(Child))
1249 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1250 AddStmtChoice asc) {
1251 AddressTakenLabels.insert(A->getLabel());
1253 if (asc.alwaysAdd(*this, A)) {
1255 appendStmt(Block, A);
1261 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1262 AddStmtChoice asc) {
1263 if (asc.alwaysAdd(*this, U)) {
1265 appendStmt(Block, U);
1268 return Visit(U->getSubExpr(), AddStmtChoice());
1271 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1272 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1273 appendStmt(ConfluenceBlock, B);
1278 return VisitLogicalOperator(B, 0, ConfluenceBlock, ConfluenceBlock).first;
1281 std::pair<CFGBlock*, CFGBlock*>
1282 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1284 CFGBlock *TrueBlock,
1285 CFGBlock *FalseBlock) {
1287 // Introspect the RHS. If it is a nested logical operation, we recursively
1288 // build the CFG using this function. Otherwise, resort to default
1289 // CFG construction behavior.
1290 Expr *RHS = B->getRHS()->IgnoreParens();
1291 CFGBlock *RHSBlock, *ExitBlock;
1294 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1295 if (B_RHS->isLogicalOp()) {
1296 llvm::tie(RHSBlock, ExitBlock) =
1297 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1301 // The RHS is not a nested logical operation. Don't push the terminator
1302 // down further, but instead visit RHS and construct the respective
1303 // pieces of the CFG, and link up the RHSBlock with the terminator
1304 // we have been provided.
1305 ExitBlock = RHSBlock = createBlock(false);
1308 assert(TrueBlock == FalseBlock);
1309 addSuccessor(RHSBlock, TrueBlock);
1312 RHSBlock->setTerminator(Term);
1313 TryResult KnownVal = tryEvaluateBool(RHS);
1314 addSuccessor(RHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1315 addSuccessor(RHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1319 RHSBlock = addStmt(RHS);
1324 return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1326 // Generate the blocks for evaluating the LHS.
1327 Expr *LHS = B->getLHS()->IgnoreParens();
1329 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1330 if (B_LHS->isLogicalOp()) {
1331 if (B->getOpcode() == BO_LOr)
1332 FalseBlock = RHSBlock;
1334 TrueBlock = RHSBlock;
1336 // For the LHS, treat 'B' as the terminator that we want to sink
1337 // into the nested branch. The RHS always gets the top-most
1339 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1342 // Create the block evaluating the LHS.
1343 // This contains the '&&' or '||' as the terminator.
1344 CFGBlock *LHSBlock = createBlock(false);
1345 LHSBlock->setTerminator(B);
1348 CFGBlock *EntryLHSBlock = addStmt(LHS);
1351 return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1353 // See if this is a known constant.
1354 TryResult KnownVal = tryEvaluateBool(LHS);
1356 // Now link the LHSBlock with RHSBlock.
1357 if (B->getOpcode() == BO_LOr) {
1358 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1359 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : RHSBlock);
1361 assert(B->getOpcode() == BO_LAnd);
1362 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
1363 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1366 return std::make_pair(EntryLHSBlock, ExitBlock);
1370 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1371 AddStmtChoice asc) {
1373 if (B->isLogicalOp())
1374 return VisitLogicalOperator(B);
1376 if (B->getOpcode() == BO_Comma) { // ,
1378 appendStmt(Block, B);
1379 addStmt(B->getRHS());
1380 return addStmt(B->getLHS());
1383 if (B->isAssignmentOp()) {
1384 if (asc.alwaysAdd(*this, B)) {
1386 appendStmt(Block, B);
1389 return Visit(B->getRHS());
1392 if (asc.alwaysAdd(*this, B)) {
1394 appendStmt(Block, B);
1397 CFGBlock *RBlock = Visit(B->getRHS());
1398 CFGBlock *LBlock = Visit(B->getLHS());
1399 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1400 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1401 // return RBlock. Otherwise we'll incorrectly return NULL.
1402 return (LBlock ? LBlock : RBlock);
1405 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1406 if (asc.alwaysAdd(*this, E)) {
1408 appendStmt(Block, E);
1413 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1414 // "break" is a control-flow statement. Thus we stop processing the current
1419 // Now create a new block that ends with the break statement.
1420 Block = createBlock(false);
1421 Block->setTerminator(B);
1423 // If there is no target for the break, then we are looking at an incomplete
1424 // AST. This means that the CFG cannot be constructed.
1425 if (BreakJumpTarget.block) {
1426 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1427 addSuccessor(Block, BreakJumpTarget.block);
1435 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1436 QualType Ty = E->getType();
1437 if (Ty->isFunctionPointerType())
1438 Ty = Ty->getAs<PointerType>()->getPointeeType();
1439 else if (Ty->isBlockPointerType())
1440 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1442 const FunctionType *FT = Ty->getAs<FunctionType>();
1444 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1445 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1446 Proto->isNothrow(Ctx))
1452 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1453 // Compute the callee type.
1454 QualType calleeType = C->getCallee()->getType();
1455 if (calleeType == Context->BoundMemberTy) {
1456 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1458 // We should only get a null bound type if processing a dependent
1459 // CFG. Recover by assuming nothing.
1460 if (!boundType.isNull()) calleeType = boundType;
1463 // If this is a call to a no-return function, this stops the block here.
1464 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1466 bool AddEHEdge = false;
1468 // Languages without exceptions are assumed to not throw.
1469 if (Context->getLangOpts().Exceptions) {
1470 if (BuildOpts.AddEHEdges)
1474 // If this is a call to a builtin function, it might not actually evaluate
1475 // its arguments. Don't add them to the CFG if this is the case.
1476 bool OmitArguments = false;
1478 if (FunctionDecl *FD = C->getDirectCallee()) {
1479 if (FD->isNoReturn())
1481 if (FD->hasAttr<NoThrowAttr>())
1483 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1484 OmitArguments = true;
1487 if (!CanThrow(C->getCallee(), *Context))
1490 if (OmitArguments) {
1491 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1492 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1494 appendStmt(Block, C);
1495 return Visit(C->getCallee());
1498 if (!NoReturn && !AddEHEdge) {
1499 return VisitStmt(C, asc.withAlwaysAdd(true));
1509 Block = createNoReturnBlock();
1511 Block = createBlock();
1513 appendStmt(Block, C);
1516 // Add exceptional edges.
1517 if (TryTerminatedBlock)
1518 addSuccessor(Block, TryTerminatedBlock);
1520 addSuccessor(Block, &cfg->getExit());
1523 return VisitChildren(C);
1526 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1527 AddStmtChoice asc) {
1528 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1529 appendStmt(ConfluenceBlock, C);
1533 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1534 Succ = ConfluenceBlock;
1536 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
1540 Succ = ConfluenceBlock;
1542 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
1546 Block = createBlock(false);
1547 // See if this is a known constant.
1548 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1549 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1550 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1551 Block->setTerminator(C);
1552 return addStmt(C->getCond());
1556 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
1557 addLocalScopeAndDtors(C);
1558 CFGBlock *LastBlock = Block;
1560 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1562 // If we hit a segment of code just containing ';' (NullStmts), we can
1563 // get a null block back. In such cases, just use the LastBlock
1564 if (CFGBlock *newBlock = addStmt(*I))
1565 LastBlock = newBlock;
1574 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1575 AddStmtChoice asc) {
1576 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1577 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL);
1579 // Create the confluence block that will "merge" the results of the ternary
1581 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1582 appendStmt(ConfluenceBlock, C);
1586 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1588 // Create a block for the LHS expression if there is an LHS expression. A
1589 // GCC extension allows LHS to be NULL, causing the condition to be the
1590 // value that is returned instead.
1591 // e.g: x ?: y is shorthand for: x ? x : y;
1592 Succ = ConfluenceBlock;
1594 CFGBlock *LHSBlock = 0;
1595 const Expr *trueExpr = C->getTrueExpr();
1596 if (trueExpr != opaqueValue) {
1597 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
1603 LHSBlock = ConfluenceBlock;
1605 // Create the block for the RHS expression.
1606 Succ = ConfluenceBlock;
1607 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
1611 // If the condition is a logical '&&' or '||', build a more accurate CFG.
1612 if (BinaryOperator *Cond =
1613 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1614 if (Cond->isLogicalOp())
1615 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1617 // Create the block that will contain the condition.
1618 Block = createBlock(false);
1620 // See if this is a known constant.
1621 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1622 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1623 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1624 Block->setTerminator(C);
1625 Expr *condExpr = C->getCond();
1628 // Run the condition expression if it's not trivially expressed in
1629 // terms of the opaque value (or if there is no opaque value).
1630 if (condExpr != opaqueValue)
1633 // Before that, run the common subexpression if there was one.
1634 // At least one of this or the above will be run.
1635 return addStmt(BCO->getCommon());
1638 return addStmt(condExpr);
1641 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1642 // Check if the Decl is for an __label__. If so, elide it from the
1644 if (isa<LabelDecl>(*DS->decl_begin()))
1647 // This case also handles static_asserts.
1648 if (DS->isSingleDecl())
1649 return VisitDeclSubExpr(DS);
1653 // Build an individual DeclStmt for each decl.
1654 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1655 E = DS->decl_rend();
1657 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1658 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1659 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1661 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
1662 // automatically freed with the CFG.
1663 DeclGroupRef DG(*I);
1665 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1666 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1667 cfg->addSyntheticDeclStmt(DSNew, DS);
1669 // Append the fake DeclStmt to block.
1670 B = VisitDeclSubExpr(DSNew);
1676 /// VisitDeclSubExpr - Utility method to add block-level expressions for
1677 /// DeclStmts and initializers in them.
1678 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
1679 assert(DS->isSingleDecl() && "Can handle single declarations only.");
1680 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1683 // Of everything that can be declared in a DeclStmt, only VarDecls impact
1684 // runtime semantics.
1688 bool IsReference = false;
1689 bool HasTemporaries = false;
1691 // Guard static initializers under a branch.
1692 CFGBlock *blockAfterStaticInit = 0;
1694 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
1695 // For static variables, we need to create a branch to track
1696 // whether or not they are initialized.
1703 blockAfterStaticInit = Succ;
1706 // Destructors of temporaries in initialization expression should be called
1707 // after initialization finishes.
1708 Expr *Init = VD->getInit();
1710 IsReference = VD->getType()->isReferenceType();
1711 HasTemporaries = isa<ExprWithCleanups>(Init);
1713 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1714 // Generate destructors for temporaries in initialization expression.
1715 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1721 appendStmt(Block, DS);
1723 // Keep track of the last non-null block, as 'Block' can be nulled out
1724 // if the initializer expression is something like a 'while' in a
1725 // statement-expression.
1726 CFGBlock *LastBlock = Block;
1729 if (HasTemporaries) {
1730 // For expression with temporaries go directly to subexpression to omit
1731 // generating destructors for the second time.
1732 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
1733 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
1734 LastBlock = newBlock;
1737 if (CFGBlock *newBlock = Visit(Init))
1738 LastBlock = newBlock;
1742 // If the type of VD is a VLA, then we must process its size expressions.
1743 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
1744 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) {
1745 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
1746 LastBlock = newBlock;
1749 // Remove variable from local scope.
1750 if (ScopePos && VD == *ScopePos)
1753 CFGBlock *B = LastBlock;
1754 if (blockAfterStaticInit) {
1756 Block = createBlock(false);
1757 Block->setTerminator(DS);
1758 addSuccessor(Block, blockAfterStaticInit);
1759 addSuccessor(Block, B);
1766 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
1767 // We may see an if statement in the middle of a basic block, or it may be the
1768 // first statement we are processing. In either case, we create a new basic
1769 // block. First, we create the blocks for the then...else statements, and
1770 // then we create the block containing the if statement. If we were in the
1771 // middle of a block, we stop processing that block. That block is then the
1772 // implicit successor for the "then" and "else" clauses.
1774 // Save local scope position because in case of condition variable ScopePos
1775 // won't be restored when traversing AST.
1776 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1778 // Create local scope for possible condition variable.
1779 // Store scope position. Add implicit destructor.
1780 if (VarDecl *VD = I->getConditionVariable()) {
1781 LocalScope::const_iterator BeginScopePos = ScopePos;
1782 addLocalScopeForVarDecl(VD);
1783 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1786 // The block we were processing is now finished. Make it the successor
1794 // Process the false branch.
1795 CFGBlock *ElseBlock = Succ;
1797 if (Stmt *Else = I->getElse()) {
1798 SaveAndRestore<CFGBlock*> sv(Succ);
1800 // NULL out Block so that the recursive call to Visit will
1801 // create a new basic block.
1804 // If branch is not a compound statement create implicit scope
1805 // and add destructors.
1806 if (!isa<CompoundStmt>(Else))
1807 addLocalScopeAndDtors(Else);
1809 ElseBlock = addStmt(Else);
1811 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1812 ElseBlock = sv.get();
1819 // Process the true branch.
1820 CFGBlock *ThenBlock;
1822 Stmt *Then = I->getThen();
1824 SaveAndRestore<CFGBlock*> sv(Succ);
1827 // If branch is not a compound statement create implicit scope
1828 // and add destructors.
1829 if (!isa<CompoundStmt>(Then))
1830 addLocalScopeAndDtors(Then);
1832 ThenBlock = addStmt(Then);
1835 // We can reach here if the "then" body has all NullStmts.
1836 // Create an empty block so we can distinguish between true and false
1837 // branches in path-sensitive analyses.
1838 ThenBlock = createBlock(false);
1839 addSuccessor(ThenBlock, sv.get());
1846 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
1847 // having these handle the actual control-flow jump. Note that
1848 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
1849 // we resort to the old control-flow behavior. This special handling
1850 // removes infeasible paths from the control-flow graph by having the
1851 // control-flow transfer of '&&' or '||' go directly into the then/else
1853 if (!I->getConditionVariable())
1854 if (BinaryOperator *Cond =
1855 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
1856 if (Cond->isLogicalOp())
1857 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
1859 // Now create a new block containing the if statement.
1860 Block = createBlock(false);
1862 // Set the terminator of the new block to the If statement.
1863 Block->setTerminator(I);
1865 // See if this is a known constant.
1866 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
1868 // Now add the successors.
1869 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1870 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1872 // Add the condition as the last statement in the new block. This may create
1873 // new blocks as the condition may contain control-flow. Any newly created
1874 // blocks will be pointed to be "Block".
1875 CFGBlock *LastBlock = addStmt(I->getCond());
1877 // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1878 // and the condition variable initialization to the CFG.
1879 if (VarDecl *VD = I->getConditionVariable()) {
1880 if (Expr *Init = VD->getInit()) {
1882 appendStmt(Block, I->getConditionVariableDeclStmt());
1883 LastBlock = addStmt(Init);
1891 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
1892 // If we were in the middle of a block we stop processing that block.
1894 // NOTE: If a "return" appears in the middle of a block, this means that the
1895 // code afterwards is DEAD (unreachable). We still keep a basic block
1896 // for that code; a simple "mark-and-sweep" from the entry block will be
1897 // able to report such dead blocks.
1899 // Create the new block.
1900 Block = createBlock(false);
1902 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1904 // If the one of the destructors does not return, we already have the Exit
1905 // block as a successor.
1906 if (!Block->hasNoReturnElement())
1907 addSuccessor(Block, &cfg->getExit());
1909 // Add the return statement to the block. This may create new blocks if R
1910 // contains control-flow (short-circuit operations).
1911 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1914 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
1915 // Get the block of the labeled statement. Add it to our map.
1916 addStmt(L->getSubStmt());
1917 CFGBlock *LabelBlock = Block;
1919 if (!LabelBlock) // This can happen when the body is empty, i.e.
1920 LabelBlock = createBlock(); // scopes that only contains NullStmts.
1922 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
1923 "label already in map");
1924 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
1926 // Labels partition blocks, so this is the end of the basic block we were
1927 // processing (L is the block's label). Because this is label (and we have
1928 // already processed the substatement) there is no extra control-flow to worry
1930 LabelBlock->setLabel(L);
1934 // We set Block to NULL to allow lazy creation of a new block (if necessary);
1937 // This block is now the implicit successor of other blocks.
1943 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
1944 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
1945 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
1946 et = E->capture_init_end(); it != et; ++it) {
1947 if (Expr *Init = *it) {
1948 CFGBlock *Tmp = Visit(Init);
1956 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
1957 // Goto is a control-flow statement. Thus we stop processing the current
1958 // block and create a new one.
1960 Block = createBlock(false);
1961 Block->setTerminator(G);
1963 // If we already know the mapping to the label block add the successor now.
1964 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1966 if (I == LabelMap.end())
1967 // We will need to backpatch this block later.
1968 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1970 JumpTarget JT = I->second;
1971 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
1972 addSuccessor(Block, JT.block);
1978 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
1979 CFGBlock *LoopSuccessor = NULL;
1981 // Save local scope position because in case of condition variable ScopePos
1982 // won't be restored when traversing AST.
1983 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1985 // Create local scope for init statement and possible condition variable.
1986 // Add destructor for init statement and condition variable.
1987 // Store scope position for continue statement.
1988 if (Stmt *Init = F->getInit())
1989 addLocalScopeForStmt(Init);
1990 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1992 if (VarDecl *VD = F->getConditionVariable())
1993 addLocalScopeForVarDecl(VD);
1994 LocalScope::const_iterator ContinueScopePos = ScopePos;
1996 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
1998 // "for" is a control-flow statement. Thus we stop processing the current
2003 LoopSuccessor = Block;
2005 LoopSuccessor = Succ;
2007 // Save the current value for the break targets.
2008 // All breaks should go to the code following the loop.
2009 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2010 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2012 CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2014 // Now create the loop body.
2016 assert(F->getBody());
2018 // Save the current values for Block, Succ, continue and break targets.
2019 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2020 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2022 // Create an empty block to represent the transition block for looping back
2023 // to the head of the loop. If we have increment code, it will
2024 // go in this block as well.
2025 Block = Succ = TransitionBlock = createBlock(false);
2026 TransitionBlock->setLoopTarget(F);
2028 if (Stmt *I = F->getInc()) {
2029 // Generate increment code in its own basic block. This is the target of
2030 // continue statements.
2034 // Finish up the increment (or empty) block if it hasn't been already.
2036 assert(Block == Succ);
2042 // The starting block for the loop increment is the block that should
2043 // represent the 'loop target' for looping back to the start of the loop.
2044 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2045 ContinueJumpTarget.block->setLoopTarget(F);
2047 // Loop body should end with destructor of Condition variable (if any).
2048 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
2050 // If body is not a compound statement create implicit scope
2051 // and add destructors.
2052 if (!isa<CompoundStmt>(F->getBody()))
2053 addLocalScopeAndDtors(F->getBody());
2055 // Now populate the body block, and in the process create new blocks as we
2056 // walk the body of the loop.
2057 BodyBlock = addStmt(F->getBody());
2060 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2061 // Use the continue jump target as the proxy for the body.
2062 BodyBlock = ContinueJumpTarget.block;
2068 // Because of short-circuit evaluation, the condition of the loop can span
2069 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2070 // evaluate the condition.
2071 CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2074 Expr *C = F->getCond();
2076 // Specially handle logical operators, which have a slightly
2077 // more optimal CFG representation.
2078 if (BinaryOperator *Cond =
2079 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : 0))
2080 if (Cond->isLogicalOp()) {
2081 llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2082 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2086 // The default case when not handling logical operators.
2087 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2088 ExitConditionBlock->setTerminator(F);
2090 // See if this is a known constant.
2091 TryResult KnownVal(true);
2094 // Now add the actual condition to the condition block.
2095 // Because the condition itself may contain control-flow, new blocks may
2096 // be created. Thus we update "Succ" after adding the condition.
2097 Block = ExitConditionBlock;
2098 EntryConditionBlock = addStmt(C);
2100 // If this block contains a condition variable, add both the condition
2101 // variable and initializer to the CFG.
2102 if (VarDecl *VD = F->getConditionVariable()) {
2103 if (Expr *Init = VD->getInit()) {
2105 appendStmt(Block, F->getConditionVariableDeclStmt());
2106 EntryConditionBlock = addStmt(Init);
2107 assert(Block == EntryConditionBlock);
2111 if (Block && badCFG)
2114 KnownVal = tryEvaluateBool(C);
2117 // Add the loop body entry as a successor to the condition.
2118 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2119 // Link up the condition block with the code that follows the loop. (the
2121 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2125 // Link up the loop-back block to the entry condition block.
2126 addSuccessor(TransitionBlock, EntryConditionBlock);
2128 // The condition block is the implicit successor for any code above the loop.
2129 Succ = EntryConditionBlock;
2131 // If the loop contains initialization, create a new block for those
2132 // statements. This block can also contain statements that precede the loop.
2133 if (Stmt *I = F->getInit()) {
2134 Block = createBlock();
2138 // There is no loop initialization. We are thus basically a while loop.
2139 // NULL out Block to force lazy block construction.
2141 Succ = EntryConditionBlock;
2142 return EntryConditionBlock;
2145 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2146 if (asc.alwaysAdd(*this, M)) {
2148 appendStmt(Block, M);
2150 return Visit(M->getBase());
2153 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2154 // Objective-C fast enumeration 'for' statements:
2155 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2157 // for ( Type newVariable in collection_expression ) { statements }
2162 // 1. collection_expression
2163 // T. jump to loop_entry
2165 // 1. side-effects of element expression
2166 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2167 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2170 // T. jump to loop_entry
2176 // Type existingItem;
2177 // for ( existingItem in expression ) { statements }
2181 // the same with newVariable replaced with existingItem; the binding works
2182 // the same except that for one ObjCForCollectionStmt::getElement() returns
2183 // a DeclStmt and the other returns a DeclRefExpr.
2186 CFGBlock *LoopSuccessor = 0;
2191 LoopSuccessor = Block;
2194 LoopSuccessor = Succ;
2196 // Build the condition blocks.
2197 CFGBlock *ExitConditionBlock = createBlock(false);
2199 // Set the terminator for the "exit" condition block.
2200 ExitConditionBlock->setTerminator(S);
2202 // The last statement in the block should be the ObjCForCollectionStmt, which
2203 // performs the actual binding to 'element' and determines if there are any
2204 // more items in the collection.
2205 appendStmt(ExitConditionBlock, S);
2206 Block = ExitConditionBlock;
2208 // Walk the 'element' expression to see if there are any side-effects. We
2209 // generate new blocks as necessary. We DON'T add the statement by default to
2210 // the CFG unless it contains control-flow.
2211 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2212 AddStmtChoice::NotAlwaysAdd);
2219 // The condition block is the implicit successor for the loop body as well as
2220 // any code above the loop.
2221 Succ = EntryConditionBlock;
2223 // Now create the true branch.
2225 // Save the current values for Succ, continue and break targets.
2226 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2227 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2228 save_break(BreakJumpTarget);
2230 // Add an intermediate block between the BodyBlock and the
2231 // EntryConditionBlock to represent the "loop back" transition, for looping
2232 // back to the head of the loop.
2233 CFGBlock *LoopBackBlock = 0;
2234 Succ = LoopBackBlock = createBlock();
2235 LoopBackBlock->setLoopTarget(S);
2237 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2238 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2240 CFGBlock *BodyBlock = addStmt(S->getBody());
2243 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2249 // This new body block is a successor to our "exit" condition block.
2250 addSuccessor(ExitConditionBlock, BodyBlock);
2253 // Link up the condition block with the code that follows the loop.
2254 // (the false branch).
2255 addSuccessor(ExitConditionBlock, LoopSuccessor);
2257 // Now create a prologue block to contain the collection expression.
2258 Block = createBlock();
2259 return addStmt(S->getCollection());
2262 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2264 return addStmt(S->getSubStmt());
2265 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2268 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2269 // FIXME: Add locking 'primitives' to CFG for @synchronized.
2272 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2274 // The sync body starts its own basic block. This makes it a little easier
2275 // for diagnostic clients.
2284 // Add the @synchronized to the CFG.
2286 appendStmt(Block, S);
2288 // Inline the sync expression.
2289 return addStmt(S->getSynchExpr());
2292 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2297 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2300 // Add the PseudoObject as the last thing.
2301 appendStmt(Block, E);
2303 CFGBlock *lastBlock = Block;
2305 // Before that, evaluate all of the semantics in order. In
2306 // CFG-land, that means appending them in reverse order.
2307 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2308 Expr *Semantic = E->getSemanticExpr(--i);
2310 // If the semantic is an opaque value, we're being asked to bind
2311 // it to its source expression.
2312 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2313 Semantic = OVE->getSourceExpr();
2315 if (CFGBlock *B = Visit(Semantic))
2322 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2323 CFGBlock *LoopSuccessor = NULL;
2325 // Save local scope position because in case of condition variable ScopePos
2326 // won't be restored when traversing AST.
2327 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2329 // Create local scope for possible condition variable.
2330 // Store scope position for continue statement.
2331 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2332 if (VarDecl *VD = W->getConditionVariable()) {
2333 addLocalScopeForVarDecl(VD);
2334 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2337 // "while" is a control-flow statement. Thus we stop processing the current
2342 LoopSuccessor = Block;
2345 LoopSuccessor = Succ;
2348 CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2350 // Process the loop body.
2352 assert(W->getBody());
2354 // Save the current values for Block, Succ, continue and break targets.
2355 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2356 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2357 save_break(BreakJumpTarget);
2359 // Create an empty block to represent the transition block for looping back
2360 // to the head of the loop.
2361 Succ = TransitionBlock = createBlock(false);
2362 TransitionBlock->setLoopTarget(W);
2363 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2365 // All breaks should go to the code following the loop.
2366 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2368 // Loop body should end with destructor of Condition variable (if any).
2369 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2371 // If body is not a compound statement create implicit scope
2372 // and add destructors.
2373 if (!isa<CompoundStmt>(W->getBody()))
2374 addLocalScopeAndDtors(W->getBody());
2376 // Create the body. The returned block is the entry to the loop body.
2377 BodyBlock = addStmt(W->getBody());
2380 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2381 else if (Block && badCFG)
2385 // Because of short-circuit evaluation, the condition of the loop can span
2386 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2387 // evaluate the condition.
2388 CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2391 Expr *C = W->getCond();
2393 // Specially handle logical operators, which have a slightly
2394 // more optimal CFG representation.
2395 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2396 if (Cond->isLogicalOp()) {
2397 llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2398 VisitLogicalOperator(Cond, W, BodyBlock,
2403 // The default case when not handling logical operators.
2404 ExitConditionBlock = createBlock(false);
2405 ExitConditionBlock->setTerminator(W);
2407 // Now add the actual condition to the condition block.
2408 // Because the condition itself may contain control-flow, new blocks may
2409 // be created. Thus we update "Succ" after adding the condition.
2410 Block = ExitConditionBlock;
2411 Block = EntryConditionBlock = addStmt(C);
2413 // If this block contains a condition variable, add both the condition
2414 // variable and initializer to the CFG.
2415 if (VarDecl *VD = W->getConditionVariable()) {
2416 if (Expr *Init = VD->getInit()) {
2418 appendStmt(Block, W->getConditionVariableDeclStmt());
2419 EntryConditionBlock = addStmt(Init);
2420 assert(Block == EntryConditionBlock);
2424 if (Block && badCFG)
2427 // See if this is a known constant.
2428 const TryResult& KnownVal = tryEvaluateBool(C);
2430 // Add the loop body entry as a successor to the condition.
2431 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2432 // Link up the condition block with the code that follows the loop. (the
2434 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2438 // Link up the loop-back block to the entry condition block.
2439 addSuccessor(TransitionBlock, EntryConditionBlock);
2441 // There can be no more statements in the condition block since we loop back
2442 // to this block. NULL out Block to force lazy creation of another block.
2445 // Return the condition block, which is the dominating block for the loop.
2446 Succ = EntryConditionBlock;
2447 return EntryConditionBlock;
2451 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
2452 // FIXME: For now we pretend that @catch and the code it contains does not
2457 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
2458 // FIXME: This isn't complete. We basically treat @throw like a return
2461 // If we were in the middle of a block we stop processing that block.
2465 // Create the new block.
2466 Block = createBlock(false);
2468 // The Exit block is the only successor.
2469 addSuccessor(Block, &cfg->getExit());
2471 // Add the statement to the block. This may create new blocks if S contains
2472 // control-flow (short-circuit operations).
2473 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
2476 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
2477 // If we were in the middle of a block we stop processing that block.
2481 // Create the new block.
2482 Block = createBlock(false);
2484 if (TryTerminatedBlock)
2485 // The current try statement is the only successor.
2486 addSuccessor(Block, TryTerminatedBlock);
2488 // otherwise the Exit block is the only successor.
2489 addSuccessor(Block, &cfg->getExit());
2491 // Add the statement to the block. This may create new blocks if S contains
2492 // control-flow (short-circuit operations).
2493 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
2496 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
2497 CFGBlock *LoopSuccessor = NULL;
2499 // "do...while" is a control-flow statement. Thus we stop processing the
2504 LoopSuccessor = Block;
2506 LoopSuccessor = Succ;
2508 // Because of short-circuit evaluation, the condition of the loop can span
2509 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2510 // evaluate the condition.
2511 CFGBlock *ExitConditionBlock = createBlock(false);
2512 CFGBlock *EntryConditionBlock = ExitConditionBlock;
2514 // Set the terminator for the "exit" condition block.
2515 ExitConditionBlock->setTerminator(D);
2517 // Now add the actual condition to the condition block. Because the condition
2518 // itself may contain control-flow, new blocks may be created.
2519 if (Stmt *C = D->getCond()) {
2520 Block = ExitConditionBlock;
2521 EntryConditionBlock = addStmt(C);
2528 // The condition block is the implicit successor for the loop body.
2529 Succ = EntryConditionBlock;
2531 // See if this is a known constant.
2532 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2534 // Process the loop body.
2535 CFGBlock *BodyBlock = NULL;
2537 assert(D->getBody());
2539 // Save the current values for Block, Succ, and continue and break targets
2540 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2541 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2542 save_break(BreakJumpTarget);
2544 // All continues within this loop should go to the condition block
2545 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2547 // All breaks should go to the code following the loop.
2548 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2550 // NULL out Block to force lazy instantiation of blocks for the body.
2553 // If body is not a compound statement create implicit scope
2554 // and add destructors.
2555 if (!isa<CompoundStmt>(D->getBody()))
2556 addLocalScopeAndDtors(D->getBody());
2558 // Create the body. The returned block is the entry to the loop body.
2559 BodyBlock = addStmt(D->getBody());
2562 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2568 if (!KnownVal.isFalse()) {
2569 // Add an intermediate block between the BodyBlock and the
2570 // ExitConditionBlock to represent the "loop back" transition. Create an
2571 // empty block to represent the transition block for looping back to the
2572 // head of the loop.
2573 // FIXME: Can we do this more efficiently without adding another block?
2576 CFGBlock *LoopBackBlock = createBlock();
2577 LoopBackBlock->setLoopTarget(D);
2579 // Add the loop body entry as a successor to the condition.
2580 addSuccessor(ExitConditionBlock, LoopBackBlock);
2583 addSuccessor(ExitConditionBlock, NULL);
2586 // Link up the condition block with the code that follows the loop.
2587 // (the false branch).
2588 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2590 // There can be no more statements in the body block(s) since we loop back to
2591 // the body. NULL out Block to force lazy creation of another block.
2594 // Return the loop body, which is the dominating block for the loop.
2599 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
2600 // "continue" is a control-flow statement. Thus we stop processing the
2605 // Now create a new block that ends with the continue statement.
2606 Block = createBlock(false);
2607 Block->setTerminator(C);
2609 // If there is no target for the continue, then we are looking at an
2610 // incomplete AST. This means the CFG cannot be constructed.
2611 if (ContinueJumpTarget.block) {
2612 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2613 addSuccessor(Block, ContinueJumpTarget.block);
2620 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2621 AddStmtChoice asc) {
2623 if (asc.alwaysAdd(*this, E)) {
2625 appendStmt(Block, E);
2628 // VLA types have expressions that must be evaluated.
2629 CFGBlock *lastBlock = Block;
2631 if (E->isArgumentType()) {
2632 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
2633 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
2634 lastBlock = addStmt(VA->getSizeExpr());
2639 /// VisitStmtExpr - Utility method to handle (nested) statement
2640 /// expressions (a GCC extension).
2641 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2642 if (asc.alwaysAdd(*this, SE)) {
2644 appendStmt(Block, SE);
2646 return VisitCompoundStmt(SE->getSubStmt());
2649 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
2650 // "switch" is a control-flow statement. Thus we stop processing the current
2652 CFGBlock *SwitchSuccessor = NULL;
2654 // Save local scope position because in case of condition variable ScopePos
2655 // won't be restored when traversing AST.
2656 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2658 // Create local scope for possible condition variable.
2659 // Store scope position. Add implicit destructor.
2660 if (VarDecl *VD = Terminator->getConditionVariable()) {
2661 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2662 addLocalScopeForVarDecl(VD);
2663 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2669 SwitchSuccessor = Block;
2670 } else SwitchSuccessor = Succ;
2672 // Save the current "switch" context.
2673 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2674 save_default(DefaultCaseBlock);
2675 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2677 // Set the "default" case to be the block after the switch statement. If the
2678 // switch statement contains a "default:", this value will be overwritten with
2679 // the block for that code.
2680 DefaultCaseBlock = SwitchSuccessor;
2682 // Create a new block that will contain the switch statement.
2683 SwitchTerminatedBlock = createBlock(false);
2685 // Now process the switch body. The code after the switch is the implicit
2687 Succ = SwitchSuccessor;
2688 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2690 // When visiting the body, the case statements should automatically get linked
2691 // up to the switch. We also don't keep a pointer to the body, since all
2692 // control-flow from the switch goes to case/default statements.
2693 assert(Terminator->getBody() && "switch must contain a non-NULL body");
2696 // For pruning unreachable case statements, save the current state
2697 // for tracking the condition value.
2698 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
2701 // Determine if the switch condition can be explicitly evaluated.
2702 assert(Terminator->getCond() && "switch condition must be non-NULL");
2703 Expr::EvalResult result;
2704 bool b = tryEvaluate(Terminator->getCond(), result);
2705 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
2708 // If body is not a compound statement create implicit scope
2709 // and add destructors.
2710 if (!isa<CompoundStmt>(Terminator->getBody()))
2711 addLocalScopeAndDtors(Terminator->getBody());
2713 addStmt(Terminator->getBody());
2719 // If we have no "default:" case, the default transition is to the code
2720 // following the switch body. Moreover, take into account if all the
2721 // cases of a switch are covered (e.g., switching on an enum value).
2723 // Note: We add a successor to a switch that is considered covered yet has no
2724 // case statements if the enumeration has no enumerators.
2725 bool SwitchAlwaysHasSuccessor = false;
2726 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
2727 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
2728 Terminator->getSwitchCaseList();
2729 addSuccessor(SwitchTerminatedBlock,
2730 SwitchAlwaysHasSuccessor ? 0 : DefaultCaseBlock);
2732 // Add the terminator and condition in the switch block.
2733 SwitchTerminatedBlock->setTerminator(Terminator);
2734 Block = SwitchTerminatedBlock;
2735 CFGBlock *LastBlock = addStmt(Terminator->getCond());
2737 // Finally, if the SwitchStmt contains a condition variable, add both the
2738 // SwitchStmt and the condition variable initialization to the CFG.
2739 if (VarDecl *VD = Terminator->getConditionVariable()) {
2740 if (Expr *Init = VD->getInit()) {
2742 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
2743 LastBlock = addStmt(Init);
2750 static bool shouldAddCase(bool &switchExclusivelyCovered,
2751 const Expr::EvalResult *switchCond,
2757 bool addCase = false;
2759 if (!switchExclusivelyCovered) {
2760 if (switchCond->Val.isInt()) {
2761 // Evaluate the LHS of the case value.
2762 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
2763 const llvm::APSInt &condInt = switchCond->Val.getInt();
2765 if (condInt == lhsInt) {
2767 switchExclusivelyCovered = true;
2769 else if (condInt < lhsInt) {
2770 if (const Expr *RHS = CS->getRHS()) {
2771 // Evaluate the RHS of the case value.
2772 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
2773 if (V2 <= condInt) {
2775 switchExclusivelyCovered = true;
2786 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
2787 // CaseStmts are essentially labels, so they are the first statement in a
2789 CFGBlock *TopBlock = 0, *LastBlock = 0;
2791 if (Stmt *Sub = CS->getSubStmt()) {
2792 // For deeply nested chains of CaseStmts, instead of doing a recursion
2793 // (which can blow out the stack), manually unroll and create blocks
2795 while (isa<CaseStmt>(Sub)) {
2796 CFGBlock *currentBlock = createBlock(false);
2797 currentBlock->setLabel(CS);
2800 addSuccessor(LastBlock, currentBlock);
2802 TopBlock = currentBlock;
2804 addSuccessor(SwitchTerminatedBlock,
2805 shouldAddCase(switchExclusivelyCovered, switchCond,
2807 ? currentBlock : 0);
2809 LastBlock = currentBlock;
2810 CS = cast<CaseStmt>(Sub);
2811 Sub = CS->getSubStmt();
2817 CFGBlock *CaseBlock = Block;
2819 CaseBlock = createBlock();
2821 // Cases statements partition blocks, so this is the top of the basic block we
2822 // were processing (the "case XXX:" is the label).
2823 CaseBlock->setLabel(CS);
2828 // Add this block to the list of successors for the block with the switch
2830 assert(SwitchTerminatedBlock);
2831 addSuccessor(SwitchTerminatedBlock,
2832 shouldAddCase(switchExclusivelyCovered, switchCond,
2836 // We set Block to NULL to allow lazy creation of a new block (if necessary)
2840 addSuccessor(LastBlock, CaseBlock);
2843 // This block is now the implicit successor of other blocks.
2850 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
2851 if (Terminator->getSubStmt())
2852 addStmt(Terminator->getSubStmt());
2854 DefaultCaseBlock = Block;
2856 if (!DefaultCaseBlock)
2857 DefaultCaseBlock = createBlock();
2859 // Default statements partition blocks, so this is the top of the basic block
2860 // we were processing (the "default:" is the label).
2861 DefaultCaseBlock->setLabel(Terminator);
2866 // Unlike case statements, we don't add the default block to the successors
2867 // for the switch statement immediately. This is done when we finish
2868 // processing the switch statement. This allows for the default case
2869 // (including a fall-through to the code after the switch statement) to always
2870 // be the last successor of a switch-terminated block.
2872 // We set Block to NULL to allow lazy creation of a new block (if necessary)
2875 // This block is now the implicit successor of other blocks.
2876 Succ = DefaultCaseBlock;
2878 return DefaultCaseBlock;
2881 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2882 // "try"/"catch" is a control-flow statement. Thus we stop processing the
2884 CFGBlock *TrySuccessor = NULL;
2889 TrySuccessor = Block;
2890 } else TrySuccessor = Succ;
2892 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2894 // Create a new block that will contain the try statement.
2895 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2896 // Add the terminator in the try block.
2897 NewTryTerminatedBlock->setTerminator(Terminator);
2899 bool HasCatchAll = false;
2900 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2901 // The code after the try is the implicit successor.
2902 Succ = TrySuccessor;
2903 CXXCatchStmt *CS = Terminator->getHandler(h);
2904 if (CS->getExceptionDecl() == 0) {
2908 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2909 if (CatchBlock == 0)
2911 // Add this block to the list of successors for the block with the try
2913 addSuccessor(NewTryTerminatedBlock, CatchBlock);
2916 if (PrevTryTerminatedBlock)
2917 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2919 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2922 // The code after the try is the implicit successor.
2923 Succ = TrySuccessor;
2925 // Save the current "try" context.
2926 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
2927 cfg->addTryDispatchBlock(TryTerminatedBlock);
2929 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2931 return addStmt(Terminator->getTryBlock());
2934 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
2935 // CXXCatchStmt are treated like labels, so they are the first statement in a
2938 // Save local scope position because in case of exception variable ScopePos
2939 // won't be restored when traversing AST.
2940 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2942 // Create local scope for possible exception variable.
2943 // Store scope position. Add implicit destructor.
2944 if (VarDecl *VD = CS->getExceptionDecl()) {
2945 LocalScope::const_iterator BeginScopePos = ScopePos;
2946 addLocalScopeForVarDecl(VD);
2947 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2950 if (CS->getHandlerBlock())
2951 addStmt(CS->getHandlerBlock());
2953 CFGBlock *CatchBlock = Block;
2955 CatchBlock = createBlock();
2957 // CXXCatchStmt is more than just a label. They have semantic meaning
2958 // as well, as they implicitly "initialize" the catch variable. Add
2959 // it to the CFG as a CFGElement so that the control-flow of these
2960 // semantics gets captured.
2961 appendStmt(CatchBlock, CS);
2963 // Also add the CXXCatchStmt as a label, to mirror handling of regular
2965 CatchBlock->setLabel(CS);
2967 // Bail out if the CFG is bad.
2971 // We set Block to NULL to allow lazy creation of a new block (if necessary)
2977 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
2978 // C++0x for-range statements are specified as [stmt.ranged]:
2981 // auto && __range = range-init;
2982 // for ( auto __begin = begin-expr,
2983 // __end = end-expr;
2984 // __begin != __end;
2986 // for-range-declaration = *__begin;
2991 // Save local scope position before the addition of the implicit variables.
2992 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2994 // Create local scopes and destructors for range, begin and end variables.
2995 if (Stmt *Range = S->getRangeStmt())
2996 addLocalScopeForStmt(Range);
2997 if (Stmt *BeginEnd = S->getBeginEndStmt())
2998 addLocalScopeForStmt(BeginEnd);
2999 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3001 LocalScope::const_iterator ContinueScopePos = ScopePos;
3003 // "for" is a control-flow statement. Thus we stop processing the current
3005 CFGBlock *LoopSuccessor = NULL;
3009 LoopSuccessor = Block;
3011 LoopSuccessor = Succ;
3013 // Save the current value for the break targets.
3014 // All breaks should go to the code following the loop.
3015 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3016 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3018 // The block for the __begin != __end expression.
3019 CFGBlock *ConditionBlock = createBlock(false);
3020 ConditionBlock->setTerminator(S);
3022 // Now add the actual condition to the condition block.
3023 if (Expr *C = S->getCond()) {
3024 Block = ConditionBlock;
3025 CFGBlock *BeginConditionBlock = addStmt(C);
3028 assert(BeginConditionBlock == ConditionBlock &&
3029 "condition block in for-range was unexpectedly complex");
3030 (void)BeginConditionBlock;
3033 // The condition block is the implicit successor for the loop body as well as
3034 // any code above the loop.
3035 Succ = ConditionBlock;
3037 // See if this is a known constant.
3038 TryResult KnownVal(true);
3041 KnownVal = tryEvaluateBool(S->getCond());
3043 // Now create the loop body.
3045 assert(S->getBody());
3047 // Save the current values for Block, Succ, and continue targets.
3048 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3049 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3051 // Generate increment code in its own basic block. This is the target of
3052 // continue statements.
3054 Succ = addStmt(S->getInc());
3055 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3057 // The starting block for the loop increment is the block that should
3058 // represent the 'loop target' for looping back to the start of the loop.
3059 ContinueJumpTarget.block->setLoopTarget(S);
3061 // Finish up the increment block and prepare to start the loop body.
3068 // Add implicit scope and dtors for loop variable.
3069 addLocalScopeAndDtors(S->getLoopVarStmt());
3071 // Populate a new block to contain the loop body and loop variable.
3072 addStmt(S->getBody());
3075 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3079 // This new body block is a successor to our condition block.
3080 addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : LoopVarStmtBlock);
3083 // Link up the condition block with the code that follows the loop (the
3085 addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor);
3087 // Add the initialization statements.
3088 Block = createBlock();
3089 addStmt(S->getBeginEndStmt());
3090 return addStmt(S->getRangeStmt());
3093 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3094 AddStmtChoice asc) {
3095 if (BuildOpts.AddTemporaryDtors) {
3096 // If adding implicit destructors visit the full expression for adding
3097 // destructors of temporaries.
3098 VisitForTemporaryDtors(E->getSubExpr());
3100 // Full expression has to be added as CFGStmt so it will be sequenced
3101 // before destructors of it's temporaries.
3102 asc = asc.withAlwaysAdd(true);
3104 return Visit(E->getSubExpr(), asc);
3107 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3108 AddStmtChoice asc) {
3109 if (asc.alwaysAdd(*this, E)) {
3111 appendStmt(Block, E);
3113 // We do not want to propagate the AlwaysAdd property.
3114 asc = asc.withAlwaysAdd(false);
3116 return Visit(E->getSubExpr(), asc);
3119 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3120 AddStmtChoice asc) {
3122 appendStmt(Block, C);
3124 return VisitChildren(C);
3128 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3129 AddStmtChoice asc) {
3131 appendStmt(Block, DE);
3132 QualType DTy = DE->getDestroyedType();
3133 DTy = DTy.getNonReferenceType();
3134 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3136 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3137 appendDeleteDtor(Block, RD, DE);
3140 return VisitChildren(DE);
3143 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3144 AddStmtChoice asc) {
3145 if (asc.alwaysAdd(*this, E)) {
3147 appendStmt(Block, E);
3148 // We do not want to propagate the AlwaysAdd property.
3149 asc = asc.withAlwaysAdd(false);
3151 return Visit(E->getSubExpr(), asc);
3154 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3155 AddStmtChoice asc) {
3157 appendStmt(Block, C);
3158 return VisitChildren(C);
3161 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3162 AddStmtChoice asc) {
3163 if (asc.alwaysAdd(*this, E)) {
3165 appendStmt(Block, E);
3167 return Visit(E->getSubExpr(), AddStmtChoice());
3170 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3171 // Lazily create the indirect-goto dispatch block if there isn't one already.
3172 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3175 IBlock = createBlock(false);
3176 cfg->setIndirectGotoBlock(IBlock);
3179 // IndirectGoto is a control-flow statement. Thus we stop processing the
3180 // current block and create a new one.
3184 Block = createBlock(false);
3185 Block->setTerminator(I);
3186 addSuccessor(Block, IBlock);
3187 return addStmt(I->getTarget());
3190 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) {
3191 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3198 switch (E->getStmtClass()) {
3200 return VisitChildrenForTemporaryDtors(E);
3202 case Stmt::BinaryOperatorClass:
3203 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E));
3205 case Stmt::CXXBindTemporaryExprClass:
3206 return VisitCXXBindTemporaryExprForTemporaryDtors(
3207 cast<CXXBindTemporaryExpr>(E), BindToTemporary);
3209 case Stmt::BinaryConditionalOperatorClass:
3210 case Stmt::ConditionalOperatorClass:
3211 return VisitConditionalOperatorForTemporaryDtors(
3212 cast<AbstractConditionalOperator>(E), BindToTemporary);
3214 case Stmt::ImplicitCastExprClass:
3215 // For implicit cast we want BindToTemporary to be passed further.
3216 E = cast<CastExpr>(E)->getSubExpr();
3219 case Stmt::ParenExprClass:
3220 E = cast<ParenExpr>(E)->getSubExpr();
3223 case Stmt::MaterializeTemporaryExprClass:
3224 E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr();
3229 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) {
3230 // When visiting children for destructors we want to visit them in reverse
3231 // order that they will appear in the CFG. Because the CFG is built
3232 // bottom-up, this means we visit them in their natural order, which
3233 // reverses them in the CFG.
3234 CFGBlock *B = Block;
3235 for (Stmt::child_range I = E->children(); I; ++I) {
3236 if (Stmt *Child = *I)
3237 if (CFGBlock *R = VisitForTemporaryDtors(Child))
3243 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) {
3244 if (E->isLogicalOp()) {
3245 // Destructors for temporaries in LHS expression should be called after
3246 // those for RHS expression. Even if this will unnecessarily create a block,
3247 // this block will be used at least by the full expression.
3249 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS());
3253 Succ = ConfluenceBlock;
3255 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3261 // If RHS expression did produce destructors we need to connect created
3262 // blocks to CFG in same manner as for binary operator itself.
3263 CFGBlock *LHSBlock = createBlock(false);
3264 LHSBlock->setTerminator(CFGTerminator(E, true));
3266 // For binary operator LHS block is before RHS in list of predecessors
3267 // of ConfluenceBlock.
3268 std::reverse(ConfluenceBlock->pred_begin(),
3269 ConfluenceBlock->pred_end());
3271 // See if this is a known constant.
3272 TryResult KnownVal = tryEvaluateBool(E->getLHS());
3273 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr))
3276 // Link LHSBlock with RHSBlock exactly the same way as for binary operator
3278 if (E->getOpcode() == BO_LOr) {
3279 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3280 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3282 assert (E->getOpcode() == BO_LAnd);
3283 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3284 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3291 Block = ConfluenceBlock;
3292 return ConfluenceBlock;
3295 if (E->isAssignmentOp()) {
3296 // For assignment operator (=) LHS expression is visited
3297 // before RHS expression. For destructors visit them in reverse order.
3298 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3299 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3300 return LHSBlock ? LHSBlock : RHSBlock;
3303 // For any other binary operator RHS expression is visited before
3304 // LHS expression (order of children). For destructors visit them in reverse
3306 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3307 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3308 return RHSBlock ? RHSBlock : LHSBlock;
3311 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3312 CXXBindTemporaryExpr *E, bool BindToTemporary) {
3313 // First add destructors for temporaries in subexpression.
3314 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr());
3315 if (!BindToTemporary) {
3316 // If lifetime of temporary is not prolonged (by assigning to constant
3317 // reference) add destructor for it.
3319 // If the destructor is marked as a no-return destructor, we need to create
3320 // a new block for the destructor which does not have as a successor
3321 // anything built thus far. Control won't flow out of this block.
3322 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3323 if (Dtor->isNoReturn())
3324 Block = createNoReturnBlock();
3328 appendTemporaryDtor(Block, E);
3334 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3335 AbstractConditionalOperator *E, bool BindToTemporary) {
3336 // First add destructors for condition expression. Even if this will
3337 // unnecessarily create a block, this block will be used at least by the full
3340 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond());
3343 if (BinaryConditionalOperator *BCO
3344 = dyn_cast<BinaryConditionalOperator>(E)) {
3345 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon());
3350 // Try to add block with destructors for LHS expression.
3351 CFGBlock *LHSBlock = NULL;
3352 Succ = ConfluenceBlock;
3354 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary);
3358 // Try to add block with destructors for RHS expression;
3359 Succ = ConfluenceBlock;
3361 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(),
3366 if (!RHSBlock && !LHSBlock) {
3367 // If neither LHS nor RHS expression had temporaries to destroy don't create
3369 Block = ConfluenceBlock;
3373 Block = createBlock(false);
3374 Block->setTerminator(CFGTerminator(E, true));
3376 // See if this is a known constant.
3377 const TryResult &KnownVal = tryEvaluateBool(E->getCond());
3380 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
3381 } else if (KnownVal.isFalse()) {
3382 addSuccessor(Block, NULL);
3384 addSuccessor(Block, ConfluenceBlock);
3385 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end());
3389 RHSBlock = ConfluenceBlock;
3390 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
3395 } // end anonymous namespace
3397 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3398 /// no successors or predecessors. If this is the first block created in the
3399 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
3400 CFGBlock *CFG::createBlock() {
3401 bool first_block = begin() == end();
3403 // Create the block.
3404 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
3405 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
3406 Blocks.push_back(Mem, BlkBVC);
3408 // If this is the first block, set it as the Entry and Exit.
3410 Entry = Exit = &back();
3412 // Return the block.
3416 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
3417 /// CFG is returned to the caller.
3418 CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
3419 const BuildOptions &BO) {
3420 CFGBuilder Builder(C, BO);
3421 return Builder.buildCFG(D, Statement);
3424 const CXXDestructorDecl *
3425 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
3426 switch (getKind()) {
3427 case CFGElement::Statement:
3428 case CFGElement::Initializer:
3429 llvm_unreachable("getDestructorDecl should only be used with "
3431 case CFGElement::AutomaticObjectDtor: {
3432 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
3433 QualType ty = var->getType();
3434 ty = ty.getNonReferenceType();
3435 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
3436 ty = arrayType->getElementType();
3438 const RecordType *recordType = ty->getAs<RecordType>();
3439 const CXXRecordDecl *classDecl =
3440 cast<CXXRecordDecl>(recordType->getDecl());
3441 return classDecl->getDestructor();
3443 case CFGElement::DeleteDtor: {
3444 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3445 QualType DTy = DE->getDestroyedType();
3446 DTy = DTy.getNonReferenceType();
3447 const CXXRecordDecl *classDecl =
3448 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3449 return classDecl->getDestructor();
3451 case CFGElement::TemporaryDtor: {
3452 const CXXBindTemporaryExpr *bindExpr =
3453 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
3454 const CXXTemporary *temp = bindExpr->getTemporary();
3455 return temp->getDestructor();
3457 case CFGElement::BaseDtor:
3458 case CFGElement::MemberDtor:
3460 // Not yet supported.
3463 llvm_unreachable("getKind() returned bogus value");
3466 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
3467 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3468 return DD->isNoReturn();
3472 //===----------------------------------------------------------------------===//
3473 // Filtered walking of the CFG.
3474 //===----------------------------------------------------------------------===//
3476 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
3477 const CFGBlock *From, const CFGBlock *To) {
3479 if (To && F.IgnoreDefaultsWithCoveredEnums) {
3480 // If the 'To' has no label or is labeled but the label isn't a
3481 // CaseStmt then filter this edge.
3482 if (const SwitchStmt *S =
3483 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
3484 if (S->isAllEnumCasesCovered()) {
3485 const Stmt *L = To->getLabel();
3486 if (!L || !isa<CaseStmt>(L))
3495 //===----------------------------------------------------------------------===//
3496 // CFG pretty printing
3497 //===----------------------------------------------------------------------===//
3501 class StmtPrinterHelper : public PrinterHelper {
3502 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3503 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
3506 signed currentBlock;
3508 const LangOptions &LangOpts;
3511 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
3512 : currentBlock(0), currStmt(0), LangOpts(LO)
3514 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3516 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
3517 BI != BEnd; ++BI, ++j ) {
3518 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3519 const Stmt *stmt= SE->getStmt();
3520 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
3523 switch (stmt->getStmtClass()) {
3524 case Stmt::DeclStmtClass:
3525 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3527 case Stmt::IfStmtClass: {
3528 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3533 case Stmt::ForStmtClass: {
3534 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3539 case Stmt::WhileStmtClass: {
3540 const VarDecl *var =
3541 cast<WhileStmt>(stmt)->getConditionVariable();
3546 case Stmt::SwitchStmtClass: {
3547 const VarDecl *var =
3548 cast<SwitchStmt>(stmt)->getConditionVariable();
3553 case Stmt::CXXCatchStmtClass: {
3554 const VarDecl *var =
3555 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3569 virtual ~StmtPrinterHelper() {}
3571 const LangOptions &getLangOpts() const { return LangOpts; }
3572 void setBlockID(signed i) { currentBlock = i; }
3573 void setStmtID(unsigned i) { currStmt = i; }
3575 virtual bool handledStmt(Stmt *S, raw_ostream &OS) {
3576 StmtMapTy::iterator I = StmtMap.find(S);
3578 if (I == StmtMap.end())
3581 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3582 && I->second.second == currStmt) {
3586 OS << "[B" << I->second.first << "." << I->second.second << "]";
3590 bool handleDecl(const Decl *D, raw_ostream &OS) {
3591 DeclMapTy::iterator I = DeclMap.find(D);
3593 if (I == DeclMap.end())
3596 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3597 && I->second.second == currStmt) {
3601 OS << "[B" << I->second.first << "." << I->second.second << "]";
3605 } // end anonymous namespace
3609 class CFGBlockTerminatorPrint
3610 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
3613 StmtPrinterHelper* Helper;
3614 PrintingPolicy Policy;
3616 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
3617 const PrintingPolicy &Policy)
3618 : OS(os), Helper(helper), Policy(Policy) {}
3620 void VisitIfStmt(IfStmt *I) {
3622 I->getCond()->printPretty(OS,Helper,Policy);
3626 void VisitStmt(Stmt *Terminator) {
3627 Terminator->printPretty(OS, Helper, Policy);
3630 void VisitDeclStmt(DeclStmt *DS) {
3631 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
3632 OS << "static init " << VD->getName();
3635 void VisitForStmt(ForStmt *F) {
3640 if (Stmt *C = F->getCond())
3641 C->printPretty(OS, Helper, Policy);
3648 void VisitWhileStmt(WhileStmt *W) {
3650 if (Stmt *C = W->getCond())
3651 C->printPretty(OS, Helper, Policy);
3654 void VisitDoStmt(DoStmt *D) {
3655 OS << "do ... while ";
3656 if (Stmt *C = D->getCond())
3657 C->printPretty(OS, Helper, Policy);
3660 void VisitSwitchStmt(SwitchStmt *Terminator) {
3662 Terminator->getCond()->printPretty(OS, Helper, Policy);
3665 void VisitCXXTryStmt(CXXTryStmt *CS) {
3669 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
3670 C->getCond()->printPretty(OS, Helper, Policy);
3671 OS << " ? ... : ...";
3674 void VisitChooseExpr(ChooseExpr *C) {
3675 OS << "__builtin_choose_expr( ";
3676 C->getCond()->printPretty(OS, Helper, Policy);
3680 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3682 I->getTarget()->printPretty(OS, Helper, Policy);
3685 void VisitBinaryOperator(BinaryOperator* B) {
3686 if (!B->isLogicalOp()) {
3691 B->getLHS()->printPretty(OS, Helper, Policy);
3693 switch (B->getOpcode()) {
3701 llvm_unreachable("Invalid logical operator.");
3705 void VisitExpr(Expr *E) {
3706 E->printPretty(OS, Helper, Policy);
3709 } // end anonymous namespace
3711 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
3712 const CFGElement &E) {
3713 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
3714 const Stmt *S = CS->getStmt();
3716 // special printing for statement-expressions.
3717 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
3718 const CompoundStmt *Sub = SE->getSubStmt();
3720 if (Sub->children()) {
3722 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
3727 // special printing for comma expressions.
3728 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
3729 if (B->getOpcode() == BO_Comma) {
3731 Helper.handledStmt(B->getRHS(),OS);
3736 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3738 if (isa<CXXOperatorCallExpr>(S)) {
3739 OS << " (OperatorCall)";
3741 else if (isa<CXXBindTemporaryExpr>(S)) {
3742 OS << " (BindTemporary)";
3744 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
3745 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
3747 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
3748 OS << " (" << CE->getStmtClassName() << ", "
3749 << CE->getCastKindName()
3750 << ", " << CE->getType().getAsString()
3754 // Expressions need a newline.
3758 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
3759 const CXXCtorInitializer *I = IE->getInitializer();
3760 if (I->isBaseInitializer())
3761 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
3762 else if (I->isDelegatingInitializer())
3763 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
3764 else OS << I->getAnyMember()->getName();
3767 if (Expr *IE = I->getInit())
3768 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3771 if (I->isBaseInitializer())
3772 OS << " (Base initializer)\n";
3773 else if (I->isDelegatingInitializer())
3774 OS << " (Delegating initializer)\n";
3775 else OS << " (Member initializer)\n";
3777 } else if (Optional<CFGAutomaticObjDtor> DE =
3778 E.getAs<CFGAutomaticObjDtor>()) {
3779 const VarDecl *VD = DE->getVarDecl();
3780 Helper.handleDecl(VD, OS);
3782 const Type* T = VD->getType().getTypePtr();
3783 if (const ReferenceType* RT = T->getAs<ReferenceType>())
3784 T = RT->getPointeeType().getTypePtr();
3785 T = T->getBaseElementTypeUnsafe();
3787 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
3788 OS << " (Implicit destructor)\n";
3790 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
3791 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
3794 CXXDeleteExpr *DelExpr =
3795 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
3796 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
3797 OS << "->~" << RD->getName().str() << "()";
3798 OS << " (Implicit destructor)\n";
3799 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
3800 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
3801 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
3802 OS << " (Base object destructor)\n";
3804 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
3805 const FieldDecl *FD = ME->getFieldDecl();
3806 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
3807 OS << "this->" << FD->getName();
3808 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
3809 OS << " (Member object destructor)\n";
3811 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
3812 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
3814 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
3815 OS << "() (Temporary object destructor)\n";
3819 static void print_block(raw_ostream &OS, const CFG* cfg,
3821 StmtPrinterHelper &Helper, bool print_edges,
3824 Helper.setBlockID(B.getBlockID());
3826 // Print the header.
3828 OS.changeColor(raw_ostream::YELLOW, true);
3830 OS << "\n [B" << B.getBlockID();
3832 if (&B == &cfg->getEntry())
3833 OS << " (ENTRY)]\n";
3834 else if (&B == &cfg->getExit())
3836 else if (&B == cfg->getIndirectGotoBlock())
3837 OS << " (INDIRECT GOTO DISPATCH)]\n";
3844 // Print the label of this block.
3845 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
3850 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
3852 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
3854 C->getLHS()->printPretty(OS, &Helper,
3855 PrintingPolicy(Helper.getLangOpts()));
3858 C->getRHS()->printPretty(OS, &Helper,
3859 PrintingPolicy(Helper.getLangOpts()));
3861 } else if (isa<DefaultStmt>(Label))
3863 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
3865 if (CS->getExceptionDecl())
3866 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
3873 llvm_unreachable("Invalid label statement in CFGBlock.");
3878 // Iterate through the statements in the block and print them.
3881 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
3882 I != E ; ++I, ++j ) {
3884 // Print the statement # in the basic block and the statement itself.
3888 OS << llvm::format("%3d", j) << ": ";
3890 Helper.setStmtID(j);
3892 print_elem(OS, Helper, *I);
3895 // Print the terminator of this block.
3896 if (B.getTerminator()) {
3898 OS.changeColor(raw_ostream::GREEN);
3902 Helper.setBlockID(-1);
3904 PrintingPolicy PP(Helper.getLangOpts());
3905 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
3906 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
3914 // Print the predecessors of this block.
3915 if (!B.pred_empty()) {
3916 const raw_ostream::Colors Color = raw_ostream::BLUE;
3918 OS.changeColor(Color);
3922 OS << '(' << B.pred_size() << "):";
3926 OS.changeColor(Color);
3928 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
3934 OS << " B" << (*I)->getBlockID();
3943 // Print the successors of this block.
3944 if (!B.succ_empty()) {
3945 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
3947 OS.changeColor(Color);
3951 OS << '(' << B.succ_size() << "):";
3955 OS.changeColor(Color);
3957 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
3964 OS << " B" << (*I)->getBlockID();
3977 /// dump - A simple pretty printer of a CFG that outputs to stderr.
3978 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
3979 print(llvm::errs(), LO, ShowColors);
3982 /// print - A simple pretty printer of a CFG that outputs to an ostream.
3983 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
3984 StmtPrinterHelper Helper(this, LO);
3986 // Print the entry block.
3987 print_block(OS, this, getEntry(), Helper, true, ShowColors);
3989 // Iterate through the CFGBlocks and print them one by one.
3990 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
3991 // Skip the entry block, because we already printed it.
3992 if (&(**I) == &getEntry() || &(**I) == &getExit())
3995 print_block(OS, this, **I, Helper, true, ShowColors);
3998 // Print the exit block.
3999 print_block(OS, this, getExit(), Helper, true, ShowColors);
4004 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4005 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4006 bool ShowColors) const {
4007 print(llvm::errs(), cfg, LO, ShowColors);
4010 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4011 /// Generally this will only be called from CFG::print.
4012 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4013 const LangOptions &LO, bool ShowColors) const {
4014 StmtPrinterHelper Helper(cfg, LO);
4015 print_block(OS, cfg, *this, Helper, true, ShowColors);
4019 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4020 void CFGBlock::printTerminator(raw_ostream &OS,
4021 const LangOptions &LO) const {
4022 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
4023 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
4026 Stmt *CFGBlock::getTerminatorCondition() {
4027 Stmt *Terminator = this->Terminator;
4033 switch (Terminator->getStmtClass()) {
4037 case Stmt::CXXForRangeStmtClass:
4038 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4041 case Stmt::ForStmtClass:
4042 E = cast<ForStmt>(Terminator)->getCond();
4045 case Stmt::WhileStmtClass:
4046 E = cast<WhileStmt>(Terminator)->getCond();
4049 case Stmt::DoStmtClass:
4050 E = cast<DoStmt>(Terminator)->getCond();
4053 case Stmt::IfStmtClass:
4054 E = cast<IfStmt>(Terminator)->getCond();
4057 case Stmt::ChooseExprClass:
4058 E = cast<ChooseExpr>(Terminator)->getCond();
4061 case Stmt::IndirectGotoStmtClass:
4062 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4065 case Stmt::SwitchStmtClass:
4066 E = cast<SwitchStmt>(Terminator)->getCond();
4069 case Stmt::BinaryConditionalOperatorClass:
4070 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4073 case Stmt::ConditionalOperatorClass:
4074 E = cast<ConditionalOperator>(Terminator)->getCond();
4077 case Stmt::BinaryOperatorClass: // '&&' and '||'
4078 E = cast<BinaryOperator>(Terminator)->getLHS();
4081 case Stmt::ObjCForCollectionStmtClass:
4085 return E ? E->IgnoreParens() : NULL;
4088 //===----------------------------------------------------------------------===//
4089 // CFG Graphviz Visualization
4090 //===----------------------------------------------------------------------===//
4094 static StmtPrinterHelper* GraphHelper;
4097 void CFG::viewCFG(const LangOptions &LO) const {
4099 StmtPrinterHelper H(this, LO);
4101 llvm::ViewGraph(this,"CFG");
4108 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4110 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4112 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4115 std::string OutSStr;
4116 llvm::raw_string_ostream Out(OutSStr);
4117 print_block(Out,Graph, *Node, *GraphHelper, false, false);
4118 std::string& OutStr = Out.str();
4120 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4122 // Process string output to make it nicer...
4123 for (unsigned i = 0; i != OutStr.length(); ++i)
4124 if (OutStr[i] == '\n') { // Left justify
4126 OutStr.insert(OutStr.begin()+i+1, 'l');
4135 } // end namespace llvm