blob: 6e2e4dbe0e7be756312e162c04590bec81a0c98a [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source 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.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
16#include "clang/AST/Expr.h"
Ted Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
21#include "llvm/Config/config.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000022#include <iostream>
23#include <iomanip>
24#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000025#include <sstream>
26
Ted Kremenek97f75312007-08-21 21:42:03 +000027using namespace clang;
28
29namespace {
30
Ted Kremenekd6e50602007-08-23 21:26:19 +000031// SaveAndRestore - A utility class that uses RIIA to save and restore
32// the value of a variable.
33template<typename T>
34struct SaveAndRestore {
35 SaveAndRestore(T& x) : X(x), old_value(x) {}
36 ~SaveAndRestore() { X = old_value; }
37
38 T& X;
39 T old_value;
40};
Ted Kremenek97f75312007-08-21 21:42:03 +000041
42/// CFGBuilder - This class is implements CFG construction from an AST.
43/// The builder is stateful: an instance of the builder should be used to only
44/// construct a single CFG.
45///
46/// Example usage:
47///
48/// CFGBuilder builder;
49/// CFG* cfg = builder.BuildAST(stmt1);
50///
Ted Kremenek95e854d2007-08-21 22:06:14 +000051/// CFG construction is done via a recursive walk of an AST.
52/// We actually parse the AST in reverse order so that the successor
53/// of a basic block is constructed prior to its predecessor. This
54/// allows us to nicely capture implicit fall-throughs without extra
55/// basic blocks.
56///
57class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000058 CFG* cfg;
59 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000060 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000061 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000062 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000063 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000064 unsigned NumBlocks;
65
Ted Kremenek0edd3a92007-08-28 19:26:49 +000066 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000067 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
68 LabelMapTy LabelMap;
69
Ted Kremenek0edd3a92007-08-28 19:26:49 +000070 // A list of blocks that end with a "goto" that must be backpatched to
71 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000072 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000073 BackpatchBlocksTy BackpatchBlocks;
74
Ted Kremenek0edd3a92007-08-28 19:26:49 +000075 // A list of labels whose address has been taken (for indirect gotos).
76 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
77 LabelSetTy AddressTakenLabels;
78
Ted Kremenek97f75312007-08-21 21:42:03 +000079public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000080 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000081 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremeneke809ebf2007-08-23 18:43:24 +000082 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000083 NumBlocks(0) {
84 // Create an empty CFG.
85 cfg = new CFG();
86 }
87
88 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000089
Ted Kremenek73543912007-08-23 21:42:29 +000090 // buildCFG - Used by external clients to construct the CFG.
91 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // Visitors to walk an AST and construct the CFG. Called by
94 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 CFGBlock* VisitStmt(Stmt* Statement);
97 CFGBlock* VisitNullStmt(NullStmt* Statement);
98 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
99 CFGBlock* VisitIfStmt(IfStmt* I);
100 CFGBlock* VisitReturnStmt(ReturnStmt* R);
101 CFGBlock* VisitLabelStmt(LabelStmt* L);
102 CFGBlock* VisitGotoStmt(GotoStmt* G);
103 CFGBlock* VisitForStmt(ForStmt* F);
104 CFGBlock* VisitWhileStmt(WhileStmt* W);
105 CFGBlock* VisitDoStmt(DoStmt* D);
106 CFGBlock* VisitContinueStmt(ContinueStmt* C);
107 CFGBlock* VisitBreakStmt(BreakStmt* B);
108 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
109 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000110 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000111
Ted Kremenek73543912007-08-23 21:42:29 +0000112private:
113 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000114 CFGBlock* addStmt(Stmt* S);
115 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
116 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000117 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000118 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenek73543912007-08-23 21:42:29 +0000119 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000120
Ted Kremenek97f75312007-08-21 21:42:03 +0000121};
Ted Kremenek73543912007-08-23 21:42:29 +0000122
123/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
124/// represent an arbitrary statement. Examples include a single expression
125/// or a function body (compound statement). The ownership of the returned
126/// CFG is transferred to the caller. If CFG construction fails, this method
127/// returns NULL.
128CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000129 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000130 if (!Statement) return NULL;
131
132 // Create an empty block that will serve as the exit block for the CFG.
133 // Since this is the first block added to the CFG, it will be implicitly
134 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000135 Succ = createBlock();
136 assert (Succ == &cfg->getExit());
137 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000138
139 // Visit the statements and create the CFG.
140 if (CFGBlock* B = Visit(Statement)) {
141 // Finalize the last constructed block. This usually involves
142 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000143 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000144
145 // Backpatch the gotos whose label -> block mappings we didn't know
146 // when we encountered them.
147 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
148 E = BackpatchBlocks.end(); I != E; ++I ) {
149
150 CFGBlock* B = *I;
151 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
152 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
153
154 // If there is no target for the goto, then we are looking at an
155 // incomplete AST. Handle this by not registering a successor.
156 if (LI == LabelMap.end()) continue;
157
158 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000159 }
Ted Kremenek73543912007-08-23 21:42:29 +0000160
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000161 // Add successors to the Indirect Goto Dispatch block (if we have one).
162 if (CFGBlock* B = cfg->getIndirectGotoBlock())
163 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
164 E = AddressTakenLabels.end(); I != E; ++I ) {
165
166 // Lookup the target block.
167 LabelMapTy::iterator LI = LabelMap.find(*I);
168
169 // If there is no target block that contains label, then we are looking
170 // at an incomplete AST. Handle this by not registering a successor.
171 if (LI == LabelMap.end()) continue;
172
173 B->addSuccessor(LI->second);
174 }
175
176 // Create an empty entry block that has no predecessors.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000177 if (B->pred_size() > 0) {
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000178 Succ = B;
179 cfg->setEntry(createBlock());
180 }
181 else cfg->setEntry(B);
182
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000183 // NULL out cfg so that repeated calls to the builder will fail and that
184 // the ownership of the constructed CFG is passed to the caller.
Ted Kremenek73543912007-08-23 21:42:29 +0000185 CFG* t = cfg;
186 cfg = NULL;
187 return t;
188 }
189 else return NULL;
190}
191
192/// createBlock - Used to lazily create blocks that are connected
193/// to the current (global) succcessor.
194CFGBlock* CFGBuilder::createBlock(bool add_successor) {
195 CFGBlock* B = cfg->createBlock(NumBlocks++);
196 if (add_successor && Succ) B->addSuccessor(Succ);
197 return B;
198}
199
200/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000201/// we must reverse the statements because they have been inserted
202/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000203void CFGBuilder::FinishBlock(CFGBlock* B) {
204 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000205 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000206}
207
Ted Kremenek65cfa562007-08-27 21:27:44 +0000208/// addStmt - Used to add statements/expressions to the current CFGBlock
209/// "Block". This method calls WalkAST on the passed statement to see if it
210/// contains any short-circuit expressions. If so, it recursively creates
211/// the necessary blocks for such expressions. It returns the "topmost" block
212/// of the created blocks, or the original value of "Block" when this method
213/// was called if no additional blocks are created.
214CFGBlock* CFGBuilder::addStmt(Stmt* S) {
215 assert (Block);
216 return WalkAST(S,true);
217}
218
219/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000220/// add extra blocks for ternary operators, &&, and ||. We also
221/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek65cfa562007-08-27 21:27:44 +0000222CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
223 switch (S->getStmtClass()) {
224 case Stmt::ConditionalOperatorClass: {
225 ConditionalOperator* C = cast<ConditionalOperator>(S);
226
227 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
228 ConfluenceBlock->appendStmt(C);
229 FinishBlock(ConfluenceBlock);
230
231 Succ = ConfluenceBlock;
232 Block = NULL;
233 CFGBlock* LHSBlock = Visit(C->getLHS());
234
235 Succ = ConfluenceBlock;
236 Block = NULL;
237 CFGBlock* RHSBlock = Visit(C->getRHS());
238
239 Block = createBlock(false);
240 Block->addSuccessor(LHSBlock);
241 Block->addSuccessor(RHSBlock);
242 Block->setTerminator(C);
243 return addStmt(C->getCond());
244 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000245
Ted Kremeneke822b622007-08-28 18:14:37 +0000246 case Stmt::DeclStmtClass:
247 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
248 Block->appendStmt(S);
249 return WalkAST_VisitVarDecl(V);
250 }
251 else return Block;
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000252
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000253 case Stmt::AddrLabelExprClass: {
254 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
255 AddressTakenLabels.insert(A->getLabel());
256
257 if (AlwaysAddStmt) Block->appendStmt(S);
258 return Block;
259 }
260
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000261 case Stmt::StmtExprClass:
262 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000263
Ted Kremenekcfaae762007-08-27 21:54:41 +0000264 case Stmt::BinaryOperatorClass: {
265 BinaryOperator* B = cast<BinaryOperator>(S);
266
267 if (B->isLogicalOp()) { // && or ||
268 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
269 ConfluenceBlock->appendStmt(B);
270 FinishBlock(ConfluenceBlock);
271
272 // create the block evaluating the LHS
273 CFGBlock* LHSBlock = createBlock(false);
274 LHSBlock->addSuccessor(ConfluenceBlock);
275 LHSBlock->setTerminator(B);
276
277 // create the block evaluating the RHS
278 Succ = ConfluenceBlock;
279 Block = NULL;
280 CFGBlock* RHSBlock = Visit(B->getRHS());
281 LHSBlock->addSuccessor(RHSBlock);
282
283 // Generate the blocks for evaluating the LHS.
284 Block = LHSBlock;
285 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000286 }
287 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
288 Block->appendStmt(B);
289 addStmt(B->getRHS());
290 return addStmt(B->getLHS());
Ted Kremenekcfaae762007-08-27 21:54:41 +0000291 }
292
293 // Fall through to the default case.
294 }
295
Ted Kremenek65cfa562007-08-27 21:27:44 +0000296 default:
297 if (AlwaysAddStmt) Block->appendStmt(S);
298 return WalkAST_VisitChildren(S);
299 };
300}
301
Ted Kremeneke822b622007-08-28 18:14:37 +0000302/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
303/// DeclStmts. Because the initialization code for declarations can
304/// contain arbitrary expressions, we must linearize declarations
305/// to handle arbitrary control-flow induced by those expressions.
306CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
307 // We actually must parse the LAST declaration in a chain of
308 // declarations first, because we are building the CFG in reverse
309 // order.
310 if (Decl* D = V->getNextDeclarator())
311 if (VarDecl* Next = cast<VarDecl>(D))
312 Block = WalkAST_VisitVarDecl(Next);
313
314 if (Expr* E = V->getInit())
315 return addStmt(E);
316
317 assert (Block);
318 return Block;
319}
320
Ted Kremenek65cfa562007-08-27 21:27:44 +0000321/// WalkAST_VisitChildren - Utility method to call WalkAST on the
322/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000323CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000324 CFGBlock* B = Block;
325 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
326 I != E; ++I)
327 B = WalkAST(*I);
328
329 return B;
330}
331
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000332/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
333/// expressions (a GCC extension).
334CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
335 Block->appendStmt(S);
336 return VisitCompoundStmt(S->getSubStmt());
337}
338
Ted Kremenek73543912007-08-23 21:42:29 +0000339/// VisitStmt - Handle statements with no branching control flow.
340CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
341 // We cannot assume that we are in the middle of a basic block, since
342 // the CFG might only be constructed for this single statement. If
343 // we have no current basic block, just create one lazily.
344 if (!Block) Block = createBlock();
345
346 // Simply add the statement to the current block. We actually
347 // insert statements in reverse order; this order is reversed later
348 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000349 addStmt(Statement);
350
Ted Kremenek73543912007-08-23 21:42:29 +0000351 return Block;
352}
353
354CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
355 return Block;
356}
357
358CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
359 // The value returned from this function is the last created CFGBlock
360 // that represents the "entry" point for the translated AST node.
361 CFGBlock* LastBlock;
362
363 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
364 E = C->body_rend(); I != E; ++I )
365 // Add the statement to the current block.
366 if (!(LastBlock=Visit(*I)))
367 return NULL;
368
369 return LastBlock;
370}
371
372CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
373 // We may see an if statement in the middle of a basic block, or
374 // it may be the first statement we are processing. In either case,
375 // we create a new basic block. First, we create the blocks for
376 // the then...else statements, and then we create the block containing
377 // the if statement. If we were in the middle of a block, we
378 // stop processing that block and reverse its statements. That block
379 // is then the implicit successor for the "then" and "else" clauses.
380
381 // The block we were proccessing is now finished. Make it the
382 // successor block.
383 if (Block) {
384 Succ = Block;
385 FinishBlock(Block);
386 }
387
388 // Process the false branch. NULL out Block so that the recursive
389 // call to Visit will create a new basic block.
390 // Null out Block so that all successor
391 CFGBlock* ElseBlock = Succ;
392
393 if (Stmt* Else = I->getElse()) {
394 SaveAndRestore<CFGBlock*> sv(Succ);
395
396 // NULL out Block so that the recursive call to Visit will
397 // create a new basic block.
398 Block = NULL;
399 ElseBlock = Visit(Else);
400 if (!ElseBlock) return NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000401 if (Block) FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000402 }
403
404 // Process the true branch. NULL out Block so that the recursive
405 // call to Visit will create a new basic block.
406 // Null out Block so that all successor
407 CFGBlock* ThenBlock;
408 {
409 Stmt* Then = I->getThen();
410 assert (Then);
411 SaveAndRestore<CFGBlock*> sv(Succ);
412 Block = NULL;
413 ThenBlock = Visit(Then);
414 if (!ThenBlock) return NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000415 if (Block) FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000416 }
417
418 // Now create a new block containing the if statement.
419 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000420
421 // Set the terminator of the new block to the If statement.
422 Block->setTerminator(I);
423
424 // Now add the successors.
425 Block->addSuccessor(ThenBlock);
426 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000427
428 // Add the condition as the last statement in the new block. This
429 // may create new blocks as the condition may contain control-flow. Any
430 // newly created blocks will be pointed to be "Block".
431 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000432}
433
434CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
435 // If we were in the middle of a block we stop processing that block
436 // and reverse its statements.
437 //
438 // NOTE: If a "return" appears in the middle of a block, this means
439 // that the code afterwards is DEAD (unreachable). We still
440 // keep a basic block for that code; a simple "mark-and-sweep"
441 // from the entry block will be able to report such dead
442 // blocks.
443 if (Block) FinishBlock(Block);
444
445 // Create the new block.
446 Block = createBlock(false);
447
448 // The Exit block is the only successor.
449 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000450
451 // Add the return statement to the block. This may create new blocks
452 // if R contains control-flow (short-circuit operations).
453 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000454}
455
456CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
457 // Get the block of the labeled statement. Add it to our map.
458 CFGBlock* LabelBlock = Visit(L->getSubStmt());
459 assert (LabelBlock);
460
461 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
462 LabelMap[ L ] = LabelBlock;
463
464 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000465 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000466 // label (and we have already processed the substatement) there is no
467 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000468 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000469 FinishBlock(LabelBlock);
470
471 // We set Block to NULL to allow lazy creation of a new block
472 // (if necessary);
473 Block = NULL;
474
475 // This block is now the implicit successor of other blocks.
476 Succ = LabelBlock;
477
478 return LabelBlock;
479}
480
481CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
482 // Goto is a control-flow statement. Thus we stop processing the
483 // current block and create a new one.
484 if (Block) FinishBlock(Block);
485 Block = createBlock(false);
486 Block->setTerminator(G);
487
488 // If we already know the mapping to the label block add the
489 // successor now.
490 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
491
492 if (I == LabelMap.end())
493 // We will need to backpatch this block later.
494 BackpatchBlocks.push_back(Block);
495 else
496 Block->addSuccessor(I->second);
497
498 return Block;
499}
500
501CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
502 // "for" is a control-flow statement. Thus we stop processing the
503 // current block.
504
505 CFGBlock* LoopSuccessor = NULL;
506
507 if (Block) {
508 FinishBlock(Block);
509 LoopSuccessor = Block;
510 }
511 else LoopSuccessor = Succ;
512
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000513 // Because of short-circuit evaluation, the condition of the loop
514 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
515 // blocks that evaluate the condition.
516 CFGBlock* ExitConditionBlock = createBlock(false);
517 CFGBlock* EntryConditionBlock = ExitConditionBlock;
518
519 // Set the terminator for the "exit" condition block.
520 ExitConditionBlock->setTerminator(F);
521
522 // Now add the actual condition to the condition block. Because the
523 // condition itself may contain control-flow, new blocks may be created.
524 if (Stmt* C = F->getCond()) {
525 Block = ExitConditionBlock;
526 EntryConditionBlock = addStmt(C);
527 if (Block) FinishBlock(EntryConditionBlock);
528 }
Ted Kremenek73543912007-08-23 21:42:29 +0000529
530 // The condition block is the implicit successor for the loop body as
531 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000532 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000533
534 // Now create the loop body.
535 {
536 assert (F->getBody());
537
538 // Save the current values for Block, Succ, and continue and break targets
539 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
540 save_continue(ContinueTargetBlock),
541 save_break(BreakTargetBlock);
542
543 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000544 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000545
546 // All breaks should go to the code following the loop.
547 BreakTargetBlock = LoopSuccessor;
548
549 // Create a new block to contain the (bottom) of the loop body.
550 Block = createBlock();
551
552 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000553 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000554
555 // Now populate the body block, and in the process create new blocks
556 // as we walk the body of the loop.
557 CFGBlock* BodyBlock = Visit(F->getBody());
558 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000559 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000560
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000561 // This new body block is a successor to our "exit" condition block.
562 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000563 }
564
565 // Link up the condition block with the code that follows the loop.
566 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000567 ExitConditionBlock->addSuccessor(LoopSuccessor);
568
Ted Kremenek73543912007-08-23 21:42:29 +0000569 // If the loop contains initialization, create a new block for those
570 // statements. This block can also contain statements that precede
571 // the loop.
572 if (Stmt* I = F->getInit()) {
573 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000574 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000575 }
576 else {
577 // There is no loop initialization. We are thus basically a while
578 // loop. NULL out Block to force lazy block construction.
579 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000580 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000581 }
582}
583
584CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
585 // "while" is a control-flow statement. Thus we stop processing the
586 // current block.
587
588 CFGBlock* LoopSuccessor = NULL;
589
590 if (Block) {
591 FinishBlock(Block);
592 LoopSuccessor = Block;
593 }
594 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000595
596 // Because of short-circuit evaluation, the condition of the loop
597 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
598 // blocks that evaluate the condition.
599 CFGBlock* ExitConditionBlock = createBlock(false);
600 CFGBlock* EntryConditionBlock = ExitConditionBlock;
601
602 // Set the terminator for the "exit" condition block.
603 ExitConditionBlock->setTerminator(W);
604
605 // Now add the actual condition to the condition block. Because the
606 // condition itself may contain control-flow, new blocks may be created.
607 // Thus we update "Succ" after adding the condition.
608 if (Stmt* C = W->getCond()) {
609 Block = ExitConditionBlock;
610 EntryConditionBlock = addStmt(C);
611 if (Block) FinishBlock(EntryConditionBlock);
612 }
Ted Kremenek73543912007-08-23 21:42:29 +0000613
614 // The condition block is the implicit successor for the loop body as
615 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000616 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000617
618 // Process the loop body.
619 {
620 assert (W->getBody());
621
622 // Save the current values for Block, Succ, and continue and break targets
623 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
624 save_continue(ContinueTargetBlock),
625 save_break(BreakTargetBlock);
626
627 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000628 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000629
630 // All breaks should go to the code following the loop.
631 BreakTargetBlock = LoopSuccessor;
632
633 // NULL out Block to force lazy instantiation of blocks for the body.
634 Block = NULL;
635
636 // Create the body. The returned block is the entry to the loop body.
637 CFGBlock* BodyBlock = Visit(W->getBody());
638 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000639 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000640
641 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000642 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000643 }
644
645 // Link up the condition block with the code that follows the loop.
646 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000647 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000648
649 // There can be no more statements in the condition block
650 // since we loop back to this block. NULL out Block to force
651 // lazy creation of another block.
652 Block = NULL;
653
654 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000655 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000656}
657
658CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
659 // "do...while" is a control-flow statement. Thus we stop processing the
660 // current block.
661
662 CFGBlock* LoopSuccessor = NULL;
663
664 if (Block) {
665 FinishBlock(Block);
666 LoopSuccessor = Block;
667 }
668 else LoopSuccessor = Succ;
669
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000670 // Because of short-circuit evaluation, the condition of the loop
671 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
672 // blocks that evaluate the condition.
673 CFGBlock* ExitConditionBlock = createBlock(false);
674 CFGBlock* EntryConditionBlock = ExitConditionBlock;
675
676 // Set the terminator for the "exit" condition block.
677 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000678
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000679 // Now add the actual condition to the condition block. Because the
680 // condition itself may contain control-flow, new blocks may be created.
681 if (Stmt* C = D->getCond()) {
682 Block = ExitConditionBlock;
683 EntryConditionBlock = addStmt(C);
684 if (Block) FinishBlock(EntryConditionBlock);
685 }
Ted Kremenek73543912007-08-23 21:42:29 +0000686
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000687 // The condition block is the implicit successor for the loop body as
688 // well as any code above the loop.
689 Succ = EntryConditionBlock;
690
691
Ted Kremenek73543912007-08-23 21:42:29 +0000692 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000693 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000694 {
695 assert (D->getBody());
696
697 // Save the current values for Block, Succ, and continue and break targets
698 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
699 save_continue(ContinueTargetBlock),
700 save_break(BreakTargetBlock);
701
702 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000703 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000704
705 // All breaks should go to the code following the loop.
706 BreakTargetBlock = LoopSuccessor;
707
708 // NULL out Block to force lazy instantiation of blocks for the body.
709 Block = NULL;
710
711 // Create the body. The returned block is the entry to the loop body.
712 BodyBlock = Visit(D->getBody());
713 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000714 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000715
716 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000717 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000718 }
719
720 // Link up the condition block with the code that follows the loop.
721 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000722 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000723
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000724 // There can be no more statements in the body block(s)
725 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000726 // lazy creation of another block.
727 Block = NULL;
728
729 // Return the loop body, which is the dominating block for the loop.
730 return BodyBlock;
731}
732
733CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
734 // "continue" is a control-flow statement. Thus we stop processing the
735 // current block.
736 if (Block) FinishBlock(Block);
737
738 // Now create a new block that ends with the continue statement.
739 Block = createBlock(false);
740 Block->setTerminator(C);
741
742 // If there is no target for the continue, then we are looking at an
743 // incomplete AST. Handle this by not registering a successor.
744 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
745
746 return Block;
747}
748
749CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
750 // "break" is a control-flow statement. Thus we stop processing the
751 // current block.
752 if (Block) FinishBlock(Block);
753
754 // Now create a new block that ends with the continue statement.
755 Block = createBlock(false);
756 Block->setTerminator(B);
757
758 // If there is no target for the break, then we are looking at an
759 // incomplete AST. Handle this by not registering a successor.
760 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
761
762 return Block;
763}
764
765CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
766 // "switch" is a control-flow statement. Thus we stop processing the
767 // current block.
768 CFGBlock* SwitchSuccessor = NULL;
769
770 if (Block) {
771 FinishBlock(Block);
772 SwitchSuccessor = Block;
773 }
774 else SwitchSuccessor = Succ;
775
776 // Save the current "switch" context.
777 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
778 save_break(BreakTargetBlock);
779
780 // Create a new block that will contain the switch statement.
781 SwitchTerminatedBlock = createBlock(false);
782
Ted Kremenek73543912007-08-23 21:42:29 +0000783 // Now process the switch body. The code after the switch is the implicit
784 // successor.
785 Succ = SwitchSuccessor;
786 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000787
788 // When visiting the body, the case statements should automatically get
789 // linked up to the switch. We also don't keep a pointer to the body,
790 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000791 assert (S->getBody() && "switch must contain a non-NULL body");
792 Block = NULL;
793 CFGBlock *BodyBlock = Visit(S->getBody());
794 if (Block) FinishBlock(BodyBlock);
795
796 // Add the terminator and condition in the switch block.
797 SwitchTerminatedBlock->setTerminator(S);
798 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000799 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000800 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000801}
802
803CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
804 // A SwitchCase is either a "default" or "case" statement. We handle
805 // both in the same way. They are essentially labels, so they are the
806 // first statement in a block.
807 CFGBlock* CaseBlock = Visit(S->getSubStmt());
808 assert (CaseBlock);
809
Ted Kremenekec055e12007-08-29 23:20:49 +0000810 // Cases/Default statements partition block, so this is the top of
811 // the basic block we were processing (the case/default is the label).
812 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000813 FinishBlock(CaseBlock);
814
815 // Add this block to the list of successors for the block with the
816 // switch statement.
817 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
818
819 // We set Block to NULL to allow lazy creation of a new block (if necessary)
820 Block = NULL;
821
822 // This block is now the implicit successor of other blocks.
823 Succ = CaseBlock;
824
825 return CaseBlock;
826}
827
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000828CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
829 // Lazily create the indirect-goto dispatch block if there isn't one
830 // already.
831 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
832
833 if (!IBlock) {
834 IBlock = createBlock(false);
835 cfg->setIndirectGotoBlock(IBlock);
836 }
837
838 // IndirectGoto is a control-flow statement. Thus we stop processing the
839 // current block and create a new one.
840 if (Block) FinishBlock(Block);
841 Block = createBlock(false);
842 Block->setTerminator(I);
843 Block->addSuccessor(IBlock);
844 return addStmt(I->getTarget());
845}
846
Ted Kremenek73543912007-08-23 21:42:29 +0000847
Ted Kremenekd6e50602007-08-23 21:26:19 +0000848} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000849
850/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
851/// block has no successors or predecessors. If this is the first block
852/// created in the CFG, it is automatically set to be the Entry and Exit
853/// of the CFG.
854CFGBlock* CFG::createBlock(unsigned blockID) {
855 bool first_block = begin() == end();
856
857 // Create the block.
858 Blocks.push_front(CFGBlock(blockID));
859
860 // If this is the first block, set it as the Entry and Exit.
861 if (first_block) Entry = Exit = &front();
862
863 // Return the block.
864 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000865}
866
Ted Kremenek4db5b452007-08-23 16:51:22 +0000867/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
868/// CFG is returned to the caller.
869CFG* CFG::buildCFG(Stmt* Statement) {
870 CFGBuilder Builder;
871 return Builder.buildCFG(Statement);
872}
873
874/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000875void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
876
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000877
878//===----------------------------------------------------------------------===//
879// CFG pretty printing
880//===----------------------------------------------------------------------===//
881
Ted Kremenek4db5b452007-08-23 16:51:22 +0000882/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000883void CFG::dump() const { print(std::cerr); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000884
Ted Kremenek4db5b452007-08-23 16:51:22 +0000885/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000886void CFG::print(std::ostream& OS) const {
887
888 // Print the entry block.
889 getEntry().print(OS,this);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000890
Ted Kremenek4db5b452007-08-23 16:51:22 +0000891 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000892 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000893 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000894 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000895 I->print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000896 }
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000897
898 // Print the exit block.
899 getExit().print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000900}
901
Ted Kremenekd8313202007-08-22 18:22:34 +0000902namespace {
903
Ted Kremenek73543912007-08-23 21:42:29 +0000904class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
905 void > {
906 std::ostream& OS;
907public:
908 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
909
910 void VisitIfStmt(IfStmt* I) {
911 OS << "if ";
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000912 I->getCond()->printPretty(OS);
Ted Kremenek73543912007-08-23 21:42:29 +0000913 OS << "\n";
914 }
915
916 // Default case.
917 void VisitStmt(Stmt* S) { S->printPretty(OS); }
918
919 void VisitForStmt(ForStmt* F) {
920 OS << "for (" ;
921 if (Stmt* I = F->getInit()) I->printPretty(OS);
922 OS << " ; ";
923 if (Stmt* C = F->getCond()) C->printPretty(OS);
924 OS << " ; ";
925 if (Stmt* I = F->getInc()) I->printPretty(OS);
926 OS << ")\n";
927 }
928
929 void VisitWhileStmt(WhileStmt* W) {
930 OS << "while " ;
931 if (Stmt* C = W->getCond()) C->printPretty(OS);
932 OS << "\n";
933 }
934
935 void VisitDoStmt(DoStmt* D) {
936 OS << "do ... while ";
937 if (Stmt* C = D->getCond()) C->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000938 OS << '\n';
939 }
940
941 void VisitSwitchStmt(SwitchStmt* S) {
942 OS << "switch ";
943 S->getCond()->printPretty(OS);
944 OS << '\n';
945 }
946
Ted Kremenekcfaae762007-08-27 21:54:41 +0000947 void VisitExpr(Expr* E) {
948 E->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000949 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +0000950 }
Ted Kremenek73543912007-08-23 21:42:29 +0000951};
952} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000953
Ted Kremenek4db5b452007-08-23 16:51:22 +0000954/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000955void CFGBlock::dump(const CFG* cfg) const { print(std::cerr,cfg); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000956
Ted Kremenek4db5b452007-08-23 16:51:22 +0000957/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
958/// Generally this will only be called from CFG::print.
Ted Kremenekec055e12007-08-29 23:20:49 +0000959void CFGBlock::print(std::ostream& OS, const CFG* cfg, bool print_edges) const {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000960
961 // Print the header.
962 OS << "\n [ B" << getBlockID();
963 if (this == &cfg->getEntry()) { OS << " (ENTRY) ]\n"; }
964 else if (this == &cfg->getExit()) { OS << " (EXIT) ]\n"; }
965 else if (this == cfg->getIndirectGotoBlock()) {
966 OS << " (INDIRECT GOTO DISPATCH) ]\n";
967 }
968 else OS << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000969
Ted Kremenekec055e12007-08-29 23:20:49 +0000970 // Print the label of this block.
971 if (Stmt* S = const_cast<Stmt*>(getLabel())) {
972 if (print_edges) OS << " ";
973 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
974 OS << L->getName();
975 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
976 OS << "case ";
977 C->getLHS()->printPretty(OS);
978 if (C->getRHS()) {
979 OS << " ... ";
980 C->getRHS()->printPretty(OS);
981 }
982 }
983 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D)) {
984 OS << "default";
985 }
986 else assert(false && "Invalid label statement in CFGBlock.");
987
988 OS << ":\n";
989 }
990
Ted Kremenek97f75312007-08-21 21:42:03 +0000991 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +0000992 unsigned j = 1;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000993 for (const_iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekec055e12007-08-29 23:20:49 +0000994 // Print the statement # in the basic block and the statement itself.
995 if (print_edges) OS << " ";
996 OS << std::setw(3) << j << ": ";
997 (*I)->printPretty(OS);
998
Ted Kremenekc5de2222007-08-21 23:26:17 +0000999 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +00001000 if (isa<Expr>(*I)) OS << '\n';
1001 }
Ted Kremenek97f75312007-08-21 21:42:03 +00001002
Ted Kremenekec055e12007-08-29 23:20:49 +00001003 // Print the terminator of this block.
1004 if (getTerminator()) {
1005 if (print_edges) OS << " ";
1006 OS << " T: ";
1007 CFGBlockTerminatorPrint(OS).Visit(const_cast<Stmt*>(getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001008 }
1009
Ted Kremenekec055e12007-08-29 23:20:49 +00001010 if (print_edges) {
1011 // Print the predecessors of this block.
1012 OS << " Predecessors (" << pred_size() << "):";
1013 unsigned i = 0;
1014 for (const_pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i) {
1015 if (i == 8 || (i-8) == 0) {
1016 OS << "\n ";
1017 }
1018 OS << " B" << (*I)->getBlockID();
Ted Kremenek97f75312007-08-21 21:42:03 +00001019 }
Ted Kremenekec055e12007-08-29 23:20:49 +00001020 OS << '\n';
1021
1022 // Print the successors of this block.
1023 OS << " Successors (" << succ_size() << "):";
1024 i = 0;
1025 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i) {
1026 if (i == 8 || (i-8) % 10 == 0) {
1027 OS << "\n ";
1028 }
1029 OS << " B" << (*I)->getBlockID();
1030 }
1031 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001032 }
Ted Kremenek4db5b452007-08-23 16:51:22 +00001033}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001034
1035//===----------------------------------------------------------------------===//
1036// CFG Graphviz Visualization
1037//===----------------------------------------------------------------------===//
1038
1039namespace llvm {
1040template<>
1041struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1042 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1043
1044 std::ostringstream Out;
Ted Kremenekec055e12007-08-29 23:20:49 +00001045 Node->print(Out,Graph,false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001046 std::string OutStr = Out.str();
1047
1048 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1049
1050 // Process string output to make it nicer...
1051 for (unsigned i = 0; i != OutStr.length(); ++i)
1052 if (OutStr[i] == '\n') { // Left justify
1053 OutStr[i] = '\\';
1054 OutStr.insert(OutStr.begin()+i+1, 'l');
1055 }
1056
1057 return OutStr;
1058 }
1059};
1060} // end namespace llvm
1061
1062void CFG::viewCFG() const {
1063#ifndef NDEBUG
1064 llvm::ViewGraph(this,"CFG");
1065#else
1066 std::cerr << "CFG::viewCFG is only available in debug builds on "
1067 << "systems with Graphviz or gv!" << std::endl;
1068#endif
1069}