Add include needed for MSVC.
[clang/acc.git] / lib / Analysis / CFG.cpp
blob5a9e61143214c416de459ea6d89412c8a480e0f3
1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/StmtVisitor.h"
17 #include "clang/AST/PrettyPrinter.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/Support/GraphWriter.h"
21 #include "llvm/Support/Streams.h"
22 #include "llvm/Support/Compiler.h"
23 #include <llvm/Support/Allocator.h>
24 #include <llvm/Support/Format.h>
26 using namespace clang;
28 namespace {
30 // SaveAndRestore - A utility class that uses RIIA to save and restore
31 // the value of a variable.
32 template<typename T>
33 struct VISIBILITY_HIDDEN SaveAndRestore {
34 SaveAndRestore(T& x) : X(x), old_value(x) {}
35 ~SaveAndRestore() { X = old_value; }
36 T get() { return old_value; }
38 T& X;
39 T old_value;
42 static SourceLocation GetEndLoc(Decl* D) {
43 if (VarDecl* VD = dyn_cast<VarDecl>(D))
44 if (Expr* Ex = VD->getInit())
45 return Ex->getSourceRange().getEnd();
47 return D->getLocation();
50 /// CFGBuilder - This class implements CFG construction from an AST.
51 /// The builder is stateful: an instance of the builder should be used to only
52 /// construct a single CFG.
53 ///
54 /// Example usage:
55 ///
56 /// CFGBuilder builder;
57 /// CFG* cfg = builder.BuildAST(stmt1);
58 ///
59 /// CFG construction is done via a recursive walk of an AST. We actually parse
60 /// the AST in reverse order so that the successor of a basic block is
61 /// constructed prior to its predecessor. This allows us to nicely capture
62 /// implicit fall-throughs without extra basic blocks.
63 ///
64 class VISIBILITY_HIDDEN CFGBuilder {
65 CFG* cfg;
66 CFGBlock* Block;
67 CFGBlock* Succ;
68 CFGBlock* ContinueTargetBlock;
69 CFGBlock* BreakTargetBlock;
70 CFGBlock* SwitchTerminatedBlock;
71 CFGBlock* DefaultCaseBlock;
73 // LabelMap records the mapping from Label expressions to their blocks.
74 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
75 LabelMapTy LabelMap;
77 // A list of blocks that end with a "goto" that must be backpatched to their
78 // resolved targets upon completion of CFG construction.
79 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
80 BackpatchBlocksTy BackpatchBlocks;
82 // A list of labels whose address has been taken (for indirect gotos).
83 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
84 LabelSetTy AddressTakenLabels;
86 public:
87 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
88 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
89 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
90 // Create an empty CFG.
91 cfg = new CFG();
94 ~CFGBuilder() { delete cfg; }
96 // buildCFG - Used by external clients to construct the CFG.
97 CFG* buildCFG(Stmt* Statement);
99 private:
100 // Visitors to walk an AST and construct the CFG.
101 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd);
102 CFGBlock *VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd);
103 CFGBlock *VisitBlockExpr(BlockExpr* E, bool alwaysAdd);
104 CFGBlock *VisitBlockDeclRefExpr(BlockDeclRefExpr* E, bool alwaysAdd);
105 CFGBlock *VisitBreakStmt(BreakStmt *B);
106 CFGBlock *VisitCallExpr(CallExpr *C, bool alwaysAdd);
107 CFGBlock *VisitCaseStmt(CaseStmt *C);
108 CFGBlock *VisitChooseExpr(ChooseExpr *C);
109 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
110 CFGBlock *VisitConditionalOperator(ConditionalOperator *C);
111 CFGBlock *VisitContinueStmt(ContinueStmt *C);
112 CFGBlock *VisitDeclStmt(DeclStmt *DS);
113 CFGBlock *VisitDeclSubExpr(Decl* D);
114 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
115 CFGBlock *VisitDoStmt(DoStmt *D);
116 CFGBlock *VisitForStmt(ForStmt *F);
117 CFGBlock *VisitGotoStmt(GotoStmt* G);
118 CFGBlock *VisitIfStmt(IfStmt *I);
119 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
120 CFGBlock *VisitLabelStmt(LabelStmt *L);
121 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
122 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
123 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
124 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
125 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
126 CFGBlock *VisitReturnStmt(ReturnStmt* R);
127 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, bool alwaysAdd);
128 CFGBlock *VisitStmtExpr(StmtExpr *S, bool alwaysAdd);
129 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
130 CFGBlock *VisitWhileStmt(WhileStmt *W);
132 CFGBlock *Visit(Stmt *S, bool alwaysAdd = false);
133 CFGBlock *VisitStmt(Stmt *S, bool alwaysAdd);
134 CFGBlock *VisitChildren(Stmt* S);
136 // NYS == Not Yet Supported
137 CFGBlock* NYS() {
138 badCFG = true;
139 return Block;
142 void autoCreateBlock() { if (!Block) Block = createBlock(); }
143 CFGBlock *createBlock(bool add_successor = true);
144 bool FinishBlock(CFGBlock* B);
145 CFGBlock *addStmt(Stmt *S) { return Visit(S, true); }
147 bool badCFG;
150 // FIXME: Add support for dependent-sized array types in C++?
151 // Does it even make sense to build a CFG for an uninstantiated template?
152 static VariableArrayType* FindVA(Type* t) {
153 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
154 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
155 if (vat->getSizeExpr())
156 return vat;
158 t = vt->getElementType().getTypePtr();
161 return 0;
164 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
165 /// arbitrary statement. Examples include a single expression or a function
166 /// body (compound statement). The ownership of the returned CFG is
167 /// transferred to the caller. If CFG construction fails, this method returns
168 /// NULL.
169 CFG* CFGBuilder::buildCFG(Stmt* Statement) {
170 assert(cfg);
171 if (!Statement)
172 return NULL;
174 badCFG = false;
176 // Create an empty block that will serve as the exit block for the CFG. Since
177 // this is the first block added to the CFG, it will be implicitly registered
178 // as the exit block.
179 Succ = createBlock();
180 assert (Succ == &cfg->getExit());
181 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
183 // Visit the statements and create the CFG.
184 CFGBlock* B = addStmt(Statement);
185 if (!B) B = Succ;
187 if (B) {
188 // Finalize the last constructed block. This usually involves reversing the
189 // order of the statements in the block.
190 if (Block) FinishBlock(B);
192 // Backpatch the gotos whose label -> block mappings we didn't know when we
193 // encountered them.
194 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
195 E = BackpatchBlocks.end(); I != E; ++I ) {
197 CFGBlock* B = *I;
198 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
199 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
201 // If there is no target for the goto, then we are looking at an
202 // incomplete AST. Handle this by not registering a successor.
203 if (LI == LabelMap.end()) continue;
205 B->addSuccessor(LI->second);
208 // Add successors to the Indirect Goto Dispatch block (if we have one).
209 if (CFGBlock* B = cfg->getIndirectGotoBlock())
210 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
211 E = AddressTakenLabels.end(); I != E; ++I ) {
213 // Lookup the target block.
214 LabelMapTy::iterator LI = LabelMap.find(*I);
216 // If there is no target block that contains label, then we are looking
217 // at an incomplete AST. Handle this by not registering a successor.
218 if (LI == LabelMap.end()) continue;
220 B->addSuccessor(LI->second);
223 Succ = B;
226 // Create an empty entry block that has no predecessors.
227 cfg->setEntry(createBlock());
229 if (badCFG) {
230 delete cfg;
231 cfg = NULL;
232 return NULL;
235 // NULL out cfg so that repeated calls to the builder will fail and that the
236 // ownership of the constructed CFG is passed to the caller.
237 CFG* t = cfg;
238 cfg = NULL;
239 return t;
242 /// createBlock - Used to lazily create blocks that are connected
243 /// to the current (global) succcessor.
244 CFGBlock* CFGBuilder::createBlock(bool add_successor) {
245 CFGBlock* B = cfg->createBlock();
246 if (add_successor && Succ)
247 B->addSuccessor(Succ);
248 return B;
251 /// FinishBlock - When the last statement has been added to the block, we must
252 /// reverse the statements because they have been inserted in reverse order.
253 bool CFGBuilder::FinishBlock(CFGBlock* B) {
254 if (badCFG)
255 return false;
257 assert(B);
258 B->reverseStmts();
259 return true;
262 /// Visit - Walk the subtree of a statement and add extra
263 /// blocks for ternary operators, &&, and ||. We also process "," and
264 /// DeclStmts (which may contain nested control-flow).
265 CFGBlock* CFGBuilder::Visit(Stmt * S, bool alwaysAdd) {
266 tryAgain:
267 switch (S->getStmtClass()) {
268 default:
269 return VisitStmt(S, alwaysAdd);
271 case Stmt::AddrLabelExprClass:
272 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), alwaysAdd);
274 case Stmt::BinaryOperatorClass:
275 return VisitBinaryOperator(cast<BinaryOperator>(S), alwaysAdd);
277 case Stmt::BlockExprClass:
278 return VisitBlockExpr(cast<BlockExpr>(S), alwaysAdd);
280 case Stmt::BlockDeclRefExprClass:
281 return VisitBlockDeclRefExpr(cast<BlockDeclRefExpr>(S), alwaysAdd);
283 case Stmt::BreakStmtClass:
284 return VisitBreakStmt(cast<BreakStmt>(S));
286 case Stmt::CallExprClass:
287 return VisitCallExpr(cast<CallExpr>(S), alwaysAdd);
289 case Stmt::CaseStmtClass:
290 return VisitCaseStmt(cast<CaseStmt>(S));
292 case Stmt::ChooseExprClass:
293 return VisitChooseExpr(cast<ChooseExpr>(S));
295 case Stmt::CompoundStmtClass:
296 return VisitCompoundStmt(cast<CompoundStmt>(S));
298 case Stmt::ConditionalOperatorClass:
299 return VisitConditionalOperator(cast<ConditionalOperator>(S));
301 case Stmt::ContinueStmtClass:
302 return VisitContinueStmt(cast<ContinueStmt>(S));
304 case Stmt::DeclStmtClass:
305 return VisitDeclStmt(cast<DeclStmt>(S));
307 case Stmt::DefaultStmtClass:
308 return VisitDefaultStmt(cast<DefaultStmt>(S));
310 case Stmt::DoStmtClass:
311 return VisitDoStmt(cast<DoStmt>(S));
313 case Stmt::ForStmtClass:
314 return VisitForStmt(cast<ForStmt>(S));
316 case Stmt::GotoStmtClass:
317 return VisitGotoStmt(cast<GotoStmt>(S));
319 case Stmt::IfStmtClass:
320 return VisitIfStmt(cast<IfStmt>(S));
322 case Stmt::IndirectGotoStmtClass:
323 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
325 case Stmt::LabelStmtClass:
326 return VisitLabelStmt(cast<LabelStmt>(S));
328 case Stmt::ObjCAtCatchStmtClass:
329 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
331 case Stmt::ObjCAtSynchronizedStmtClass:
332 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
334 case Stmt::ObjCAtThrowStmtClass:
335 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
337 case Stmt::ObjCAtTryStmtClass:
338 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
340 case Stmt::ObjCForCollectionStmtClass:
341 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
343 case Stmt::ParenExprClass:
344 S = cast<ParenExpr>(S)->getSubExpr();
345 goto tryAgain;
347 case Stmt::NullStmtClass:
348 return Block;
350 case Stmt::ReturnStmtClass:
351 return VisitReturnStmt(cast<ReturnStmt>(S));
353 case Stmt::SizeOfAlignOfExprClass:
354 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), alwaysAdd);
356 case Stmt::StmtExprClass:
357 return VisitStmtExpr(cast<StmtExpr>(S), alwaysAdd);
359 case Stmt::SwitchStmtClass:
360 return VisitSwitchStmt(cast<SwitchStmt>(S));
362 case Stmt::WhileStmtClass:
363 return VisitWhileStmt(cast<WhileStmt>(S));
367 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, bool alwaysAdd) {
368 if (alwaysAdd) {
369 autoCreateBlock();
370 Block->appendStmt(S);
373 return VisitChildren(S);
376 /// VisitChildren - Visit the children of a Stmt.
377 CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
378 CFGBlock *B = Block;
379 for (Stmt::child_iterator I = Terminator->child_begin(),
380 E = Terminator->child_end(); I != E; ++I) {
381 if (*I) B = Visit(*I);
383 return B;
386 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) {
387 AddressTakenLabels.insert(A->getLabel());
389 if (alwaysAdd) {
390 autoCreateBlock();
391 Block->appendStmt(A);
394 return Block;
397 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) {
398 if (B->isLogicalOp()) { // && or ||
400 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
401 ConfluenceBlock->appendStmt(B);
403 if (!FinishBlock(ConfluenceBlock))
404 return 0;
406 // create the block evaluating the LHS
407 CFGBlock* LHSBlock = createBlock(false);
408 LHSBlock->setTerminator(B);
410 // create the block evaluating the RHS
411 Succ = ConfluenceBlock;
412 Block = NULL;
413 CFGBlock* RHSBlock = addStmt(B->getRHS());
414 if (!FinishBlock(RHSBlock))
415 return 0;
417 // Now link the LHSBlock with RHSBlock.
418 if (B->getOpcode() == BinaryOperator::LOr) {
419 LHSBlock->addSuccessor(ConfluenceBlock);
420 LHSBlock->addSuccessor(RHSBlock);
421 } else {
422 assert (B->getOpcode() == BinaryOperator::LAnd);
423 LHSBlock->addSuccessor(RHSBlock);
424 LHSBlock->addSuccessor(ConfluenceBlock);
427 // Generate the blocks for evaluating the LHS.
428 Block = LHSBlock;
429 return addStmt(B->getLHS());
431 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
432 autoCreateBlock();
433 Block->appendStmt(B);
434 addStmt(B->getRHS());
435 return addStmt(B->getLHS());
438 return VisitStmt(B, alwaysAdd);
441 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr* E, bool alwaysAdd) {
442 // FIXME
443 return NYS();
446 CFGBlock *CFGBuilder::VisitBlockDeclRefExpr(BlockDeclRefExpr* E,
447 bool alwaysAdd) {
448 // FIXME
449 return NYS();
452 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
453 // "break" is a control-flow statement. Thus we stop processing the current
454 // block.
455 if (Block && !FinishBlock(Block))
456 return 0;
458 // Now create a new block that ends with the break statement.
459 Block = createBlock(false);
460 Block->setTerminator(B);
462 // If there is no target for the break, then we are looking at an incomplete
463 // AST. This means that the CFG cannot be constructed.
464 if (BreakTargetBlock)
465 Block->addSuccessor(BreakTargetBlock);
466 else
467 badCFG = true;
470 return Block;
473 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) {
474 // If this is a call to a no-return function, this stops the block here.
475 if (FunctionDecl *FD = C->getDirectCallee()) {
477 if (!FD->hasAttr<NoReturnAttr>())
478 return VisitStmt(C, alwaysAdd);
480 if (Block && !FinishBlock(Block))
481 return 0;
483 // Create new block with no successor for the remaining pieces.
484 Block = createBlock(false);
485 Block->appendStmt(C);
487 // Wire this to the exit block directly.
488 Block->addSuccessor(&cfg->getExit());
490 return VisitChildren(C);
493 return VisitStmt(C, alwaysAdd);
496 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C) {
497 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
498 ConfluenceBlock->appendStmt(C);
499 if (!FinishBlock(ConfluenceBlock))
500 return 0;
502 Succ = ConfluenceBlock;
503 Block = NULL;
504 CFGBlock* LHSBlock = addStmt(C->getLHS());
505 if (!FinishBlock(LHSBlock))
506 return 0;
508 Succ = ConfluenceBlock;
509 Block = NULL;
510 CFGBlock* RHSBlock = addStmt(C->getRHS());
511 if (!FinishBlock(RHSBlock))
512 return 0;
514 Block = createBlock(false);
515 Block->addSuccessor(LHSBlock);
516 Block->addSuccessor(RHSBlock);
517 Block->setTerminator(C);
518 return addStmt(C->getCond());
522 CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
523 CFGBlock* LastBlock = Block;
525 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
526 I != E; ++I ) {
527 LastBlock = addStmt(*I);
529 return LastBlock;
532 CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) {
533 // Create the confluence block that will "merge" the results of the ternary
534 // expression.
535 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
536 ConfluenceBlock->appendStmt(C);
537 if (!FinishBlock(ConfluenceBlock))
538 return 0;
540 // Create a block for the LHS expression if there is an LHS expression. A
541 // GCC extension allows LHS to be NULL, causing the condition to be the
542 // value that is returned instead.
543 // e.g: x ?: y is shorthand for: x ? x : y;
544 Succ = ConfluenceBlock;
545 Block = NULL;
546 CFGBlock* LHSBlock = NULL;
547 if (C->getLHS()) {
548 LHSBlock = addStmt(C->getLHS());
549 if (!FinishBlock(LHSBlock))
550 return 0;
551 Block = NULL;
554 // Create the block for the RHS expression.
555 Succ = ConfluenceBlock;
556 CFGBlock* RHSBlock = addStmt(C->getRHS());
557 if (!FinishBlock(RHSBlock))
558 return 0;
560 // Create the block that will contain the condition.
561 Block = createBlock(false);
563 if (LHSBlock)
564 Block->addSuccessor(LHSBlock);
565 else {
566 // If we have no LHS expression, add the ConfluenceBlock as a direct
567 // successor for the block containing the condition. Moreover, we need to
568 // reverse the order of the predecessors in the ConfluenceBlock because
569 // the RHSBlock will have been added to the succcessors already, and we
570 // want the first predecessor to the the block containing the expression
571 // for the case when the ternary expression evaluates to true.
572 Block->addSuccessor(ConfluenceBlock);
573 assert (ConfluenceBlock->pred_size() == 2);
574 std::reverse(ConfluenceBlock->pred_begin(),
575 ConfluenceBlock->pred_end());
578 Block->addSuccessor(RHSBlock);
580 Block->setTerminator(C);
581 return addStmt(C->getCond());
584 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
585 autoCreateBlock();
587 if (DS->isSingleDecl()) {
588 Block->appendStmt(DS);
589 return VisitDeclSubExpr(DS->getSingleDecl());
592 CFGBlock *B = 0;
594 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
595 typedef llvm::SmallVector<Decl*,10> BufTy;
596 BufTy Buf(DS->decl_begin(), DS->decl_end());
598 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
599 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
600 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
601 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
603 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
604 // automatically freed with the CFG.
605 DeclGroupRef DG(*I);
606 Decl *D = *I;
607 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
608 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
610 // Append the fake DeclStmt to block.
611 Block->appendStmt(DSNew);
612 B = VisitDeclSubExpr(D);
615 return B;
618 /// VisitDeclSubExpr - Utility method to add block-level expressions for
619 /// initializers in Decls.
620 CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
621 assert(Block);
623 VarDecl *VD = dyn_cast<VarDecl>(D);
625 if (!VD)
626 return Block;
628 Expr *Init = VD->getInit();
630 if (Init) {
631 // Optimization: Don't create separate block-level statements for literals.
632 switch (Init->getStmtClass()) {
633 case Stmt::IntegerLiteralClass:
634 case Stmt::CharacterLiteralClass:
635 case Stmt::StringLiteralClass:
636 break;
637 default:
638 Block = addStmt(Init);
642 // If the type of VD is a VLA, then we must process its size expressions.
643 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
644 VA = FindVA(VA->getElementType().getTypePtr()))
645 Block = addStmt(VA->getSizeExpr());
647 return Block;
650 CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
651 // We may see an if statement in the middle of a basic block, or it may be the
652 // first statement we are processing. In either case, we create a new basic
653 // block. First, we create the blocks for the then...else statements, and
654 // then we create the block containing the if statement. If we were in the
655 // middle of a block, we stop processing that block and reverse its
656 // statements. That block is then the implicit successor for the "then" and
657 // "else" clauses.
659 // The block we were proccessing is now finished. Make it the successor
660 // block.
661 if (Block) {
662 Succ = Block;
663 if (!FinishBlock(Block))
664 return 0;
667 // Process the false branch.
668 CFGBlock* ElseBlock = Succ;
670 if (Stmt* Else = I->getElse()) {
671 SaveAndRestore<CFGBlock*> sv(Succ);
673 // NULL out Block so that the recursive call to Visit will
674 // create a new basic block.
675 Block = NULL;
676 ElseBlock = addStmt(Else);
678 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
679 ElseBlock = sv.get();
680 else if (Block) {
681 if (!FinishBlock(ElseBlock))
682 return 0;
686 // Process the true branch.
687 CFGBlock* ThenBlock;
689 Stmt* Then = I->getThen();
690 assert (Then);
691 SaveAndRestore<CFGBlock*> sv(Succ);
692 Block = NULL;
693 ThenBlock = addStmt(Then);
695 if (!ThenBlock) {
696 // We can reach here if the "then" body has all NullStmts.
697 // Create an empty block so we can distinguish between true and false
698 // branches in path-sensitive analyses.
699 ThenBlock = createBlock(false);
700 ThenBlock->addSuccessor(sv.get());
701 } else if (Block) {
702 if (!FinishBlock(ThenBlock))
703 return 0;
707 // Now create a new block containing the if statement.
708 Block = createBlock(false);
710 // Set the terminator of the new block to the If statement.
711 Block->setTerminator(I);
713 // Now add the successors.
714 Block->addSuccessor(ThenBlock);
715 Block->addSuccessor(ElseBlock);
717 // Add the condition as the last statement in the new block. This may create
718 // new blocks as the condition may contain control-flow. Any newly created
719 // blocks will be pointed to be "Block".
720 return addStmt(I->getCond());
724 CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
725 // If we were in the middle of a block we stop processing that block and
726 // reverse its statements.
728 // NOTE: If a "return" appears in the middle of a block, this means that the
729 // code afterwards is DEAD (unreachable). We still keep a basic block
730 // for that code; a simple "mark-and-sweep" from the entry block will be
731 // able to report such dead blocks.
732 if (Block) FinishBlock(Block);
734 // Create the new block.
735 Block = createBlock(false);
737 // The Exit block is the only successor.
738 Block->addSuccessor(&cfg->getExit());
740 // Add the return statement to the block. This may create new blocks if R
741 // contains control-flow (short-circuit operations).
742 return VisitStmt(R, true);
745 CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
746 // Get the block of the labeled statement. Add it to our map.
747 addStmt(L->getSubStmt());
748 CFGBlock* LabelBlock = Block;
750 if (!LabelBlock) // This can happen when the body is empty, i.e.
751 LabelBlock = createBlock(); // scopes that only contains NullStmts.
753 assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
754 LabelMap[ L ] = LabelBlock;
756 // Labels partition blocks, so this is the end of the basic block we were
757 // processing (L is the block's label). Because this is label (and we have
758 // already processed the substatement) there is no extra control-flow to worry
759 // about.
760 LabelBlock->setLabel(L);
761 if (!FinishBlock(LabelBlock))
762 return 0;
764 // We set Block to NULL to allow lazy creation of a new block (if necessary);
765 Block = NULL;
767 // This block is now the implicit successor of other blocks.
768 Succ = LabelBlock;
770 return LabelBlock;
773 CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
774 // Goto is a control-flow statement. Thus we stop processing the current
775 // block and create a new one.
776 if (Block)
777 FinishBlock(Block);
779 Block = createBlock(false);
780 Block->setTerminator(G);
782 // If we already know the mapping to the label block add the successor now.
783 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
785 if (I == LabelMap.end())
786 // We will need to backpatch this block later.
787 BackpatchBlocks.push_back(Block);
788 else
789 Block->addSuccessor(I->second);
791 return Block;
794 CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
795 // "for" is a control-flow statement. Thus we stop processing the current
796 // block.
797 CFGBlock* LoopSuccessor = NULL;
799 if (Block) {
800 if (!FinishBlock(Block))
801 return 0;
802 LoopSuccessor = Block;
803 } else
804 LoopSuccessor = Succ;
806 // Because of short-circuit evaluation, the condition of the loop can span
807 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
808 // evaluate the condition.
809 CFGBlock* ExitConditionBlock = createBlock(false);
810 CFGBlock* EntryConditionBlock = ExitConditionBlock;
812 // Set the terminator for the "exit" condition block.
813 ExitConditionBlock->setTerminator(F);
815 // Now add the actual condition to the condition block. Because the condition
816 // itself may contain control-flow, new blocks may be created.
817 if (Stmt* C = F->getCond()) {
818 Block = ExitConditionBlock;
819 EntryConditionBlock = addStmt(C);
820 if (Block) {
821 if (!FinishBlock(EntryConditionBlock))
822 return 0;
826 // The condition block is the implicit successor for the loop body as well as
827 // any code above the loop.
828 Succ = EntryConditionBlock;
830 // Now create the loop body.
832 assert (F->getBody());
834 // Save the current values for Block, Succ, and continue and break targets
835 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
836 save_continue(ContinueTargetBlock),
837 save_break(BreakTargetBlock);
839 // Create a new block to contain the (bottom) of the loop body.
840 Block = NULL;
842 if (Stmt* I = F->getInc()) {
843 // Generate increment code in its own basic block. This is the target of
844 // continue statements.
845 Succ = addStmt(I);
846 } else {
847 // No increment code. Create a special, empty, block that is used as the
848 // target block for "looping back" to the start of the loop.
849 assert(Succ == EntryConditionBlock);
850 Succ = createBlock();
853 // Finish up the increment (or empty) block if it hasn't been already.
854 if (Block) {
855 assert(Block == Succ);
856 if (!FinishBlock(Block))
857 return 0;
858 Block = 0;
861 ContinueTargetBlock = Succ;
863 // The starting block for the loop increment is the block that should
864 // represent the 'loop target' for looping back to the start of the loop.
865 ContinueTargetBlock->setLoopTarget(F);
867 // All breaks should go to the code following the loop.
868 BreakTargetBlock = LoopSuccessor;
870 // Now populate the body block, and in the process create new blocks as we
871 // walk the body of the loop.
872 CFGBlock* BodyBlock = addStmt(F->getBody());
874 if (!BodyBlock)
875 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
876 else if (Block) {
877 if (!FinishBlock(BodyBlock))
878 return 0;
881 // This new body block is a successor to our "exit" condition block.
882 ExitConditionBlock->addSuccessor(BodyBlock);
885 // Link up the condition block with the code that follows the loop. (the
886 // false branch).
887 ExitConditionBlock->addSuccessor(LoopSuccessor);
889 // If the loop contains initialization, create a new block for those
890 // statements. This block can also contain statements that precede the loop.
891 if (Stmt* I = F->getInit()) {
892 Block = createBlock();
893 return addStmt(I);
894 } else {
895 // There is no loop initialization. We are thus basically a while loop.
896 // NULL out Block to force lazy block construction.
897 Block = NULL;
898 Succ = EntryConditionBlock;
899 return EntryConditionBlock;
903 CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
904 // Objective-C fast enumeration 'for' statements:
905 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
907 // for ( Type newVariable in collection_expression ) { statements }
909 // becomes:
911 // prologue:
912 // 1. collection_expression
913 // T. jump to loop_entry
914 // loop_entry:
915 // 1. side-effects of element expression
916 // 1. ObjCForCollectionStmt [performs binding to newVariable]
917 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
918 // TB:
919 // statements
920 // T. jump to loop_entry
921 // FB:
922 // what comes after
924 // and
926 // Type existingItem;
927 // for ( existingItem in expression ) { statements }
929 // becomes:
931 // the same with newVariable replaced with existingItem; the binding works
932 // the same except that for one ObjCForCollectionStmt::getElement() returns
933 // a DeclStmt and the other returns a DeclRefExpr.
936 CFGBlock* LoopSuccessor = 0;
938 if (Block) {
939 if (!FinishBlock(Block))
940 return 0;
941 LoopSuccessor = Block;
942 Block = 0;
943 } else
944 LoopSuccessor = Succ;
946 // Build the condition blocks.
947 CFGBlock* ExitConditionBlock = createBlock(false);
948 CFGBlock* EntryConditionBlock = ExitConditionBlock;
950 // Set the terminator for the "exit" condition block.
951 ExitConditionBlock->setTerminator(S);
953 // The last statement in the block should be the ObjCForCollectionStmt, which
954 // performs the actual binding to 'element' and determines if there are any
955 // more items in the collection.
956 ExitConditionBlock->appendStmt(S);
957 Block = ExitConditionBlock;
959 // Walk the 'element' expression to see if there are any side-effects. We
960 // generate new blocks as necesary. We DON'T add the statement by default to
961 // the CFG unless it contains control-flow.
962 EntryConditionBlock = Visit(S->getElement(), false);
963 if (Block) {
964 if (!FinishBlock(EntryConditionBlock))
965 return 0;
966 Block = 0;
969 // The condition block is the implicit successor for the loop body as well as
970 // any code above the loop.
971 Succ = EntryConditionBlock;
973 // Now create the true branch.
975 // Save the current values for Succ, continue and break targets.
976 SaveAndRestore<CFGBlock*> save_Succ(Succ),
977 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
979 BreakTargetBlock = LoopSuccessor;
980 ContinueTargetBlock = EntryConditionBlock;
982 CFGBlock* BodyBlock = addStmt(S->getBody());
984 if (!BodyBlock)
985 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
986 else if (Block) {
987 if (!FinishBlock(BodyBlock))
988 return 0;
991 // This new body block is a successor to our "exit" condition block.
992 ExitConditionBlock->addSuccessor(BodyBlock);
995 // Link up the condition block with the code that follows the loop.
996 // (the false branch).
997 ExitConditionBlock->addSuccessor(LoopSuccessor);
999 // Now create a prologue block to contain the collection expression.
1000 Block = createBlock();
1001 return addStmt(S->getCollection());
1004 CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1005 // FIXME: Add locking 'primitives' to CFG for @synchronized.
1007 // Inline the body.
1008 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1010 // The sync body starts its own basic block. This makes it a little easier
1011 // for diagnostic clients.
1012 if (SyncBlock) {
1013 if (!FinishBlock(SyncBlock))
1014 return 0;
1016 Block = 0;
1019 Succ = SyncBlock;
1021 // Inline the sync expression.
1022 return addStmt(S->getSynchExpr());
1025 CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1026 // FIXME
1027 return NYS();
1030 CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1031 // "while" is a control-flow statement. Thus we stop processing the current
1032 // block.
1034 CFGBlock* LoopSuccessor = NULL;
1036 if (Block) {
1037 if (!FinishBlock(Block))
1038 return 0;
1039 LoopSuccessor = Block;
1040 } else
1041 LoopSuccessor = Succ;
1043 // Because of short-circuit evaluation, the condition of the loop can span
1044 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1045 // evaluate the condition.
1046 CFGBlock* ExitConditionBlock = createBlock(false);
1047 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1049 // Set the terminator for the "exit" condition block.
1050 ExitConditionBlock->setTerminator(W);
1052 // Now add the actual condition to the condition block. Because the condition
1053 // itself may contain control-flow, new blocks may be created. Thus we update
1054 // "Succ" after adding the condition.
1055 if (Stmt* C = W->getCond()) {
1056 Block = ExitConditionBlock;
1057 EntryConditionBlock = addStmt(C);
1058 assert(Block == EntryConditionBlock);
1059 if (Block) {
1060 if (!FinishBlock(EntryConditionBlock))
1061 return 0;
1065 // The condition block is the implicit successor for the loop body as well as
1066 // any code above the loop.
1067 Succ = EntryConditionBlock;
1069 // Process the loop body.
1071 assert(W->getBody());
1073 // Save the current values for Block, Succ, and continue and break targets
1074 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1075 save_continue(ContinueTargetBlock),
1076 save_break(BreakTargetBlock);
1078 // Create an empty block to represent the transition block for looping back
1079 // to the head of the loop.
1080 Block = 0;
1081 assert(Succ == EntryConditionBlock);
1082 Succ = createBlock();
1083 Succ->setLoopTarget(W);
1084 ContinueTargetBlock = Succ;
1086 // All breaks should go to the code following the loop.
1087 BreakTargetBlock = LoopSuccessor;
1089 // NULL out Block to force lazy instantiation of blocks for the body.
1090 Block = NULL;
1092 // Create the body. The returned block is the entry to the loop body.
1093 CFGBlock* BodyBlock = addStmt(W->getBody());
1095 if (!BodyBlock)
1096 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
1097 else if (Block) {
1098 if (!FinishBlock(BodyBlock))
1099 return 0;
1102 // Add the loop body entry as a successor to the condition.
1103 ExitConditionBlock->addSuccessor(BodyBlock);
1106 // Link up the condition block with the code that follows the loop. (the
1107 // false branch).
1108 ExitConditionBlock->addSuccessor(LoopSuccessor);
1110 // There can be no more statements in the condition block since we loop back
1111 // to this block. NULL out Block to force lazy creation of another block.
1112 Block = NULL;
1114 // Return the condition block, which is the dominating block for the loop.
1115 Succ = EntryConditionBlock;
1116 return EntryConditionBlock;
1120 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1121 // FIXME: For now we pretend that @catch and the code it contains does not
1122 // exit.
1123 return Block;
1126 CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1127 // FIXME: This isn't complete. We basically treat @throw like a return
1128 // statement.
1130 // If we were in the middle of a block we stop processing that block and
1131 // reverse its statements.
1132 if (Block && !FinishBlock(Block))
1133 return 0;
1135 // Create the new block.
1136 Block = createBlock(false);
1138 // The Exit block is the only successor.
1139 Block->addSuccessor(&cfg->getExit());
1141 // Add the statement to the block. This may create new blocks if S contains
1142 // control-flow (short-circuit operations).
1143 return VisitStmt(S, true);
1146 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1147 // "do...while" is a control-flow statement. Thus we stop processing the
1148 // current block.
1150 CFGBlock* LoopSuccessor = NULL;
1152 if (Block) {
1153 if (!FinishBlock(Block))
1154 return 0;
1155 LoopSuccessor = Block;
1156 } else
1157 LoopSuccessor = Succ;
1159 // Because of short-circuit evaluation, the condition of the loop can span
1160 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1161 // evaluate the condition.
1162 CFGBlock* ExitConditionBlock = createBlock(false);
1163 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1165 // Set the terminator for the "exit" condition block.
1166 ExitConditionBlock->setTerminator(D);
1168 // Now add the actual condition to the condition block. Because the condition
1169 // itself may contain control-flow, new blocks may be created.
1170 if (Stmt* C = D->getCond()) {
1171 Block = ExitConditionBlock;
1172 EntryConditionBlock = addStmt(C);
1173 if (Block) {
1174 if (!FinishBlock(EntryConditionBlock))
1175 return 0;
1179 // The condition block is the implicit successor for the loop body.
1180 Succ = EntryConditionBlock;
1182 // Process the loop body.
1183 CFGBlock* BodyBlock = NULL;
1185 assert (D->getBody());
1187 // Save the current values for Block, Succ, and continue and break targets
1188 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1189 save_continue(ContinueTargetBlock),
1190 save_break(BreakTargetBlock);
1192 // All continues within this loop should go to the condition block
1193 ContinueTargetBlock = EntryConditionBlock;
1195 // All breaks should go to the code following the loop.
1196 BreakTargetBlock = LoopSuccessor;
1198 // NULL out Block to force lazy instantiation of blocks for the body.
1199 Block = NULL;
1201 // Create the body. The returned block is the entry to the loop body.
1202 BodyBlock = addStmt(D->getBody());
1204 if (!BodyBlock)
1205 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1206 else if (Block) {
1207 if (!FinishBlock(BodyBlock))
1208 return 0;
1211 // Add an intermediate block between the BodyBlock and the
1212 // ExitConditionBlock to represent the "loop back" transition. Create an
1213 // empty block to represent the transition block for looping back to the
1214 // head of the loop.
1215 // FIXME: Can we do this more efficiently without adding another block?
1216 Block = NULL;
1217 Succ = BodyBlock;
1218 CFGBlock *LoopBackBlock = createBlock();
1219 LoopBackBlock->setLoopTarget(D);
1221 // Add the loop body entry as a successor to the condition.
1222 ExitConditionBlock->addSuccessor(LoopBackBlock);
1225 // Link up the condition block with the code that follows the loop.
1226 // (the false branch).
1227 ExitConditionBlock->addSuccessor(LoopSuccessor);
1229 // There can be no more statements in the body block(s) since we loop back to
1230 // the body. NULL out Block to force lazy creation of another block.
1231 Block = NULL;
1233 // Return the loop body, which is the dominating block for the loop.
1234 Succ = BodyBlock;
1235 return BodyBlock;
1238 CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1239 // "continue" is a control-flow statement. Thus we stop processing the
1240 // current block.
1241 if (Block && !FinishBlock(Block))
1242 return 0;
1244 // Now create a new block that ends with the continue statement.
1245 Block = createBlock(false);
1246 Block->setTerminator(C);
1248 // If there is no target for the continue, then we are looking at an
1249 // incomplete AST. This means the CFG cannot be constructed.
1250 if (ContinueTargetBlock)
1251 Block->addSuccessor(ContinueTargetBlock);
1252 else
1253 badCFG = true;
1255 return Block;
1258 CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1259 bool alwaysAdd) {
1261 if (alwaysAdd) {
1262 autoCreateBlock();
1263 Block->appendStmt(E);
1266 // VLA types have expressions that must be evaluated.
1267 if (E->isArgumentType()) {
1268 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1269 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1270 addStmt(VA->getSizeExpr());
1273 return Block;
1276 /// VisitStmtExpr - Utility method to handle (nested) statement
1277 /// expressions (a GCC extension).
1278 CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, bool alwaysAdd) {
1279 if (alwaysAdd) {
1280 autoCreateBlock();
1281 Block->appendStmt(SE);
1283 return VisitCompoundStmt(SE->getSubStmt());
1286 CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1287 // "switch" is a control-flow statement. Thus we stop processing the current
1288 // block.
1289 CFGBlock* SwitchSuccessor = NULL;
1291 if (Block) {
1292 if (!FinishBlock(Block))
1293 return 0;
1294 SwitchSuccessor = Block;
1295 } else SwitchSuccessor = Succ;
1297 // Save the current "switch" context.
1298 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1299 save_break(BreakTargetBlock),
1300 save_default(DefaultCaseBlock);
1302 // Set the "default" case to be the block after the switch statement. If the
1303 // switch statement contains a "default:", this value will be overwritten with
1304 // the block for that code.
1305 DefaultCaseBlock = SwitchSuccessor;
1307 // Create a new block that will contain the switch statement.
1308 SwitchTerminatedBlock = createBlock(false);
1310 // Now process the switch body. The code after the switch is the implicit
1311 // successor.
1312 Succ = SwitchSuccessor;
1313 BreakTargetBlock = SwitchSuccessor;
1315 // When visiting the body, the case statements should automatically get linked
1316 // up to the switch. We also don't keep a pointer to the body, since all
1317 // control-flow from the switch goes to case/default statements.
1318 assert (Terminator->getBody() && "switch must contain a non-NULL body");
1319 Block = NULL;
1320 CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1321 if (Block) {
1322 if (!FinishBlock(BodyBlock))
1323 return 0;
1326 // If we have no "default:" case, the default transition is to the code
1327 // following the switch body.
1328 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
1330 // Add the terminator and condition in the switch block.
1331 SwitchTerminatedBlock->setTerminator(Terminator);
1332 assert (Terminator->getCond() && "switch condition must be non-NULL");
1333 Block = SwitchTerminatedBlock;
1335 return addStmt(Terminator->getCond());
1338 CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1339 // CaseStmts are essentially labels, so they are the first statement in a
1340 // block.
1342 if (CS->getSubStmt())
1343 addStmt(CS->getSubStmt());
1345 CFGBlock* CaseBlock = Block;
1346 if (!CaseBlock)
1347 CaseBlock = createBlock();
1349 // Cases statements partition blocks, so this is the top of the basic block we
1350 // were processing (the "case XXX:" is the label).
1351 CaseBlock->setLabel(CS);
1353 if (!FinishBlock(CaseBlock))
1354 return 0;
1356 // Add this block to the list of successors for the block with the switch
1357 // statement.
1358 assert(SwitchTerminatedBlock);
1359 SwitchTerminatedBlock->addSuccessor(CaseBlock);
1361 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1362 Block = NULL;
1364 // This block is now the implicit successor of other blocks.
1365 Succ = CaseBlock;
1367 return CaseBlock;
1370 CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1371 if (Terminator->getSubStmt())
1372 addStmt(Terminator->getSubStmt());
1374 DefaultCaseBlock = Block;
1376 if (!DefaultCaseBlock)
1377 DefaultCaseBlock = createBlock();
1379 // Default statements partition blocks, so this is the top of the basic block
1380 // we were processing (the "default:" is the label).
1381 DefaultCaseBlock->setLabel(Terminator);
1383 if (!FinishBlock(DefaultCaseBlock))
1384 return 0;
1386 // Unlike case statements, we don't add the default block to the successors
1387 // for the switch statement immediately. This is done when we finish
1388 // processing the switch statement. This allows for the default case
1389 // (including a fall-through to the code after the switch statement) to always
1390 // be the last successor of a switch-terminated block.
1392 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1393 Block = NULL;
1395 // This block is now the implicit successor of other blocks.
1396 Succ = DefaultCaseBlock;
1398 return DefaultCaseBlock;
1401 CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1402 // Lazily create the indirect-goto dispatch block if there isn't one already.
1403 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1405 if (!IBlock) {
1406 IBlock = createBlock(false);
1407 cfg->setIndirectGotoBlock(IBlock);
1410 // IndirectGoto is a control-flow statement. Thus we stop processing the
1411 // current block and create a new one.
1412 if (Block && !FinishBlock(Block))
1413 return 0;
1415 Block = createBlock(false);
1416 Block->setTerminator(I);
1417 Block->addSuccessor(IBlock);
1418 return addStmt(I->getTarget());
1421 } // end anonymous namespace
1423 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
1424 /// no successors or predecessors. If this is the first block created in the
1425 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
1426 CFGBlock* CFG::createBlock() {
1427 bool first_block = begin() == end();
1429 // Create the block.
1430 Blocks.push_front(CFGBlock(NumBlockIDs++));
1432 // If this is the first block, set it as the Entry and Exit.
1433 if (first_block) Entry = Exit = &front();
1435 // Return the block.
1436 return &front();
1439 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1440 /// CFG is returned to the caller.
1441 CFG* CFG::buildCFG(Stmt* Statement) {
1442 CFGBuilder Builder;
1443 return Builder.buildCFG(Statement);
1446 /// reverseStmts - Reverses the orders of statements within a CFGBlock.
1447 void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1449 //===----------------------------------------------------------------------===//
1450 // CFG: Queries for BlkExprs.
1451 //===----------------------------------------------------------------------===//
1453 namespace {
1454 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1457 static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1458 if (!Terminator)
1459 return;
1461 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
1462 if (!*I) continue;
1464 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1465 if (B->isAssignmentOp()) Set.insert(B);
1467 FindSubExprAssignments(*I, Set);
1471 static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1472 BlkExprMapTy* M = new BlkExprMapTy();
1474 // Look for assignments that are used as subexpressions. These are the only
1475 // assignments that we want to *possibly* register as a block-level
1476 // expression. Basically, if an assignment occurs both in a subexpression and
1477 // at the block-level, it is a block-level expression.
1478 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1480 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1481 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1482 FindSubExprAssignments(*BI, SubExprAssignments);
1484 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1486 // Iterate over the statements again on identify the Expr* and Stmt* at the
1487 // block-level that are block-level expressions.
1489 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1490 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1492 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1493 // Assignment expressions that are not nested within another
1494 // expression are really "statements" whose value is never used by
1495 // another expression.
1496 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1497 continue;
1498 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1499 // Special handling for statement expressions. The last statement in
1500 // the statement expression is also a block-level expr.
1501 const CompoundStmt* C = Terminator->getSubStmt();
1502 if (!C->body_empty()) {
1503 unsigned x = M->size();
1504 (*M)[C->body_back()] = x;
1508 unsigned x = M->size();
1509 (*M)[Exp] = x;
1512 // Look at terminators. The condition is a block-level expression.
1514 Stmt* S = I->getTerminatorCondition();
1516 if (S && M->find(S) == M->end()) {
1517 unsigned x = M->size();
1518 (*M)[S] = x;
1522 return M;
1525 CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1526 assert(S != NULL);
1527 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1529 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1530 BlkExprMapTy::iterator I = M->find(S);
1532 if (I == M->end()) return CFG::BlkExprNumTy();
1533 else return CFG::BlkExprNumTy(I->second);
1536 unsigned CFG::getNumBlkExprs() {
1537 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1538 return M->size();
1539 else {
1540 // We assume callers interested in the number of BlkExprs will want
1541 // the map constructed if it doesn't already exist.
1542 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1543 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1547 //===----------------------------------------------------------------------===//
1548 // Cleanup: CFG dstor.
1549 //===----------------------------------------------------------------------===//
1551 CFG::~CFG() {
1552 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1555 //===----------------------------------------------------------------------===//
1556 // CFG pretty printing
1557 //===----------------------------------------------------------------------===//
1559 namespace {
1561 class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
1563 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1564 StmtMapTy StmtMap;
1565 signed CurrentBlock;
1566 unsigned CurrentStmt;
1567 const LangOptions &LangOpts;
1568 public:
1570 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1571 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1572 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1573 unsigned j = 1;
1574 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1575 BI != BEnd; ++BI, ++j )
1576 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1580 virtual ~StmtPrinterHelper() {}
1582 const LangOptions &getLangOpts() const { return LangOpts; }
1583 void setBlockID(signed i) { CurrentBlock = i; }
1584 void setStmtID(unsigned i) { CurrentStmt = i; }
1586 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1588 StmtMapTy::iterator I = StmtMap.find(Terminator);
1590 if (I == StmtMap.end())
1591 return false;
1593 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1594 && I->second.second == CurrentStmt)
1595 return false;
1597 OS << "[B" << I->second.first << "." << I->second.second << "]";
1598 return true;
1601 } // end anonymous namespace
1604 namespace {
1605 class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1606 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1608 llvm::raw_ostream& OS;
1609 StmtPrinterHelper* Helper;
1610 PrintingPolicy Policy;
1612 public:
1613 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1614 const PrintingPolicy &Policy)
1615 : OS(os), Helper(helper), Policy(Policy) {}
1617 void VisitIfStmt(IfStmt* I) {
1618 OS << "if ";
1619 I->getCond()->printPretty(OS,Helper,Policy);
1622 // Default case.
1623 void VisitStmt(Stmt* Terminator) {
1624 Terminator->printPretty(OS, Helper, Policy);
1627 void VisitForStmt(ForStmt* F) {
1628 OS << "for (" ;
1629 if (F->getInit()) OS << "...";
1630 OS << "; ";
1631 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
1632 OS << "; ";
1633 if (F->getInc()) OS << "...";
1634 OS << ")";
1637 void VisitWhileStmt(WhileStmt* W) {
1638 OS << "while " ;
1639 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
1642 void VisitDoStmt(DoStmt* D) {
1643 OS << "do ... while ";
1644 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
1647 void VisitSwitchStmt(SwitchStmt* Terminator) {
1648 OS << "switch ";
1649 Terminator->getCond()->printPretty(OS, Helper, Policy);
1652 void VisitConditionalOperator(ConditionalOperator* C) {
1653 C->getCond()->printPretty(OS, Helper, Policy);
1654 OS << " ? ... : ...";
1657 void VisitChooseExpr(ChooseExpr* C) {
1658 OS << "__builtin_choose_expr( ";
1659 C->getCond()->printPretty(OS, Helper, Policy);
1660 OS << " )";
1663 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1664 OS << "goto *";
1665 I->getTarget()->printPretty(OS, Helper, Policy);
1668 void VisitBinaryOperator(BinaryOperator* B) {
1669 if (!B->isLogicalOp()) {
1670 VisitExpr(B);
1671 return;
1674 B->getLHS()->printPretty(OS, Helper, Policy);
1676 switch (B->getOpcode()) {
1677 case BinaryOperator::LOr:
1678 OS << " || ...";
1679 return;
1680 case BinaryOperator::LAnd:
1681 OS << " && ...";
1682 return;
1683 default:
1684 assert(false && "Invalid logical operator.");
1688 void VisitExpr(Expr* E) {
1689 E->printPretty(OS, Helper, Policy);
1692 } // end anonymous namespace
1695 static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1696 Stmt* Terminator) {
1697 if (Helper) {
1698 // special printing for statement-expressions.
1699 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
1700 CompoundStmt* Sub = SE->getSubStmt();
1702 if (Sub->child_begin() != Sub->child_end()) {
1703 OS << "({ ... ; ";
1704 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
1705 OS << " })\n";
1706 return;
1710 // special printing for comma expressions.
1711 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
1712 if (B->getOpcode() == BinaryOperator::Comma) {
1713 OS << "... , ";
1714 Helper->handledStmt(B->getRHS(),OS);
1715 OS << '\n';
1716 return;
1721 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
1723 // Expressions need a newline.
1724 if (isa<Expr>(Terminator)) OS << '\n';
1727 static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
1728 const CFGBlock& B,
1729 StmtPrinterHelper* Helper, bool print_edges) {
1731 if (Helper) Helper->setBlockID(B.getBlockID());
1733 // Print the header.
1734 OS << "\n [ B" << B.getBlockID();
1736 if (&B == &cfg->getEntry())
1737 OS << " (ENTRY) ]\n";
1738 else if (&B == &cfg->getExit())
1739 OS << " (EXIT) ]\n";
1740 else if (&B == cfg->getIndirectGotoBlock())
1741 OS << " (INDIRECT GOTO DISPATCH) ]\n";
1742 else
1743 OS << " ]\n";
1745 // Print the label of this block.
1746 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
1748 if (print_edges)
1749 OS << " ";
1751 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
1752 OS << L->getName();
1753 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
1754 OS << "case ";
1755 C->getLHS()->printPretty(OS, Helper,
1756 PrintingPolicy(Helper->getLangOpts()));
1757 if (C->getRHS()) {
1758 OS << " ... ";
1759 C->getRHS()->printPretty(OS, Helper,
1760 PrintingPolicy(Helper->getLangOpts()));
1762 } else if (isa<DefaultStmt>(Terminator))
1763 OS << "default";
1764 else
1765 assert(false && "Invalid label statement in CFGBlock.");
1767 OS << ":\n";
1770 // Iterate through the statements in the block and print them.
1771 unsigned j = 1;
1773 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1774 I != E ; ++I, ++j ) {
1776 // Print the statement # in the basic block and the statement itself.
1777 if (print_edges)
1778 OS << " ";
1780 OS << llvm::format("%3d", j) << ": ";
1782 if (Helper)
1783 Helper->setStmtID(j);
1785 print_stmt(OS,Helper,*I);
1788 // Print the terminator of this block.
1789 if (B.getTerminator()) {
1790 if (print_edges)
1791 OS << " ";
1793 OS << " T: ";
1795 if (Helper) Helper->setBlockID(-1);
1797 CFGBlockTerminatorPrint TPrinter(OS, Helper,
1798 PrintingPolicy(Helper->getLangOpts()));
1799 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
1800 OS << '\n';
1803 if (print_edges) {
1804 // Print the predecessors of this block.
1805 OS << " Predecessors (" << B.pred_size() << "):";
1806 unsigned i = 0;
1808 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1809 I != E; ++I, ++i) {
1811 if (i == 8 || (i-8) == 0)
1812 OS << "\n ";
1814 OS << " B" << (*I)->getBlockID();
1817 OS << '\n';
1819 // Print the successors of this block.
1820 OS << " Successors (" << B.succ_size() << "):";
1821 i = 0;
1823 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1824 I != E; ++I, ++i) {
1826 if (i == 8 || (i-8) % 10 == 0)
1827 OS << "\n ";
1829 OS << " B" << (*I)->getBlockID();
1832 OS << '\n';
1837 /// dump - A simple pretty printer of a CFG that outputs to stderr.
1838 void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
1840 /// print - A simple pretty printer of a CFG that outputs to an ostream.
1841 void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
1842 StmtPrinterHelper Helper(this, LO);
1844 // Print the entry block.
1845 print_block(OS, this, getEntry(), &Helper, true);
1847 // Iterate through the CFGBlocks and print them one by one.
1848 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1849 // Skip the entry block, because we already printed it.
1850 if (&(*I) == &getEntry() || &(*I) == &getExit())
1851 continue;
1853 print_block(OS, this, *I, &Helper, true);
1856 // Print the exit block.
1857 print_block(OS, this, getExit(), &Helper, true);
1858 OS.flush();
1861 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1862 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
1863 print(llvm::errs(), cfg, LO);
1866 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1867 /// Generally this will only be called from CFG::print.
1868 void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
1869 const LangOptions &LO) const {
1870 StmtPrinterHelper Helper(cfg, LO);
1871 print_block(OS, cfg, *this, &Helper, true);
1874 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1875 void CFGBlock::printTerminator(llvm::raw_ostream &OS,
1876 const LangOptions &LO) const {
1877 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
1878 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1881 Stmt* CFGBlock::getTerminatorCondition() {
1883 if (!Terminator)
1884 return NULL;
1886 Expr* E = NULL;
1888 switch (Terminator->getStmtClass()) {
1889 default:
1890 break;
1892 case Stmt::ForStmtClass:
1893 E = cast<ForStmt>(Terminator)->getCond();
1894 break;
1896 case Stmt::WhileStmtClass:
1897 E = cast<WhileStmt>(Terminator)->getCond();
1898 break;
1900 case Stmt::DoStmtClass:
1901 E = cast<DoStmt>(Terminator)->getCond();
1902 break;
1904 case Stmt::IfStmtClass:
1905 E = cast<IfStmt>(Terminator)->getCond();
1906 break;
1908 case Stmt::ChooseExprClass:
1909 E = cast<ChooseExpr>(Terminator)->getCond();
1910 break;
1912 case Stmt::IndirectGotoStmtClass:
1913 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1914 break;
1916 case Stmt::SwitchStmtClass:
1917 E = cast<SwitchStmt>(Terminator)->getCond();
1918 break;
1920 case Stmt::ConditionalOperatorClass:
1921 E = cast<ConditionalOperator>(Terminator)->getCond();
1922 break;
1924 case Stmt::BinaryOperatorClass: // '&&' and '||'
1925 E = cast<BinaryOperator>(Terminator)->getLHS();
1926 break;
1928 case Stmt::ObjCForCollectionStmtClass:
1929 return Terminator;
1932 return E ? E->IgnoreParens() : NULL;
1935 bool CFGBlock::hasBinaryBranchTerminator() const {
1937 if (!Terminator)
1938 return false;
1940 Expr* E = NULL;
1942 switch (Terminator->getStmtClass()) {
1943 default:
1944 return false;
1946 case Stmt::ForStmtClass:
1947 case Stmt::WhileStmtClass:
1948 case Stmt::DoStmtClass:
1949 case Stmt::IfStmtClass:
1950 case Stmt::ChooseExprClass:
1951 case Stmt::ConditionalOperatorClass:
1952 case Stmt::BinaryOperatorClass:
1953 return true;
1956 return E ? E->IgnoreParens() : NULL;
1960 //===----------------------------------------------------------------------===//
1961 // CFG Graphviz Visualization
1962 //===----------------------------------------------------------------------===//
1965 #ifndef NDEBUG
1966 static StmtPrinterHelper* GraphHelper;
1967 #endif
1969 void CFG::viewCFG(const LangOptions &LO) const {
1970 #ifndef NDEBUG
1971 StmtPrinterHelper H(this, LO);
1972 GraphHelper = &H;
1973 llvm::ViewGraph(this,"CFG");
1974 GraphHelper = NULL;
1975 #endif
1978 namespace llvm {
1979 template<>
1980 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1981 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph,
1982 bool ShortNames) {
1984 #ifndef NDEBUG
1985 std::string OutSStr;
1986 llvm::raw_string_ostream Out(OutSStr);
1987 print_block(Out,Graph, *Node, GraphHelper, false);
1988 std::string& OutStr = Out.str();
1990 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1992 // Process string output to make it nicer...
1993 for (unsigned i = 0; i != OutStr.length(); ++i)
1994 if (OutStr[i] == '\n') { // Left justify
1995 OutStr[i] = '\\';
1996 OutStr.insert(OutStr.begin()+i+1, 'l');
1999 return OutStr;
2000 #else
2001 return "";
2002 #endif
2005 } // end namespace llvm