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/Support/SaveAndRestore.h"
16 #include "clang/Analysis/CFG.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/AST/PrettyPrinter.h"
19 #include "llvm/Support/GraphWriter.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallPtrSet.h"
26 using namespace clang;
30 static SourceLocation GetEndLoc(Decl* D) {
31 if (VarDecl* VD = dyn_cast<VarDecl>(D))
32 if (Expr* Ex = VD->getInit())
33 return Ex->getSourceRange().getEnd();
35 return D->getLocation();
38 /// CFGBuilder - This class implements CFG construction from an AST.
39 /// The builder is stateful: an instance of the builder should be used to only
40 /// construct a single CFG.
44 /// CFGBuilder builder;
45 /// CFG* cfg = builder.BuildAST(stmt1);
47 /// CFG construction is done via a recursive walk of an AST. We actually parse
48 /// the AST in reverse order so that the successor of a basic block is
49 /// constructed prior to its predecessor. This allows us to nicely capture
50 /// implicit fall-throughs without extra basic blocks.
52 class VISIBILITY_HIDDEN CFGBuilder {
58 CFGBlock* ContinueTargetBlock;
59 CFGBlock* BreakTargetBlock;
60 CFGBlock* SwitchTerminatedBlock;
61 CFGBlock* DefaultCaseBlock;
63 // LabelMap records the mapping from Label expressions to their blocks.
64 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
67 // A list of blocks that end with a "goto" that must be backpatched to their
68 // resolved targets upon completion of CFG construction.
69 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
70 BackpatchBlocksTy BackpatchBlocks;
72 // A list of labels whose address has been taken (for indirect gotos).
73 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
74 LabelSetTy AddressTakenLabels;
77 explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
78 Block(NULL), Succ(NULL),
79 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
80 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {}
82 ~CFGBuilder() { delete cfg; }
84 // buildCFG - Used by external clients to construct the CFG.
85 CFG* buildCFG(Stmt *Statement, ASTContext *C);
88 // Visitors to walk an AST and construct the CFG.
89 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd);
90 CFGBlock *VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd);
91 CFGBlock *VisitBlockExpr(BlockExpr* E, bool alwaysAdd);
92 CFGBlock *VisitBlockDeclRefExpr(BlockDeclRefExpr* E, bool alwaysAdd);
93 CFGBlock *VisitBreakStmt(BreakStmt *B);
94 CFGBlock *VisitCallExpr(CallExpr *C, bool alwaysAdd);
95 CFGBlock *VisitCaseStmt(CaseStmt *C);
96 CFGBlock *VisitChooseExpr(ChooseExpr *C);
97 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
98 CFGBlock *VisitConditionalOperator(ConditionalOperator *C);
99 CFGBlock *VisitContinueStmt(ContinueStmt *C);
100 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
101 CFGBlock *VisitDeclStmt(DeclStmt *DS);
102 CFGBlock *VisitDeclSubExpr(Decl* D);
103 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
104 CFGBlock *VisitDoStmt(DoStmt *D);
105 CFGBlock *VisitForStmt(ForStmt *F);
106 CFGBlock *VisitGotoStmt(GotoStmt* G);
107 CFGBlock *VisitIfStmt(IfStmt *I);
108 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
109 CFGBlock *VisitLabelStmt(LabelStmt *L);
110 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
111 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
112 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
113 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
114 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
115 CFGBlock *VisitReturnStmt(ReturnStmt* R);
116 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, bool alwaysAdd);
117 CFGBlock *VisitStmtExpr(StmtExpr *S, bool alwaysAdd);
118 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
119 CFGBlock *VisitWhileStmt(WhileStmt *W);
121 CFGBlock *Visit(Stmt *S, bool alwaysAdd = false);
122 CFGBlock *VisitStmt(Stmt *S, bool alwaysAdd);
123 CFGBlock *VisitChildren(Stmt* S);
125 // NYS == Not Yet Supported
131 void autoCreateBlock() { if (!Block) Block = createBlock(); }
132 CFGBlock *createBlock(bool add_successor = true);
133 bool FinishBlock(CFGBlock* B);
134 CFGBlock *addStmt(Stmt *S) { return Visit(S, true); }
136 void AppendStmt(CFGBlock *B, Stmt *S) {
137 B->appendStmt(S, cfg->getBumpVectorContext());
140 void AddSuccessor(CFGBlock *B, CFGBlock *S) {
141 B->addSuccessor(S, cfg->getBumpVectorContext());
144 /// TryResult - a class representing a variant over the values
145 /// 'true', 'false', or 'unknown'. This is returned by TryEvaluateBool,
146 /// and is used by the CFGBuilder to decide if a branch condition
147 /// can be decided up front during CFG construction.
151 TryResult(bool b) : X(b ? 1 : 0) {}
152 TryResult() : X(-1) {}
154 bool isTrue() const { return X == 1; }
155 bool isFalse() const { return X == 0; }
156 bool isKnown() const { return X >= 0; }
163 /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
164 /// if we can evaluate to a known value, otherwise return -1.
165 TryResult TryEvaluateBool(Expr *S) {
166 Expr::EvalResult Result;
167 if (!S->isTypeDependent() && !S->isValueDependent() &&
168 S->Evaluate(Result, *Context) && Result.Val.isInt())
169 return Result.Val.getInt().getBoolValue();
177 // FIXME: Add support for dependent-sized array types in C++?
178 // Does it even make sense to build a CFG for an uninstantiated template?
179 static VariableArrayType* FindVA(Type* t) {
180 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
181 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
182 if (vat->getSizeExpr())
185 t = vt->getElementType().getTypePtr();
191 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
192 /// arbitrary statement. Examples include a single expression or a function
193 /// body (compound statement). The ownership of the returned CFG is
194 /// transferred to the caller. If CFG construction fails, this method returns
196 CFG* CFGBuilder::buildCFG(Stmt* Statement, ASTContext* C) {
204 // Create an empty block that will serve as the exit block for the CFG. Since
205 // this is the first block added to the CFG, it will be implicitly registered
206 // as the exit block.
207 Succ = createBlock();
208 assert(Succ == &cfg->getExit());
209 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
211 // Visit the statements and create the CFG.
212 CFGBlock* B = addStmt(Statement);
216 // Finalize the last constructed block. This usually involves reversing the
217 // order of the statements in the block.
218 if (Block) FinishBlock(B);
220 // Backpatch the gotos whose label -> block mappings we didn't know when we
222 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
223 E = BackpatchBlocks.end(); I != E; ++I ) {
226 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
227 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
229 // If there is no target for the goto, then we are looking at an
230 // incomplete AST. Handle this by not registering a successor.
231 if (LI == LabelMap.end()) continue;
233 AddSuccessor(B, LI->second);
236 // Add successors to the Indirect Goto Dispatch block (if we have one).
237 if (CFGBlock* B = cfg->getIndirectGotoBlock())
238 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
239 E = AddressTakenLabels.end(); I != E; ++I ) {
241 // Lookup the target block.
242 LabelMapTy::iterator LI = LabelMap.find(*I);
244 // If there is no target block that contains label, then we are looking
245 // at an incomplete AST. Handle this by not registering a successor.
246 if (LI == LabelMap.end()) continue;
248 AddSuccessor(B, LI->second);
254 // Create an empty entry block that has no predecessors.
255 cfg->setEntry(createBlock());
263 // NULL out cfg so that repeated calls to the builder will fail and that the
264 // ownership of the constructed CFG is passed to the caller.
270 /// createBlock - Used to lazily create blocks that are connected
271 /// to the current (global) succcessor.
272 CFGBlock* CFGBuilder::createBlock(bool add_successor) {
273 CFGBlock* B = cfg->createBlock();
274 if (add_successor && Succ)
275 AddSuccessor(B, Succ);
279 /// FinishBlock - "Finalize" the block by checking if we have a bad CFG.
280 bool CFGBuilder::FinishBlock(CFGBlock* B) {
288 /// Visit - Walk the subtree of a statement and add extra
289 /// blocks for ternary operators, &&, and ||. We also process "," and
290 /// DeclStmts (which may contain nested control-flow).
291 CFGBlock* CFGBuilder::Visit(Stmt * S, bool alwaysAdd) {
293 switch (S->getStmtClass()) {
295 return VisitStmt(S, alwaysAdd);
297 case Stmt::AddrLabelExprClass:
298 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), alwaysAdd);
300 case Stmt::BinaryOperatorClass:
301 return VisitBinaryOperator(cast<BinaryOperator>(S), alwaysAdd);
303 case Stmt::BlockExprClass:
304 return VisitBlockExpr(cast<BlockExpr>(S), alwaysAdd);
306 case Stmt::BlockDeclRefExprClass:
307 return VisitBlockDeclRefExpr(cast<BlockDeclRefExpr>(S), alwaysAdd);
309 case Stmt::BreakStmtClass:
310 return VisitBreakStmt(cast<BreakStmt>(S));
312 case Stmt::CallExprClass:
313 return VisitCallExpr(cast<CallExpr>(S), alwaysAdd);
315 case Stmt::CaseStmtClass:
316 return VisitCaseStmt(cast<CaseStmt>(S));
318 case Stmt::ChooseExprClass:
319 return VisitChooseExpr(cast<ChooseExpr>(S));
321 case Stmt::CompoundStmtClass:
322 return VisitCompoundStmt(cast<CompoundStmt>(S));
324 case Stmt::ConditionalOperatorClass:
325 return VisitConditionalOperator(cast<ConditionalOperator>(S));
327 case Stmt::ContinueStmtClass:
328 return VisitContinueStmt(cast<ContinueStmt>(S));
330 case Stmt::DeclStmtClass:
331 return VisitDeclStmt(cast<DeclStmt>(S));
333 case Stmt::DefaultStmtClass:
334 return VisitDefaultStmt(cast<DefaultStmt>(S));
336 case Stmt::DoStmtClass:
337 return VisitDoStmt(cast<DoStmt>(S));
339 case Stmt::ForStmtClass:
340 return VisitForStmt(cast<ForStmt>(S));
342 case Stmt::GotoStmtClass:
343 return VisitGotoStmt(cast<GotoStmt>(S));
345 case Stmt::IfStmtClass:
346 return VisitIfStmt(cast<IfStmt>(S));
348 case Stmt::IndirectGotoStmtClass:
349 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
351 case Stmt::LabelStmtClass:
352 return VisitLabelStmt(cast<LabelStmt>(S));
354 case Stmt::ObjCAtCatchStmtClass:
355 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
357 case Stmt::CXXThrowExprClass:
358 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
360 case Stmt::ObjCAtSynchronizedStmtClass:
361 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
363 case Stmt::ObjCAtThrowStmtClass:
364 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
366 case Stmt::ObjCAtTryStmtClass:
367 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
369 case Stmt::ObjCForCollectionStmtClass:
370 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
372 case Stmt::ParenExprClass:
373 S = cast<ParenExpr>(S)->getSubExpr();
376 case Stmt::NullStmtClass:
379 case Stmt::ReturnStmtClass:
380 return VisitReturnStmt(cast<ReturnStmt>(S));
382 case Stmt::SizeOfAlignOfExprClass:
383 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), alwaysAdd);
385 case Stmt::StmtExprClass:
386 return VisitStmtExpr(cast<StmtExpr>(S), alwaysAdd);
388 case Stmt::SwitchStmtClass:
389 return VisitSwitchStmt(cast<SwitchStmt>(S));
391 case Stmt::WhileStmtClass:
392 return VisitWhileStmt(cast<WhileStmt>(S));
396 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, bool alwaysAdd) {
399 AppendStmt(Block, S);
402 return VisitChildren(S);
405 /// VisitChildren - Visit the children of a Stmt.
406 CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
408 for (Stmt::child_iterator I = Terminator->child_begin(),
409 E = Terminator->child_end(); I != E; ++I) {
410 if (*I) B = Visit(*I);
415 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) {
416 AddressTakenLabels.insert(A->getLabel());
420 AppendStmt(Block, A);
426 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) {
427 if (B->isLogicalOp()) { // && or ||
428 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
429 AppendStmt(ConfluenceBlock, B);
431 if (!FinishBlock(ConfluenceBlock))
434 // create the block evaluating the LHS
435 CFGBlock* LHSBlock = createBlock(false);
436 LHSBlock->setTerminator(B);
438 // create the block evaluating the RHS
439 Succ = ConfluenceBlock;
441 CFGBlock* RHSBlock = addStmt(B->getRHS());
442 if (!FinishBlock(RHSBlock))
445 // See if this is a known constant.
446 TryResult KnownVal = TryEvaluateBool(B->getLHS());
447 if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr))
450 // Now link the LHSBlock with RHSBlock.
451 if (B->getOpcode() == BinaryOperator::LOr) {
452 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
453 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
455 assert (B->getOpcode() == BinaryOperator::LAnd);
456 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
457 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
460 // Generate the blocks for evaluating the LHS.
462 return addStmt(B->getLHS());
464 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
466 AppendStmt(Block, B);
467 addStmt(B->getRHS());
468 return addStmt(B->getLHS());
471 return VisitStmt(B, alwaysAdd);
474 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr* E, bool alwaysAdd) {
479 CFGBlock *CFGBuilder::VisitBlockDeclRefExpr(BlockDeclRefExpr* E,
485 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
486 // "break" is a control-flow statement. Thus we stop processing the current
488 if (Block && !FinishBlock(Block))
491 // Now create a new block that ends with the break statement.
492 Block = createBlock(false);
493 Block->setTerminator(B);
495 // If there is no target for the break, then we are looking at an incomplete
496 // AST. This means that the CFG cannot be constructed.
497 if (BreakTargetBlock)
498 AddSuccessor(Block, BreakTargetBlock);
506 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) {
507 // If this is a call to a no-return function, this stops the block here.
508 bool NoReturn = false;
509 if (C->getCallee()->getType().getNoReturnAttr()) {
513 if (FunctionDecl *FD = C->getDirectCallee())
514 if (FD->hasAttr<NoReturnAttr>())
518 return VisitStmt(C, alwaysAdd);
520 if (Block && !FinishBlock(Block))
523 // Create new block with no successor for the remaining pieces.
524 Block = createBlock(false);
525 AppendStmt(Block, C);
527 // Wire this to the exit block directly.
528 AddSuccessor(Block, &cfg->getExit());
530 return VisitChildren(C);
533 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C) {
534 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
535 AppendStmt(ConfluenceBlock, C);
536 if (!FinishBlock(ConfluenceBlock))
539 Succ = ConfluenceBlock;
541 CFGBlock* LHSBlock = addStmt(C->getLHS());
542 if (!FinishBlock(LHSBlock))
545 Succ = ConfluenceBlock;
547 CFGBlock* RHSBlock = addStmt(C->getRHS());
548 if (!FinishBlock(RHSBlock))
551 Block = createBlock(false);
552 // See if this is a known constant.
553 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
554 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
555 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
556 Block->setTerminator(C);
557 return addStmt(C->getCond());
561 CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
562 CFGBlock* LastBlock = Block;
564 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
566 LastBlock = addStmt(*I);
574 CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) {
575 // Create the confluence block that will "merge" the results of the ternary
577 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
578 AppendStmt(ConfluenceBlock, C);
579 if (!FinishBlock(ConfluenceBlock))
582 // Create a block for the LHS expression if there is an LHS expression. A
583 // GCC extension allows LHS to be NULL, causing the condition to be the
584 // value that is returned instead.
585 // e.g: x ?: y is shorthand for: x ? x : y;
586 Succ = ConfluenceBlock;
588 CFGBlock* LHSBlock = NULL;
590 LHSBlock = addStmt(C->getLHS());
591 if (!FinishBlock(LHSBlock))
596 // Create the block for the RHS expression.
597 Succ = ConfluenceBlock;
598 CFGBlock* RHSBlock = addStmt(C->getRHS());
599 if (!FinishBlock(RHSBlock))
602 // Create the block that will contain the condition.
603 Block = createBlock(false);
605 // See if this is a known constant.
606 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
608 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
610 if (KnownVal.isFalse()) {
611 // If we know the condition is false, add NULL as the successor for
612 // the block containing the condition. In this case, the confluence
613 // block will have just one predecessor.
614 AddSuccessor(Block, 0);
615 assert(ConfluenceBlock->pred_size() == 1);
617 // If we have no LHS expression, add the ConfluenceBlock as a direct
618 // successor for the block containing the condition. Moreover, we need to
619 // reverse the order of the predecessors in the ConfluenceBlock because
620 // the RHSBlock will have been added to the succcessors already, and we
621 // want the first predecessor to the the block containing the expression
622 // for the case when the ternary expression evaluates to true.
623 AddSuccessor(Block, ConfluenceBlock);
624 assert(ConfluenceBlock->pred_size() == 2);
625 std::reverse(ConfluenceBlock->pred_begin(),
626 ConfluenceBlock->pred_end());
630 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
631 Block->setTerminator(C);
632 return addStmt(C->getCond());
635 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
638 if (DS->isSingleDecl()) {
639 AppendStmt(Block, DS);
640 return VisitDeclSubExpr(DS->getSingleDecl());
645 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
646 typedef llvm::SmallVector<Decl*,10> BufTy;
647 BufTy Buf(DS->decl_begin(), DS->decl_end());
649 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
650 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
651 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
652 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
654 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
655 // automatically freed with the CFG.
658 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
659 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
661 // Append the fake DeclStmt to block.
662 AppendStmt(Block, DSNew);
663 B = VisitDeclSubExpr(D);
669 /// VisitDeclSubExpr - Utility method to add block-level expressions for
670 /// initializers in Decls.
671 CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
674 VarDecl *VD = dyn_cast<VarDecl>(D);
679 Expr *Init = VD->getInit();
682 // Optimization: Don't create separate block-level statements for literals.
683 switch (Init->getStmtClass()) {
684 case Stmt::IntegerLiteralClass:
685 case Stmt::CharacterLiteralClass:
686 case Stmt::StringLiteralClass:
689 Block = addStmt(Init);
693 // If the type of VD is a VLA, then we must process its size expressions.
694 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
695 VA = FindVA(VA->getElementType().getTypePtr()))
696 Block = addStmt(VA->getSizeExpr());
701 CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
702 // We may see an if statement in the middle of a basic block, or it may be the
703 // first statement we are processing. In either case, we create a new basic
704 // block. First, we create the blocks for the then...else statements, and
705 // then we create the block containing the if statement. If we were in the
706 // middle of a block, we stop processing that block. That block is then the
707 // implicit successor for the "then" and "else" clauses.
709 // The block we were proccessing is now finished. Make it the successor
713 if (!FinishBlock(Block))
717 // Process the false branch.
718 CFGBlock* ElseBlock = Succ;
720 if (Stmt* Else = I->getElse()) {
721 SaveAndRestore<CFGBlock*> sv(Succ);
723 // NULL out Block so that the recursive call to Visit will
724 // create a new basic block.
726 ElseBlock = addStmt(Else);
728 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
729 ElseBlock = sv.get();
731 if (!FinishBlock(ElseBlock))
736 // Process the true branch.
739 Stmt* Then = I->getThen();
741 SaveAndRestore<CFGBlock*> sv(Succ);
743 ThenBlock = addStmt(Then);
746 // We can reach here if the "then" body has all NullStmts.
747 // Create an empty block so we can distinguish between true and false
748 // branches in path-sensitive analyses.
749 ThenBlock = createBlock(false);
750 AddSuccessor(ThenBlock, sv.get());
752 if (!FinishBlock(ThenBlock))
757 // Now create a new block containing the if statement.
758 Block = createBlock(false);
760 // Set the terminator of the new block to the If statement.
761 Block->setTerminator(I);
763 // See if this is a known constant.
764 const TryResult &KnownVal = TryEvaluateBool(I->getCond());
766 // Now add the successors.
767 AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
768 AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
770 // Add the condition as the last statement in the new block. This may create
771 // new blocks as the condition may contain control-flow. Any newly created
772 // blocks will be pointed to be "Block".
773 return addStmt(I->getCond());
777 CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
778 // If we were in the middle of a block we stop processing that block.
780 // NOTE: If a "return" appears in the middle of a block, this means that the
781 // code afterwards is DEAD (unreachable). We still keep a basic block
782 // for that code; a simple "mark-and-sweep" from the entry block will be
783 // able to report such dead blocks.
787 // Create the new block.
788 Block = createBlock(false);
790 // The Exit block is the only successor.
791 AddSuccessor(Block, &cfg->getExit());
793 // Add the return statement to the block. This may create new blocks if R
794 // contains control-flow (short-circuit operations).
795 return VisitStmt(R, true);
798 CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
799 // Get the block of the labeled statement. Add it to our map.
800 addStmt(L->getSubStmt());
801 CFGBlock* LabelBlock = Block;
803 if (!LabelBlock) // This can happen when the body is empty, i.e.
804 LabelBlock = createBlock(); // scopes that only contains NullStmts.
806 assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
807 LabelMap[ L ] = LabelBlock;
809 // Labels partition blocks, so this is the end of the basic block we were
810 // processing (L is the block's label). Because this is label (and we have
811 // already processed the substatement) there is no extra control-flow to worry
813 LabelBlock->setLabel(L);
814 if (!FinishBlock(LabelBlock))
817 // We set Block to NULL to allow lazy creation of a new block (if necessary);
820 // This block is now the implicit successor of other blocks.
826 CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
827 // Goto is a control-flow statement. Thus we stop processing the current
828 // block and create a new one.
832 Block = createBlock(false);
833 Block->setTerminator(G);
835 // If we already know the mapping to the label block add the successor now.
836 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
838 if (I == LabelMap.end())
839 // We will need to backpatch this block later.
840 BackpatchBlocks.push_back(Block);
842 AddSuccessor(Block, I->second);
847 CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
848 CFGBlock* LoopSuccessor = NULL;
850 // "for" is a control-flow statement. Thus we stop processing the current
853 if (!FinishBlock(Block))
855 LoopSuccessor = Block;
857 LoopSuccessor = Succ;
859 // Because of short-circuit evaluation, the condition of the loop can span
860 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
861 // evaluate the condition.
862 CFGBlock* ExitConditionBlock = createBlock(false);
863 CFGBlock* EntryConditionBlock = ExitConditionBlock;
865 // Set the terminator for the "exit" condition block.
866 ExitConditionBlock->setTerminator(F);
868 // Now add the actual condition to the condition block. Because the condition
869 // itself may contain control-flow, new blocks may be created.
870 if (Stmt* C = F->getCond()) {
871 Block = ExitConditionBlock;
872 EntryConditionBlock = addStmt(C);
874 if (!FinishBlock(EntryConditionBlock))
879 // The condition block is the implicit successor for the loop body as well as
880 // any code above the loop.
881 Succ = EntryConditionBlock;
883 // See if this is a known constant.
884 TryResult KnownVal(true);
887 KnownVal = TryEvaluateBool(F->getCond());
889 // Now create the loop body.
891 assert (F->getBody());
893 // Save the current values for Block, Succ, and continue and break targets
894 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
895 save_continue(ContinueTargetBlock),
896 save_break(BreakTargetBlock);
898 // Create a new block to contain the (bottom) of the loop body.
901 if (Stmt* I = F->getInc()) {
902 // Generate increment code in its own basic block. This is the target of
903 // continue statements.
906 // No increment code. Create a special, empty, block that is used as the
907 // target block for "looping back" to the start of the loop.
908 assert(Succ == EntryConditionBlock);
909 Succ = createBlock();
912 // Finish up the increment (or empty) block if it hasn't been already.
914 assert(Block == Succ);
915 if (!FinishBlock(Block))
920 ContinueTargetBlock = Succ;
922 // The starting block for the loop increment is the block that should
923 // represent the 'loop target' for looping back to the start of the loop.
924 ContinueTargetBlock->setLoopTarget(F);
926 // All breaks should go to the code following the loop.
927 BreakTargetBlock = LoopSuccessor;
929 // Now populate the body block, and in the process create new blocks as we
930 // walk the body of the loop.
931 CFGBlock* BodyBlock = addStmt(F->getBody());
934 BodyBlock = ContinueTargetBlock; // can happen for "for (...;...;...) ;"
935 else if (Block && !FinishBlock(BodyBlock))
938 // This new body block is a successor to our "exit" condition block.
939 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
942 // Link up the condition block with the code that follows the loop. (the
944 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
946 // If the loop contains initialization, create a new block for those
947 // statements. This block can also contain statements that precede the loop.
948 if (Stmt* I = F->getInit()) {
949 Block = createBlock();
952 // There is no loop initialization. We are thus basically a while loop.
953 // NULL out Block to force lazy block construction.
955 Succ = EntryConditionBlock;
956 return EntryConditionBlock;
960 CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
961 // Objective-C fast enumeration 'for' statements:
962 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
964 // for ( Type newVariable in collection_expression ) { statements }
969 // 1. collection_expression
970 // T. jump to loop_entry
972 // 1. side-effects of element expression
973 // 1. ObjCForCollectionStmt [performs binding to newVariable]
974 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
977 // T. jump to loop_entry
983 // Type existingItem;
984 // for ( existingItem in expression ) { statements }
988 // the same with newVariable replaced with existingItem; the binding works
989 // the same except that for one ObjCForCollectionStmt::getElement() returns
990 // a DeclStmt and the other returns a DeclRefExpr.
993 CFGBlock* LoopSuccessor = 0;
996 if (!FinishBlock(Block))
998 LoopSuccessor = Block;
1001 LoopSuccessor = Succ;
1003 // Build the condition blocks.
1004 CFGBlock* ExitConditionBlock = createBlock(false);
1005 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1007 // Set the terminator for the "exit" condition block.
1008 ExitConditionBlock->setTerminator(S);
1010 // The last statement in the block should be the ObjCForCollectionStmt, which
1011 // performs the actual binding to 'element' and determines if there are any
1012 // more items in the collection.
1013 AppendStmt(ExitConditionBlock, S);
1014 Block = ExitConditionBlock;
1016 // Walk the 'element' expression to see if there are any side-effects. We
1017 // generate new blocks as necesary. We DON'T add the statement by default to
1018 // the CFG unless it contains control-flow.
1019 EntryConditionBlock = Visit(S->getElement(), false);
1021 if (!FinishBlock(EntryConditionBlock))
1026 // The condition block is the implicit successor for the loop body as well as
1027 // any code above the loop.
1028 Succ = EntryConditionBlock;
1030 // Now create the true branch.
1032 // Save the current values for Succ, continue and break targets.
1033 SaveAndRestore<CFGBlock*> save_Succ(Succ),
1034 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
1036 BreakTargetBlock = LoopSuccessor;
1037 ContinueTargetBlock = EntryConditionBlock;
1039 CFGBlock* BodyBlock = addStmt(S->getBody());
1042 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1044 if (!FinishBlock(BodyBlock))
1048 // This new body block is a successor to our "exit" condition block.
1049 AddSuccessor(ExitConditionBlock, BodyBlock);
1052 // Link up the condition block with the code that follows the loop.
1053 // (the false branch).
1054 AddSuccessor(ExitConditionBlock, LoopSuccessor);
1056 // Now create a prologue block to contain the collection expression.
1057 Block = createBlock();
1058 return addStmt(S->getCollection());
1061 CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1062 // FIXME: Add locking 'primitives' to CFG for @synchronized.
1065 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1067 // The sync body starts its own basic block. This makes it a little easier
1068 // for diagnostic clients.
1070 if (!FinishBlock(SyncBlock))
1078 // Inline the sync expression.
1079 return addStmt(S->getSynchExpr());
1082 CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1087 CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1088 CFGBlock* LoopSuccessor = NULL;
1090 // "while" is a control-flow statement. Thus we stop processing the current
1093 if (!FinishBlock(Block))
1095 LoopSuccessor = Block;
1097 LoopSuccessor = Succ;
1099 // Because of short-circuit evaluation, the condition of the loop can span
1100 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1101 // evaluate the condition.
1102 CFGBlock* ExitConditionBlock = createBlock(false);
1103 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1105 // Set the terminator for the "exit" condition block.
1106 ExitConditionBlock->setTerminator(W);
1108 // Now add the actual condition to the condition block. Because the condition
1109 // itself may contain control-flow, new blocks may be created. Thus we update
1110 // "Succ" after adding the condition.
1111 if (Stmt* C = W->getCond()) {
1112 Block = ExitConditionBlock;
1113 EntryConditionBlock = addStmt(C);
1114 assert(Block == EntryConditionBlock);
1116 if (!FinishBlock(EntryConditionBlock))
1121 // The condition block is the implicit successor for the loop body as well as
1122 // any code above the loop.
1123 Succ = EntryConditionBlock;
1125 // See if this is a known constant.
1126 const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1128 // Process the loop body.
1130 assert(W->getBody());
1132 // Save the current values for Block, Succ, and continue and break targets
1133 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1134 save_continue(ContinueTargetBlock),
1135 save_break(BreakTargetBlock);
1137 // Create an empty block to represent the transition block for looping back
1138 // to the head of the loop.
1140 assert(Succ == EntryConditionBlock);
1141 Succ = createBlock();
1142 Succ->setLoopTarget(W);
1143 ContinueTargetBlock = Succ;
1145 // All breaks should go to the code following the loop.
1146 BreakTargetBlock = LoopSuccessor;
1148 // NULL out Block to force lazy instantiation of blocks for the body.
1151 // Create the body. The returned block is the entry to the loop body.
1152 CFGBlock* BodyBlock = addStmt(W->getBody());
1155 BodyBlock = ContinueTargetBlock; // can happen for "while(...) ;"
1157 if (!FinishBlock(BodyBlock))
1161 // Add the loop body entry as a successor to the condition.
1162 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1165 // Link up the condition block with the code that follows the loop. (the
1167 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1169 // There can be no more statements in the condition block since we loop back
1170 // to this block. NULL out Block to force lazy creation of another block.
1173 // Return the condition block, which is the dominating block for the loop.
1174 Succ = EntryConditionBlock;
1175 return EntryConditionBlock;
1179 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1180 // FIXME: For now we pretend that @catch and the code it contains does not
1185 CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1186 // FIXME: This isn't complete. We basically treat @throw like a return
1189 // If we were in the middle of a block we stop processing that block.
1190 if (Block && !FinishBlock(Block))
1193 // Create the new block.
1194 Block = createBlock(false);
1196 // The Exit block is the only successor.
1197 AddSuccessor(Block, &cfg->getExit());
1199 // Add the statement to the block. This may create new blocks if S contains
1200 // control-flow (short-circuit operations).
1201 return VisitStmt(S, true);
1204 CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1205 // If we were in the middle of a block we stop processing that block.
1206 if (Block && !FinishBlock(Block))
1209 // Create the new block.
1210 Block = createBlock(false);
1212 // The Exit block is the only successor.
1213 AddSuccessor(Block, &cfg->getExit());
1215 // Add the statement to the block. This may create new blocks if S contains
1216 // control-flow (short-circuit operations).
1217 return VisitStmt(T, true);
1220 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1221 CFGBlock* LoopSuccessor = NULL;
1223 // "do...while" is a control-flow statement. Thus we stop processing the
1226 if (!FinishBlock(Block))
1228 LoopSuccessor = Block;
1230 LoopSuccessor = Succ;
1232 // Because of short-circuit evaluation, the condition of the loop can span
1233 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1234 // evaluate the condition.
1235 CFGBlock* ExitConditionBlock = createBlock(false);
1236 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1238 // Set the terminator for the "exit" condition block.
1239 ExitConditionBlock->setTerminator(D);
1241 // Now add the actual condition to the condition block. Because the condition
1242 // itself may contain control-flow, new blocks may be created.
1243 if (Stmt* C = D->getCond()) {
1244 Block = ExitConditionBlock;
1245 EntryConditionBlock = addStmt(C);
1247 if (!FinishBlock(EntryConditionBlock))
1252 // The condition block is the implicit successor for the loop body.
1253 Succ = EntryConditionBlock;
1255 // See if this is a known constant.
1256 const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1258 // Process the loop body.
1259 CFGBlock* BodyBlock = NULL;
1261 assert (D->getBody());
1263 // Save the current values for Block, Succ, and continue and break targets
1264 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1265 save_continue(ContinueTargetBlock),
1266 save_break(BreakTargetBlock);
1268 // All continues within this loop should go to the condition block
1269 ContinueTargetBlock = EntryConditionBlock;
1271 // All breaks should go to the code following the loop.
1272 BreakTargetBlock = LoopSuccessor;
1274 // NULL out Block to force lazy instantiation of blocks for the body.
1277 // Create the body. The returned block is the entry to the loop body.
1278 BodyBlock = addStmt(D->getBody());
1281 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1283 if (!FinishBlock(BodyBlock))
1287 // Add an intermediate block between the BodyBlock and the
1288 // ExitConditionBlock to represent the "loop back" transition. Create an
1289 // empty block to represent the transition block for looping back to the
1290 // head of the loop.
1291 // FIXME: Can we do this more efficiently without adding another block?
1294 CFGBlock *LoopBackBlock = createBlock();
1295 LoopBackBlock->setLoopTarget(D);
1297 // Add the loop body entry as a successor to the condition.
1298 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : LoopBackBlock);
1301 // Link up the condition block with the code that follows the loop.
1302 // (the false branch).
1303 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1305 // There can be no more statements in the body block(s) since we loop back to
1306 // the body. NULL out Block to force lazy creation of another block.
1309 // Return the loop body, which is the dominating block for the loop.
1314 CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1315 // "continue" is a control-flow statement. Thus we stop processing the
1317 if (Block && !FinishBlock(Block))
1320 // Now create a new block that ends with the continue statement.
1321 Block = createBlock(false);
1322 Block->setTerminator(C);
1324 // If there is no target for the continue, then we are looking at an
1325 // incomplete AST. This means the CFG cannot be constructed.
1326 if (ContinueTargetBlock)
1327 AddSuccessor(Block, ContinueTargetBlock);
1334 CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1339 AppendStmt(Block, E);
1342 // VLA types have expressions that must be evaluated.
1343 if (E->isArgumentType()) {
1344 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1345 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1346 addStmt(VA->getSizeExpr());
1352 /// VisitStmtExpr - Utility method to handle (nested) statement
1353 /// expressions (a GCC extension).
1354 CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, bool alwaysAdd) {
1357 AppendStmt(Block, SE);
1359 return VisitCompoundStmt(SE->getSubStmt());
1362 CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1363 // "switch" is a control-flow statement. Thus we stop processing the current
1365 CFGBlock* SwitchSuccessor = NULL;
1368 if (!FinishBlock(Block))
1370 SwitchSuccessor = Block;
1371 } else SwitchSuccessor = Succ;
1373 // Save the current "switch" context.
1374 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1375 save_break(BreakTargetBlock),
1376 save_default(DefaultCaseBlock);
1378 // Set the "default" case to be the block after the switch statement. If the
1379 // switch statement contains a "default:", this value will be overwritten with
1380 // the block for that code.
1381 DefaultCaseBlock = SwitchSuccessor;
1383 // Create a new block that will contain the switch statement.
1384 SwitchTerminatedBlock = createBlock(false);
1386 // Now process the switch body. The code after the switch is the implicit
1388 Succ = SwitchSuccessor;
1389 BreakTargetBlock = SwitchSuccessor;
1391 // When visiting the body, the case statements should automatically get linked
1392 // up to the switch. We also don't keep a pointer to the body, since all
1393 // control-flow from the switch goes to case/default statements.
1394 assert (Terminator->getBody() && "switch must contain a non-NULL body");
1396 CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1398 if (!FinishBlock(BodyBlock))
1402 // If we have no "default:" case, the default transition is to the code
1403 // following the switch body.
1404 AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
1406 // Add the terminator and condition in the switch block.
1407 SwitchTerminatedBlock->setTerminator(Terminator);
1408 assert (Terminator->getCond() && "switch condition must be non-NULL");
1409 Block = SwitchTerminatedBlock;
1411 return addStmt(Terminator->getCond());
1414 CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1415 // CaseStmts are essentially labels, so they are the first statement in a
1418 if (CS->getSubStmt())
1419 addStmt(CS->getSubStmt());
1421 CFGBlock* CaseBlock = Block;
1423 CaseBlock = createBlock();
1425 // Cases statements partition blocks, so this is the top of the basic block we
1426 // were processing (the "case XXX:" is the label).
1427 CaseBlock->setLabel(CS);
1429 if (!FinishBlock(CaseBlock))
1432 // Add this block to the list of successors for the block with the switch
1434 assert(SwitchTerminatedBlock);
1435 AddSuccessor(SwitchTerminatedBlock, CaseBlock);
1437 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1440 // This block is now the implicit successor of other blocks.
1446 CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1447 if (Terminator->getSubStmt())
1448 addStmt(Terminator->getSubStmt());
1450 DefaultCaseBlock = Block;
1452 if (!DefaultCaseBlock)
1453 DefaultCaseBlock = createBlock();
1455 // Default statements partition blocks, so this is the top of the basic block
1456 // we were processing (the "default:" is the label).
1457 DefaultCaseBlock->setLabel(Terminator);
1459 if (!FinishBlock(DefaultCaseBlock))
1462 // Unlike case statements, we don't add the default block to the successors
1463 // for the switch statement immediately. This is done when we finish
1464 // processing the switch statement. This allows for the default case
1465 // (including a fall-through to the code after the switch statement) to always
1466 // be the last successor of a switch-terminated block.
1468 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1471 // This block is now the implicit successor of other blocks.
1472 Succ = DefaultCaseBlock;
1474 return DefaultCaseBlock;
1477 CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1478 // Lazily create the indirect-goto dispatch block if there isn't one already.
1479 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1482 IBlock = createBlock(false);
1483 cfg->setIndirectGotoBlock(IBlock);
1486 // IndirectGoto is a control-flow statement. Thus we stop processing the
1487 // current block and create a new one.
1488 if (Block && !FinishBlock(Block))
1491 Block = createBlock(false);
1492 Block->setTerminator(I);
1493 AddSuccessor(Block, IBlock);
1494 return addStmt(I->getTarget());
1497 } // end anonymous namespace
1499 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
1500 /// no successors or predecessors. If this is the first block created in the
1501 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
1502 CFGBlock* CFG::createBlock() {
1503 bool first_block = begin() == end();
1505 // Create the block.
1506 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
1507 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
1508 Blocks.push_back(Mem, BlkBVC);
1510 // If this is the first block, set it as the Entry and Exit.
1512 Entry = Exit = &back();
1514 // Return the block.
1518 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1519 /// CFG is returned to the caller.
1520 CFG* CFG::buildCFG(Stmt* Statement, ASTContext *C) {
1522 return Builder.buildCFG(Statement, C);
1525 //===----------------------------------------------------------------------===//
1526 // CFG: Queries for BlkExprs.
1527 //===----------------------------------------------------------------------===//
1530 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1533 static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1537 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
1540 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1541 if (B->isAssignmentOp()) Set.insert(B);
1543 FindSubExprAssignments(*I, Set);
1547 static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1548 BlkExprMapTy* M = new BlkExprMapTy();
1550 // Look for assignments that are used as subexpressions. These are the only
1551 // assignments that we want to *possibly* register as a block-level
1552 // expression. Basically, if an assignment occurs both in a subexpression and
1553 // at the block-level, it is a block-level expression.
1554 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1556 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1557 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1558 FindSubExprAssignments(*BI, SubExprAssignments);
1560 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1562 // Iterate over the statements again on identify the Expr* and Stmt* at the
1563 // block-level that are block-level expressions.
1565 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1566 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1568 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1569 // Assignment expressions that are not nested within another
1570 // expression are really "statements" whose value is never used by
1571 // another expression.
1572 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1574 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1575 // Special handling for statement expressions. The last statement in
1576 // the statement expression is also a block-level expr.
1577 const CompoundStmt* C = Terminator->getSubStmt();
1578 if (!C->body_empty()) {
1579 unsigned x = M->size();
1580 (*M)[C->body_back()] = x;
1584 unsigned x = M->size();
1588 // Look at terminators. The condition is a block-level expression.
1590 Stmt* S = (*I)->getTerminatorCondition();
1592 if (S && M->find(S) == M->end()) {
1593 unsigned x = M->size();
1601 CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1603 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1605 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1606 BlkExprMapTy::iterator I = M->find(S);
1608 if (I == M->end()) return CFG::BlkExprNumTy();
1609 else return CFG::BlkExprNumTy(I->second);
1612 unsigned CFG::getNumBlkExprs() {
1613 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1616 // We assume callers interested in the number of BlkExprs will want
1617 // the map constructed if it doesn't already exist.
1618 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1619 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1623 //===----------------------------------------------------------------------===//
1624 // Cleanup: CFG dstor.
1625 //===----------------------------------------------------------------------===//
1628 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1631 //===----------------------------------------------------------------------===//
1632 // CFG pretty printing
1633 //===----------------------------------------------------------------------===//
1637 class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
1639 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1641 signed CurrentBlock;
1642 unsigned CurrentStmt;
1643 const LangOptions &LangOpts;
1646 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1647 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1648 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1650 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
1651 BI != BEnd; ++BI, ++j )
1652 StmtMap[*BI] = std::make_pair((*I)->getBlockID(),j);
1656 virtual ~StmtPrinterHelper() {}
1658 const LangOptions &getLangOpts() const { return LangOpts; }
1659 void setBlockID(signed i) { CurrentBlock = i; }
1660 void setStmtID(unsigned i) { CurrentStmt = i; }
1662 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1664 StmtMapTy::iterator I = StmtMap.find(Terminator);
1666 if (I == StmtMap.end())
1669 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1670 && I->second.second == CurrentStmt)
1673 OS << "[B" << I->second.first << "." << I->second.second << "]";
1677 } // end anonymous namespace
1681 class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1682 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1684 llvm::raw_ostream& OS;
1685 StmtPrinterHelper* Helper;
1686 PrintingPolicy Policy;
1689 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1690 const PrintingPolicy &Policy)
1691 : OS(os), Helper(helper), Policy(Policy) {}
1693 void VisitIfStmt(IfStmt* I) {
1695 I->getCond()->printPretty(OS,Helper,Policy);
1699 void VisitStmt(Stmt* Terminator) {
1700 Terminator->printPretty(OS, Helper, Policy);
1703 void VisitForStmt(ForStmt* F) {
1705 if (F->getInit()) OS << "...";
1707 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
1709 if (F->getInc()) OS << "...";
1713 void VisitWhileStmt(WhileStmt* W) {
1715 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
1718 void VisitDoStmt(DoStmt* D) {
1719 OS << "do ... while ";
1720 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
1723 void VisitSwitchStmt(SwitchStmt* Terminator) {
1725 Terminator->getCond()->printPretty(OS, Helper, Policy);
1728 void VisitConditionalOperator(ConditionalOperator* C) {
1729 C->getCond()->printPretty(OS, Helper, Policy);
1730 OS << " ? ... : ...";
1733 void VisitChooseExpr(ChooseExpr* C) {
1734 OS << "__builtin_choose_expr( ";
1735 C->getCond()->printPretty(OS, Helper, Policy);
1739 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1741 I->getTarget()->printPretty(OS, Helper, Policy);
1744 void VisitBinaryOperator(BinaryOperator* B) {
1745 if (!B->isLogicalOp()) {
1750 B->getLHS()->printPretty(OS, Helper, Policy);
1752 switch (B->getOpcode()) {
1753 case BinaryOperator::LOr:
1756 case BinaryOperator::LAnd:
1760 assert(false && "Invalid logical operator.");
1764 void VisitExpr(Expr* E) {
1765 E->printPretty(OS, Helper, Policy);
1768 } // end anonymous namespace
1771 static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1774 // special printing for statement-expressions.
1775 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
1776 CompoundStmt* Sub = SE->getSubStmt();
1778 if (Sub->child_begin() != Sub->child_end()) {
1780 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
1786 // special printing for comma expressions.
1787 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
1788 if (B->getOpcode() == BinaryOperator::Comma) {
1790 Helper->handledStmt(B->getRHS(),OS);
1797 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
1799 // Expressions need a newline.
1800 if (isa<Expr>(Terminator)) OS << '\n';
1803 static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
1805 StmtPrinterHelper* Helper, bool print_edges) {
1807 if (Helper) Helper->setBlockID(B.getBlockID());
1809 // Print the header.
1810 OS << "\n [ B" << B.getBlockID();
1812 if (&B == &cfg->getEntry())
1813 OS << " (ENTRY) ]\n";
1814 else if (&B == &cfg->getExit())
1815 OS << " (EXIT) ]\n";
1816 else if (&B == cfg->getIndirectGotoBlock())
1817 OS << " (INDIRECT GOTO DISPATCH) ]\n";
1821 // Print the label of this block.
1822 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
1827 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
1829 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
1831 C->getLHS()->printPretty(OS, Helper,
1832 PrintingPolicy(Helper->getLangOpts()));
1835 C->getRHS()->printPretty(OS, Helper,
1836 PrintingPolicy(Helper->getLangOpts()));
1838 } else if (isa<DefaultStmt>(Terminator))
1841 assert(false && "Invalid label statement in CFGBlock.");
1846 // Iterate through the statements in the block and print them.
1849 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1850 I != E ; ++I, ++j ) {
1852 // Print the statement # in the basic block and the statement itself.
1856 OS << llvm::format("%3d", j) << ": ";
1859 Helper->setStmtID(j);
1861 print_stmt(OS,Helper,*I);
1864 // Print the terminator of this block.
1865 if (B.getTerminator()) {
1871 if (Helper) Helper->setBlockID(-1);
1873 CFGBlockTerminatorPrint TPrinter(OS, Helper,
1874 PrintingPolicy(Helper->getLangOpts()));
1875 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
1880 // Print the predecessors of this block.
1881 OS << " Predecessors (" << B.pred_size() << "):";
1884 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1887 if (i == 8 || (i-8) == 0)
1890 OS << " B" << (*I)->getBlockID();
1895 // Print the successors of this block.
1896 OS << " Successors (" << B.succ_size() << "):";
1899 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1902 if (i == 8 || (i-8) % 10 == 0)
1906 OS << " B" << (*I)->getBlockID();
1916 /// dump - A simple pretty printer of a CFG that outputs to stderr.
1917 void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
1919 /// print - A simple pretty printer of a CFG that outputs to an ostream.
1920 void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
1921 StmtPrinterHelper Helper(this, LO);
1923 // Print the entry block.
1924 print_block(OS, this, getEntry(), &Helper, true);
1926 // Iterate through the CFGBlocks and print them one by one.
1927 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1928 // Skip the entry block, because we already printed it.
1929 if (&(**I) == &getEntry() || &(**I) == &getExit())
1932 print_block(OS, this, **I, &Helper, true);
1935 // Print the exit block.
1936 print_block(OS, this, getExit(), &Helper, true);
1940 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1941 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
1942 print(llvm::errs(), cfg, LO);
1945 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1946 /// Generally this will only be called from CFG::print.
1947 void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
1948 const LangOptions &LO) const {
1949 StmtPrinterHelper Helper(cfg, LO);
1950 print_block(OS, cfg, *this, &Helper, true);
1953 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1954 void CFGBlock::printTerminator(llvm::raw_ostream &OS,
1955 const LangOptions &LO) const {
1956 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
1957 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1960 Stmt* CFGBlock::getTerminatorCondition() {
1967 switch (Terminator->getStmtClass()) {
1971 case Stmt::ForStmtClass:
1972 E = cast<ForStmt>(Terminator)->getCond();
1975 case Stmt::WhileStmtClass:
1976 E = cast<WhileStmt>(Terminator)->getCond();
1979 case Stmt::DoStmtClass:
1980 E = cast<DoStmt>(Terminator)->getCond();
1983 case Stmt::IfStmtClass:
1984 E = cast<IfStmt>(Terminator)->getCond();
1987 case Stmt::ChooseExprClass:
1988 E = cast<ChooseExpr>(Terminator)->getCond();
1991 case Stmt::IndirectGotoStmtClass:
1992 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1995 case Stmt::SwitchStmtClass:
1996 E = cast<SwitchStmt>(Terminator)->getCond();
1999 case Stmt::ConditionalOperatorClass:
2000 E = cast<ConditionalOperator>(Terminator)->getCond();
2003 case Stmt::BinaryOperatorClass: // '&&' and '||'
2004 E = cast<BinaryOperator>(Terminator)->getLHS();
2007 case Stmt::ObjCForCollectionStmtClass:
2011 return E ? E->IgnoreParens() : NULL;
2014 bool CFGBlock::hasBinaryBranchTerminator() const {
2021 switch (Terminator->getStmtClass()) {
2025 case Stmt::ForStmtClass:
2026 case Stmt::WhileStmtClass:
2027 case Stmt::DoStmtClass:
2028 case Stmt::IfStmtClass:
2029 case Stmt::ChooseExprClass:
2030 case Stmt::ConditionalOperatorClass:
2031 case Stmt::BinaryOperatorClass:
2035 return E ? E->IgnoreParens() : NULL;
2039 //===----------------------------------------------------------------------===//
2040 // CFG Graphviz Visualization
2041 //===----------------------------------------------------------------------===//
2045 static StmtPrinterHelper* GraphHelper;
2048 void CFG::viewCFG(const LangOptions &LO) const {
2050 StmtPrinterHelper H(this, LO);
2052 llvm::ViewGraph(this,"CFG");
2059 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2060 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph,
2064 std::string OutSStr;
2065 llvm::raw_string_ostream Out(OutSStr);
2066 print_block(Out,Graph, *Node, GraphHelper, false);
2067 std::string& OutStr = Out.str();
2069 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
2071 // Process string output to make it nicer...
2072 for (unsigned i = 0; i != OutStr.length(); ++i)
2073 if (OutStr[i] == '\n') { // Left justify
2075 OutStr.insert(OutStr.begin()+i+1, 'l');
2084 } // end namespace llvm