blob: f6b74e7f7b7580b0b60aba2eae5cef9cfd930d85 [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; }
Ted Kremenek44db7872007-08-30 18:13:31 +000037 T get() { return old_value; }
38
Ted Kremenekd6e50602007-08-23 21:26:19 +000039 T& X;
40 T old_value;
41};
Ted Kremenek97f75312007-08-21 21:42:03 +000042
43/// CFGBuilder - This class is implements CFG construction from an AST.
44/// The builder is stateful: an instance of the builder should be used to only
45/// construct a single CFG.
46///
47/// Example usage:
48///
49/// CFGBuilder builder;
50/// CFG* cfg = builder.BuildAST(stmt1);
51///
Ted Kremenek95e854d2007-08-21 22:06:14 +000052/// CFG construction is done via a recursive walk of an AST.
53/// We actually parse the AST in reverse order so that the successor
54/// of a basic block is constructed prior to its predecessor. This
55/// allows us to nicely capture implicit fall-throughs without extra
56/// basic blocks.
57///
58class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000059 CFG* cfg;
60 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000061 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000062 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000063 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000064 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000065 unsigned NumBlocks;
66
Ted Kremenek0edd3a92007-08-28 19:26:49 +000067 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000068 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
69 LabelMapTy LabelMap;
70
Ted Kremenek0edd3a92007-08-28 19:26:49 +000071 // A list of blocks that end with a "goto" that must be backpatched to
72 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000073 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000074 BackpatchBlocksTy BackpatchBlocks;
75
Ted Kremenek0edd3a92007-08-28 19:26:49 +000076 // A list of labels whose address has been taken (for indirect gotos).
77 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
78 LabelSetTy AddressTakenLabels;
79
Ted Kremenek97f75312007-08-21 21:42:03 +000080public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000081 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000082 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremeneke809ebf2007-08-23 18:43:24 +000083 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000084 NumBlocks(0) {
85 // Create an empty CFG.
86 cfg = new CFG();
87 }
88
89 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000090
Ted Kremenek73543912007-08-23 21:42:29 +000091 // buildCFG - Used by external clients to construct the CFG.
92 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000093
Ted Kremenek73543912007-08-23 21:42:29 +000094 // Visitors to walk an AST and construct the CFG. Called by
95 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000096
Ted Kremenek73543912007-08-23 21:42:29 +000097 CFGBlock* VisitStmt(Stmt* Statement);
98 CFGBlock* VisitNullStmt(NullStmt* Statement);
99 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
100 CFGBlock* VisitIfStmt(IfStmt* I);
101 CFGBlock* VisitReturnStmt(ReturnStmt* R);
102 CFGBlock* VisitLabelStmt(LabelStmt* L);
103 CFGBlock* VisitGotoStmt(GotoStmt* G);
104 CFGBlock* VisitForStmt(ForStmt* F);
105 CFGBlock* VisitWhileStmt(WhileStmt* W);
106 CFGBlock* VisitDoStmt(DoStmt* D);
107 CFGBlock* VisitContinueStmt(ContinueStmt* C);
108 CFGBlock* VisitBreakStmt(BreakStmt* B);
109 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
110 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000111 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000112
Ted Kremenek73543912007-08-23 21:42:29 +0000113private:
114 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000115 CFGBlock* addStmt(Stmt* S);
116 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
117 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000118 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000119 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenek73543912007-08-23 21:42:29 +0000120 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000121
Ted Kremenek97f75312007-08-21 21:42:03 +0000122};
Ted Kremenek73543912007-08-23 21:42:29 +0000123
124/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
125/// represent an arbitrary statement. Examples include a single expression
126/// or a function body (compound statement). The ownership of the returned
127/// CFG is transferred to the caller. If CFG construction fails, this method
128/// returns NULL.
129CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000130 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000131 if (!Statement) return NULL;
132
133 // Create an empty block that will serve as the exit block for the CFG.
134 // Since this is the first block added to the CFG, it will be implicitly
135 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000136 Succ = createBlock();
137 assert (Succ == &cfg->getExit());
138 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000139
140 // Visit the statements and create the CFG.
141 if (CFGBlock* B = Visit(Statement)) {
142 // Finalize the last constructed block. This usually involves
143 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000144 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000145
146 // Backpatch the gotos whose label -> block mappings we didn't know
147 // when we encountered them.
148 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
149 E = BackpatchBlocks.end(); I != E; ++I ) {
150
151 CFGBlock* B = *I;
152 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
153 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
154
155 // If there is no target for the goto, then we are looking at an
156 // incomplete AST. Handle this by not registering a successor.
157 if (LI == LabelMap.end()) continue;
158
159 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000160 }
Ted Kremenek73543912007-08-23 21:42:29 +0000161
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000162 // Add successors to the Indirect Goto Dispatch block (if we have one).
163 if (CFGBlock* B = cfg->getIndirectGotoBlock())
164 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
165 E = AddressTakenLabels.end(); I != E; ++I ) {
166
167 // Lookup the target block.
168 LabelMapTy::iterator LI = LabelMap.find(*I);
169
170 // If there is no target block that contains label, then we are looking
171 // at an incomplete AST. Handle this by not registering a successor.
172 if (LI == LabelMap.end()) continue;
173
174 B->addSuccessor(LI->second);
175 }
176
177 // Create an empty entry block that has no predecessors.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000178 if (B->pred_size() > 0) {
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000179 Succ = B;
180 cfg->setEntry(createBlock());
181 }
182 else cfg->setEntry(B);
183
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000184 // NULL out cfg so that repeated calls to the builder will fail and that
185 // the ownership of the constructed CFG is passed to the caller.
Ted Kremenek73543912007-08-23 21:42:29 +0000186 CFG* t = cfg;
187 cfg = NULL;
188 return t;
189 }
190 else return NULL;
191}
192
193/// createBlock - Used to lazily create blocks that are connected
194/// to the current (global) succcessor.
195CFGBlock* CFGBuilder::createBlock(bool add_successor) {
196 CFGBlock* B = cfg->createBlock(NumBlocks++);
197 if (add_successor && Succ) B->addSuccessor(Succ);
198 return B;
199}
200
201/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000202/// we must reverse the statements because they have been inserted
203/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000204void CFGBuilder::FinishBlock(CFGBlock* B) {
205 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000206 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000207}
208
Ted Kremenek65cfa562007-08-27 21:27:44 +0000209/// addStmt - Used to add statements/expressions to the current CFGBlock
210/// "Block". This method calls WalkAST on the passed statement to see if it
211/// contains any short-circuit expressions. If so, it recursively creates
212/// the necessary blocks for such expressions. It returns the "topmost" block
213/// of the created blocks, or the original value of "Block" when this method
214/// was called if no additional blocks are created.
215CFGBlock* CFGBuilder::addStmt(Stmt* S) {
216 assert (Block);
217 return WalkAST(S,true);
218}
219
220/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000221/// add extra blocks for ternary operators, &&, and ||. We also
222/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek65cfa562007-08-27 21:27:44 +0000223CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
224 switch (S->getStmtClass()) {
225 case Stmt::ConditionalOperatorClass: {
226 ConditionalOperator* C = cast<ConditionalOperator>(S);
227
228 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
229 ConfluenceBlock->appendStmt(C);
230 FinishBlock(ConfluenceBlock);
231
232 Succ = ConfluenceBlock;
233 Block = NULL;
234 CFGBlock* LHSBlock = Visit(C->getLHS());
235
236 Succ = ConfluenceBlock;
237 Block = NULL;
238 CFGBlock* RHSBlock = Visit(C->getRHS());
239
240 Block = createBlock(false);
241 Block->addSuccessor(LHSBlock);
242 Block->addSuccessor(RHSBlock);
243 Block->setTerminator(C);
244 return addStmt(C->getCond());
245 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000246
Ted Kremeneke822b622007-08-28 18:14:37 +0000247 case Stmt::DeclStmtClass:
248 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
249 Block->appendStmt(S);
250 return WalkAST_VisitVarDecl(V);
251 }
252 else return Block;
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000253
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000254 case Stmt::AddrLabelExprClass: {
255 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
256 AddressTakenLabels.insert(A->getLabel());
257
258 if (AlwaysAddStmt) Block->appendStmt(S);
259 return Block;
260 }
261
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000262 case Stmt::StmtExprClass:
263 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000264
Ted Kremenekcfaae762007-08-27 21:54:41 +0000265 case Stmt::BinaryOperatorClass: {
266 BinaryOperator* B = cast<BinaryOperator>(S);
267
268 if (B->isLogicalOp()) { // && or ||
269 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
270 ConfluenceBlock->appendStmt(B);
271 FinishBlock(ConfluenceBlock);
272
273 // create the block evaluating the LHS
274 CFGBlock* LHSBlock = createBlock(false);
275 LHSBlock->addSuccessor(ConfluenceBlock);
276 LHSBlock->setTerminator(B);
277
278 // create the block evaluating the RHS
279 Succ = ConfluenceBlock;
280 Block = NULL;
281 CFGBlock* RHSBlock = Visit(B->getRHS());
282 LHSBlock->addSuccessor(RHSBlock);
283
284 // Generate the blocks for evaluating the LHS.
285 Block = LHSBlock;
286 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000287 }
288 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
289 Block->appendStmt(B);
290 addStmt(B->getRHS());
291 return addStmt(B->getLHS());
Ted Kremenekcfaae762007-08-27 21:54:41 +0000292 }
293
294 // Fall through to the default case.
295 }
296
Ted Kremenek65cfa562007-08-27 21:27:44 +0000297 default:
298 if (AlwaysAddStmt) Block->appendStmt(S);
299 return WalkAST_VisitChildren(S);
300 };
301}
302
Ted Kremeneke822b622007-08-28 18:14:37 +0000303/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
304/// DeclStmts. Because the initialization code for declarations can
305/// contain arbitrary expressions, we must linearize declarations
306/// to handle arbitrary control-flow induced by those expressions.
307CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
308 // We actually must parse the LAST declaration in a chain of
309 // declarations first, because we are building the CFG in reverse
310 // order.
311 if (Decl* D = V->getNextDeclarator())
312 if (VarDecl* Next = cast<VarDecl>(D))
313 Block = WalkAST_VisitVarDecl(Next);
314
315 if (Expr* E = V->getInit())
316 return addStmt(E);
317
318 assert (Block);
319 return Block;
320}
321
Ted Kremenek65cfa562007-08-27 21:27:44 +0000322/// WalkAST_VisitChildren - Utility method to call WalkAST on the
323/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000324CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000325 CFGBlock* B = Block;
326 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
327 I != E; ++I)
328 B = WalkAST(*I);
329
330 return B;
331}
332
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000333/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
334/// expressions (a GCC extension).
335CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
336 Block->appendStmt(S);
337 return VisitCompoundStmt(S->getSubStmt());
338}
339
Ted Kremenek73543912007-08-23 21:42:29 +0000340/// VisitStmt - Handle statements with no branching control flow.
341CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
342 // We cannot assume that we are in the middle of a basic block, since
343 // the CFG might only be constructed for this single statement. If
344 // we have no current basic block, just create one lazily.
345 if (!Block) Block = createBlock();
346
347 // Simply add the statement to the current block. We actually
348 // insert statements in reverse order; this order is reversed later
349 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000350 addStmt(Statement);
351
Ted Kremenek73543912007-08-23 21:42:29 +0000352 return Block;
353}
354
355CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
356 return Block;
357}
358
359CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
360 // The value returned from this function is the last created CFGBlock
361 // that represents the "entry" point for the translated AST node.
362 CFGBlock* LastBlock;
363
364 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
365 E = C->body_rend(); I != E; ++I )
366 // Add the statement to the current block.
367 if (!(LastBlock=Visit(*I)))
368 return NULL;
369
370 return LastBlock;
371}
372
373CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
374 // We may see an if statement in the middle of a basic block, or
375 // it may be the first statement we are processing. In either case,
376 // we create a new basic block. First, we create the blocks for
377 // the then...else statements, and then we create the block containing
378 // the if statement. If we were in the middle of a block, we
379 // stop processing that block and reverse its statements. That block
380 // is then the implicit successor for the "then" and "else" clauses.
381
382 // The block we were proccessing is now finished. Make it the
383 // successor block.
384 if (Block) {
385 Succ = Block;
386 FinishBlock(Block);
387 }
388
389 // Process the false branch. NULL out Block so that the recursive
390 // call to Visit will create a new basic block.
391 // Null out Block so that all successor
392 CFGBlock* ElseBlock = Succ;
393
394 if (Stmt* Else = I->getElse()) {
395 SaveAndRestore<CFGBlock*> sv(Succ);
396
397 // NULL out Block so that the recursive call to Visit will
398 // create a new basic block.
399 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000400 ElseBlock = Visit(Else);
401
402 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
403 ElseBlock = sv.get();
404 else if (Block)
405 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000406 }
407
408 // Process the true branch. NULL out Block so that the recursive
409 // call to Visit will create a new basic block.
410 // Null out Block so that all successor
411 CFGBlock* ThenBlock;
412 {
413 Stmt* Then = I->getThen();
414 assert (Then);
415 SaveAndRestore<CFGBlock*> sv(Succ);
416 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000417 ThenBlock = Visit(Then);
418
419 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
420 ThenBlock = sv.get();
421 else if (Block)
422 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000423 }
424
425 // Now create a new block containing the if statement.
426 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000427
428 // Set the terminator of the new block to the If statement.
429 Block->setTerminator(I);
430
431 // Now add the successors.
432 Block->addSuccessor(ThenBlock);
433 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000434
435 // Add the condition as the last statement in the new block. This
436 // may create new blocks as the condition may contain control-flow. Any
437 // newly created blocks will be pointed to be "Block".
438 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000439}
440
441CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
442 // If we were in the middle of a block we stop processing that block
443 // and reverse its statements.
444 //
445 // NOTE: If a "return" appears in the middle of a block, this means
446 // that the code afterwards is DEAD (unreachable). We still
447 // keep a basic block for that code; a simple "mark-and-sweep"
448 // from the entry block will be able to report such dead
449 // blocks.
450 if (Block) FinishBlock(Block);
451
452 // Create the new block.
453 Block = createBlock(false);
454
455 // The Exit block is the only successor.
456 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000457
458 // Add the return statement to the block. This may create new blocks
459 // if R contains control-flow (short-circuit operations).
460 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000461}
462
463CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
464 // Get the block of the labeled statement. Add it to our map.
465 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000466
467 if (!LabelBlock) // This can happen when the body is empty, i.e.
468 LabelBlock=createBlock(); // scopes that only contains NullStmts.
469
Ted Kremenek73543912007-08-23 21:42:29 +0000470 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
471 LabelMap[ L ] = LabelBlock;
472
473 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000474 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000475 // label (and we have already processed the substatement) there is no
476 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000477 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000478 FinishBlock(LabelBlock);
479
480 // We set Block to NULL to allow lazy creation of a new block
481 // (if necessary);
482 Block = NULL;
483
484 // This block is now the implicit successor of other blocks.
485 Succ = LabelBlock;
486
487 return LabelBlock;
488}
489
490CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
491 // Goto is a control-flow statement. Thus we stop processing the
492 // current block and create a new one.
493 if (Block) FinishBlock(Block);
494 Block = createBlock(false);
495 Block->setTerminator(G);
496
497 // If we already know the mapping to the label block add the
498 // successor now.
499 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
500
501 if (I == LabelMap.end())
502 // We will need to backpatch this block later.
503 BackpatchBlocks.push_back(Block);
504 else
505 Block->addSuccessor(I->second);
506
507 return Block;
508}
509
510CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
511 // "for" is a control-flow statement. Thus we stop processing the
512 // current block.
513
514 CFGBlock* LoopSuccessor = NULL;
515
516 if (Block) {
517 FinishBlock(Block);
518 LoopSuccessor = Block;
519 }
520 else LoopSuccessor = Succ;
521
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000522 // Because of short-circuit evaluation, the condition of the loop
523 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
524 // blocks that evaluate the condition.
525 CFGBlock* ExitConditionBlock = createBlock(false);
526 CFGBlock* EntryConditionBlock = ExitConditionBlock;
527
528 // Set the terminator for the "exit" condition block.
529 ExitConditionBlock->setTerminator(F);
530
531 // Now add the actual condition to the condition block. Because the
532 // condition itself may contain control-flow, new blocks may be created.
533 if (Stmt* C = F->getCond()) {
534 Block = ExitConditionBlock;
535 EntryConditionBlock = addStmt(C);
536 if (Block) FinishBlock(EntryConditionBlock);
537 }
Ted Kremenek73543912007-08-23 21:42:29 +0000538
539 // The condition block is the implicit successor for the loop body as
540 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000541 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000542
543 // Now create the loop body.
544 {
545 assert (F->getBody());
546
547 // Save the current values for Block, Succ, and continue and break targets
548 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
549 save_continue(ContinueTargetBlock),
550 save_break(BreakTargetBlock);
551
552 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000553 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000554
555 // All breaks should go to the code following the loop.
556 BreakTargetBlock = LoopSuccessor;
557
558 // Create a new block to contain the (bottom) of the loop body.
559 Block = createBlock();
560
561 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000562 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000563
564 // Now populate the body block, and in the process create new blocks
565 // as we walk the body of the loop.
566 CFGBlock* BodyBlock = Visit(F->getBody());
567 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000568 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000569
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000570 // This new body block is a successor to our "exit" condition block.
571 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000572 }
573
574 // Link up the condition block with the code that follows the loop.
575 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000576 ExitConditionBlock->addSuccessor(LoopSuccessor);
577
Ted Kremenek73543912007-08-23 21:42:29 +0000578 // If the loop contains initialization, create a new block for those
579 // statements. This block can also contain statements that precede
580 // the loop.
581 if (Stmt* I = F->getInit()) {
582 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000583 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000584 }
585 else {
586 // There is no loop initialization. We are thus basically a while
587 // loop. NULL out Block to force lazy block construction.
588 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000589 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000590 }
591}
592
593CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
594 // "while" is a control-flow statement. Thus we stop processing the
595 // current block.
596
597 CFGBlock* LoopSuccessor = NULL;
598
599 if (Block) {
600 FinishBlock(Block);
601 LoopSuccessor = Block;
602 }
603 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000604
605 // Because of short-circuit evaluation, the condition of the loop
606 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
607 // blocks that evaluate the condition.
608 CFGBlock* ExitConditionBlock = createBlock(false);
609 CFGBlock* EntryConditionBlock = ExitConditionBlock;
610
611 // Set the terminator for the "exit" condition block.
612 ExitConditionBlock->setTerminator(W);
613
614 // Now add the actual condition to the condition block. Because the
615 // condition itself may contain control-flow, new blocks may be created.
616 // Thus we update "Succ" after adding the condition.
617 if (Stmt* C = W->getCond()) {
618 Block = ExitConditionBlock;
619 EntryConditionBlock = addStmt(C);
620 if (Block) FinishBlock(EntryConditionBlock);
621 }
Ted Kremenek73543912007-08-23 21:42:29 +0000622
623 // The condition block is the implicit successor for the loop body as
624 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000625 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000626
627 // Process the loop body.
628 {
629 assert (W->getBody());
630
631 // Save the current values for Block, Succ, and continue and break targets
632 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
633 save_continue(ContinueTargetBlock),
634 save_break(BreakTargetBlock);
635
636 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000637 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000638
639 // All breaks should go to the code following the loop.
640 BreakTargetBlock = LoopSuccessor;
641
642 // NULL out Block to force lazy instantiation of blocks for the body.
643 Block = NULL;
644
645 // Create the body. The returned block is the entry to the loop body.
646 CFGBlock* BodyBlock = Visit(W->getBody());
647 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000648 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000649
650 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000651 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000652 }
653
654 // Link up the condition block with the code that follows the loop.
655 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000656 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000657
658 // There can be no more statements in the condition block
659 // since we loop back to this block. NULL out Block to force
660 // lazy creation of another block.
661 Block = NULL;
662
663 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000664 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000665}
666
667CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
668 // "do...while" is a control-flow statement. Thus we stop processing the
669 // current block.
670
671 CFGBlock* LoopSuccessor = NULL;
672
673 if (Block) {
674 FinishBlock(Block);
675 LoopSuccessor = Block;
676 }
677 else LoopSuccessor = Succ;
678
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000679 // Because of short-circuit evaluation, the condition of the loop
680 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
681 // blocks that evaluate the condition.
682 CFGBlock* ExitConditionBlock = createBlock(false);
683 CFGBlock* EntryConditionBlock = ExitConditionBlock;
684
685 // Set the terminator for the "exit" condition block.
686 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000687
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000688 // Now add the actual condition to the condition block. Because the
689 // condition itself may contain control-flow, new blocks may be created.
690 if (Stmt* C = D->getCond()) {
691 Block = ExitConditionBlock;
692 EntryConditionBlock = addStmt(C);
693 if (Block) FinishBlock(EntryConditionBlock);
694 }
Ted Kremenek73543912007-08-23 21:42:29 +0000695
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000696 // The condition block is the implicit successor for the loop body as
697 // well as any code above the loop.
698 Succ = EntryConditionBlock;
699
700
Ted Kremenek73543912007-08-23 21:42:29 +0000701 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000702 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000703 {
704 assert (D->getBody());
705
706 // Save the current values for Block, Succ, and continue and break targets
707 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
708 save_continue(ContinueTargetBlock),
709 save_break(BreakTargetBlock);
710
711 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000712 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000713
714 // All breaks should go to the code following the loop.
715 BreakTargetBlock = LoopSuccessor;
716
717 // NULL out Block to force lazy instantiation of blocks for the body.
718 Block = NULL;
719
720 // Create the body. The returned block is the entry to the loop body.
721 BodyBlock = Visit(D->getBody());
722 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000723 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000724
725 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000726 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000727 }
728
729 // Link up the condition block with the code that follows the loop.
730 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000731 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000732
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000733 // There can be no more statements in the body block(s)
734 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000735 // lazy creation of another block.
736 Block = NULL;
737
738 // Return the loop body, which is the dominating block for the loop.
739 return BodyBlock;
740}
741
742CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
743 // "continue" is a control-flow statement. Thus we stop processing the
744 // current block.
745 if (Block) FinishBlock(Block);
746
747 // Now create a new block that ends with the continue statement.
748 Block = createBlock(false);
749 Block->setTerminator(C);
750
751 // If there is no target for the continue, then we are looking at an
752 // incomplete AST. Handle this by not registering a successor.
753 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
754
755 return Block;
756}
757
758CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
759 // "break" is a control-flow statement. Thus we stop processing the
760 // current block.
761 if (Block) FinishBlock(Block);
762
763 // Now create a new block that ends with the continue statement.
764 Block = createBlock(false);
765 Block->setTerminator(B);
766
767 // If there is no target for the break, then we are looking at an
768 // incomplete AST. Handle this by not registering a successor.
769 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
770
771 return Block;
772}
773
774CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
775 // "switch" is a control-flow statement. Thus we stop processing the
776 // current block.
777 CFGBlock* SwitchSuccessor = NULL;
778
779 if (Block) {
780 FinishBlock(Block);
781 SwitchSuccessor = Block;
782 }
783 else SwitchSuccessor = Succ;
784
785 // Save the current "switch" context.
786 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
787 save_break(BreakTargetBlock);
788
789 // Create a new block that will contain the switch statement.
790 SwitchTerminatedBlock = createBlock(false);
791
Ted Kremenek73543912007-08-23 21:42:29 +0000792 // Now process the switch body. The code after the switch is the implicit
793 // successor.
794 Succ = SwitchSuccessor;
795 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000796
797 // When visiting the body, the case statements should automatically get
798 // linked up to the switch. We also don't keep a pointer to the body,
799 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000800 assert (S->getBody() && "switch must contain a non-NULL body");
801 Block = NULL;
802 CFGBlock *BodyBlock = Visit(S->getBody());
803 if (Block) FinishBlock(BodyBlock);
804
805 // Add the terminator and condition in the switch block.
806 SwitchTerminatedBlock->setTerminator(S);
807 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000808 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000809 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000810}
811
812CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
813 // A SwitchCase is either a "default" or "case" statement. We handle
814 // both in the same way. They are essentially labels, so they are the
815 // first statement in a block.
816 CFGBlock* CaseBlock = Visit(S->getSubStmt());
817 assert (CaseBlock);
818
Ted Kremenekec055e12007-08-29 23:20:49 +0000819 // Cases/Default statements partition block, so this is the top of
820 // the basic block we were processing (the case/default is the label).
821 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000822 FinishBlock(CaseBlock);
823
824 // Add this block to the list of successors for the block with the
825 // switch statement.
826 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
827
828 // We set Block to NULL to allow lazy creation of a new block (if necessary)
829 Block = NULL;
830
831 // This block is now the implicit successor of other blocks.
832 Succ = CaseBlock;
833
834 return CaseBlock;
835}
836
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000837CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
838 // Lazily create the indirect-goto dispatch block if there isn't one
839 // already.
840 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
841
842 if (!IBlock) {
843 IBlock = createBlock(false);
844 cfg->setIndirectGotoBlock(IBlock);
845 }
846
847 // IndirectGoto is a control-flow statement. Thus we stop processing the
848 // current block and create a new one.
849 if (Block) FinishBlock(Block);
850 Block = createBlock(false);
851 Block->setTerminator(I);
852 Block->addSuccessor(IBlock);
853 return addStmt(I->getTarget());
854}
855
Ted Kremenek73543912007-08-23 21:42:29 +0000856
Ted Kremenekd6e50602007-08-23 21:26:19 +0000857} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000858
859/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
860/// block has no successors or predecessors. If this is the first block
861/// created in the CFG, it is automatically set to be the Entry and Exit
862/// of the CFG.
863CFGBlock* CFG::createBlock(unsigned blockID) {
864 bool first_block = begin() == end();
865
866 // Create the block.
867 Blocks.push_front(CFGBlock(blockID));
868
869 // If this is the first block, set it as the Entry and Exit.
870 if (first_block) Entry = Exit = &front();
871
872 // Return the block.
873 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000874}
875
Ted Kremenek4db5b452007-08-23 16:51:22 +0000876/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
877/// CFG is returned to the caller.
878CFG* CFG::buildCFG(Stmt* Statement) {
879 CFGBuilder Builder;
880 return Builder.buildCFG(Statement);
881}
882
883/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000884void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
885
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000886
887//===----------------------------------------------------------------------===//
888// CFG pretty printing
889//===----------------------------------------------------------------------===//
890
Ted Kremenek4db5b452007-08-23 16:51:22 +0000891/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000892void CFG::dump() const { print(std::cerr); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000893
Ted Kremenek4db5b452007-08-23 16:51:22 +0000894/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000895void CFG::print(std::ostream& OS) const {
896
897 // Print the entry block.
898 getEntry().print(OS,this);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000899
Ted Kremenek4db5b452007-08-23 16:51:22 +0000900 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000901 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000902 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000903 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000904 I->print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000905 }
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000906
907 // Print the exit block.
908 getExit().print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000909}
910
Ted Kremenekd8313202007-08-22 18:22:34 +0000911namespace {
912
Ted Kremenek73543912007-08-23 21:42:29 +0000913class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
914 void > {
915 std::ostream& OS;
916public:
917 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
918
919 void VisitIfStmt(IfStmt* I) {
920 OS << "if ";
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000921 I->getCond()->printPretty(OS);
Ted Kremenek73543912007-08-23 21:42:29 +0000922 OS << "\n";
923 }
924
925 // Default case.
926 void VisitStmt(Stmt* S) { S->printPretty(OS); }
927
928 void VisitForStmt(ForStmt* F) {
929 OS << "for (" ;
930 if (Stmt* I = F->getInit()) I->printPretty(OS);
931 OS << " ; ";
932 if (Stmt* C = F->getCond()) C->printPretty(OS);
933 OS << " ; ";
934 if (Stmt* I = F->getInc()) I->printPretty(OS);
935 OS << ")\n";
936 }
937
938 void VisitWhileStmt(WhileStmt* W) {
939 OS << "while " ;
940 if (Stmt* C = W->getCond()) C->printPretty(OS);
941 OS << "\n";
942 }
943
944 void VisitDoStmt(DoStmt* D) {
945 OS << "do ... while ";
946 if (Stmt* C = D->getCond()) C->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000947 OS << '\n';
948 }
949
950 void VisitSwitchStmt(SwitchStmt* S) {
951 OS << "switch ";
952 S->getCond()->printPretty(OS);
953 OS << '\n';
954 }
955
Ted Kremenekcfaae762007-08-27 21:54:41 +0000956 void VisitExpr(Expr* E) {
957 E->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000958 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +0000959 }
Ted Kremenek73543912007-08-23 21:42:29 +0000960};
961} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000962
Ted Kremenek4db5b452007-08-23 16:51:22 +0000963/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000964void CFGBlock::dump(const CFG* cfg) const { print(std::cerr,cfg); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000965
Ted Kremenek4db5b452007-08-23 16:51:22 +0000966/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
967/// Generally this will only be called from CFG::print.
Ted Kremenekec055e12007-08-29 23:20:49 +0000968void CFGBlock::print(std::ostream& OS, const CFG* cfg, bool print_edges) const {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000969
970 // Print the header.
971 OS << "\n [ B" << getBlockID();
972 if (this == &cfg->getEntry()) { OS << " (ENTRY) ]\n"; }
973 else if (this == &cfg->getExit()) { OS << " (EXIT) ]\n"; }
974 else if (this == cfg->getIndirectGotoBlock()) {
975 OS << " (INDIRECT GOTO DISPATCH) ]\n";
976 }
977 else OS << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000978
Ted Kremenekec055e12007-08-29 23:20:49 +0000979 // Print the label of this block.
980 if (Stmt* S = const_cast<Stmt*>(getLabel())) {
981 if (print_edges) OS << " ";
982 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
983 OS << L->getName();
984 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
985 OS << "case ";
986 C->getLHS()->printPretty(OS);
987 if (C->getRHS()) {
988 OS << " ... ";
989 C->getRHS()->printPretty(OS);
990 }
991 }
992 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D)) {
993 OS << "default";
994 }
995 else assert(false && "Invalid label statement in CFGBlock.");
996
997 OS << ":\n";
998 }
999
Ted Kremenek97f75312007-08-21 21:42:03 +00001000 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001001 unsigned j = 1;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001002 for (const_iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001003 // Print the statement # in the basic block and the statement itself.
1004 if (print_edges) OS << " ";
1005 OS << std::setw(3) << j << ": ";
1006 (*I)->printPretty(OS);
1007
Ted Kremenekc5de2222007-08-21 23:26:17 +00001008 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +00001009 if (isa<Expr>(*I)) OS << '\n';
1010 }
Ted Kremenek97f75312007-08-21 21:42:03 +00001011
Ted Kremenekec055e12007-08-29 23:20:49 +00001012 // Print the terminator of this block.
1013 if (getTerminator()) {
1014 if (print_edges) OS << " ";
1015 OS << " T: ";
1016 CFGBlockTerminatorPrint(OS).Visit(const_cast<Stmt*>(getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001017 }
1018
Ted Kremenekec055e12007-08-29 23:20:49 +00001019 if (print_edges) {
1020 // Print the predecessors of this block.
1021 OS << " Predecessors (" << pred_size() << "):";
1022 unsigned i = 0;
1023 for (const_pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i) {
1024 if (i == 8 || (i-8) == 0) {
1025 OS << "\n ";
1026 }
1027 OS << " B" << (*I)->getBlockID();
Ted Kremenek97f75312007-08-21 21:42:03 +00001028 }
Ted Kremenekec055e12007-08-29 23:20:49 +00001029 OS << '\n';
1030
1031 // Print the successors of this block.
1032 OS << " Successors (" << succ_size() << "):";
1033 i = 0;
1034 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i) {
1035 if (i == 8 || (i-8) % 10 == 0) {
1036 OS << "\n ";
1037 }
1038 OS << " B" << (*I)->getBlockID();
1039 }
1040 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001041 }
Ted Kremenek4db5b452007-08-23 16:51:22 +00001042}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001043
1044//===----------------------------------------------------------------------===//
1045// CFG Graphviz Visualization
1046//===----------------------------------------------------------------------===//
1047
1048namespace llvm {
1049template<>
1050struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1051 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1052
1053 std::ostringstream Out;
Ted Kremenekec055e12007-08-29 23:20:49 +00001054 Node->print(Out,Graph,false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001055 std::string OutStr = Out.str();
1056
1057 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1058
1059 // Process string output to make it nicer...
1060 for (unsigned i = 0; i != OutStr.length(); ++i)
1061 if (OutStr[i] == '\n') { // Left justify
1062 OutStr[i] = '\\';
1063 OutStr.insert(OutStr.begin()+i+1, 'l');
1064 }
1065
1066 return OutStr;
1067 }
1068};
1069} // end namespace llvm
1070
1071void CFG::viewCFG() const {
1072#ifndef NDEBUG
1073 llvm::ViewGraph(this,"CFG");
1074#else
1075 std::cerr << "CFG::viewCFG is only available in debug builds on "
1076 << "systems with Graphviz or gv!" << std::endl;
1077#endif
1078}