blob: 2c9336e3814fdaba6055d5815d1c9e33b4def6ad [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) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000216 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-08-27 21:27:44 +0000217 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
Ted Kremenek390b9762007-08-30 18:39:40 +0000558 // Create a new block to contain the (bottom) of the loop body.
559 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000560
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());
Ted Kremenek390b9762007-08-30 18:39:40 +0000567
568 if (!BodyBlock)
569 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
570 else if (Block)
571 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000572
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000573 // This new body block is a successor to our "exit" condition block.
574 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000575 }
576
577 // Link up the condition block with the code that follows the loop.
578 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000579 ExitConditionBlock->addSuccessor(LoopSuccessor);
580
Ted Kremenek73543912007-08-23 21:42:29 +0000581 // If the loop contains initialization, create a new block for those
582 // statements. This block can also contain statements that precede
583 // the loop.
584 if (Stmt* I = F->getInit()) {
585 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000586 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000587 }
588 else {
589 // There is no loop initialization. We are thus basically a while
590 // loop. NULL out Block to force lazy block construction.
591 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000592 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000593 }
594}
595
596CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
597 // "while" is a control-flow statement. Thus we stop processing the
598 // current block.
599
600 CFGBlock* LoopSuccessor = NULL;
601
602 if (Block) {
603 FinishBlock(Block);
604 LoopSuccessor = Block;
605 }
606 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000607
608 // Because of short-circuit evaluation, the condition of the loop
609 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
610 // blocks that evaluate the condition.
611 CFGBlock* ExitConditionBlock = createBlock(false);
612 CFGBlock* EntryConditionBlock = ExitConditionBlock;
613
614 // Set the terminator for the "exit" condition block.
615 ExitConditionBlock->setTerminator(W);
616
617 // Now add the actual condition to the condition block. Because the
618 // condition itself may contain control-flow, new blocks may be created.
619 // Thus we update "Succ" after adding the condition.
620 if (Stmt* C = W->getCond()) {
621 Block = ExitConditionBlock;
622 EntryConditionBlock = addStmt(C);
623 if (Block) FinishBlock(EntryConditionBlock);
624 }
Ted Kremenek73543912007-08-23 21:42:29 +0000625
626 // The condition block is the implicit successor for the loop body as
627 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000628 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000629
630 // Process the loop body.
631 {
632 assert (W->getBody());
633
634 // Save the current values for Block, Succ, and continue and break targets
635 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
636 save_continue(ContinueTargetBlock),
637 save_break(BreakTargetBlock);
638
639 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000640 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000641
642 // All breaks should go to the code following the loop.
643 BreakTargetBlock = LoopSuccessor;
644
645 // NULL out Block to force lazy instantiation of blocks for the body.
646 Block = NULL;
647
648 // Create the body. The returned block is the entry to the loop body.
649 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000650
651 if (!BodyBlock)
652 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
653 else if (Block)
654 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000655
656 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000657 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000658 }
659
660 // Link up the condition block with the code that follows the loop.
661 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000662 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000663
664 // There can be no more statements in the condition block
665 // since we loop back to this block. NULL out Block to force
666 // lazy creation of another block.
667 Block = NULL;
668
669 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000670 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000671}
672
673CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
674 // "do...while" is a control-flow statement. Thus we stop processing the
675 // current block.
676
677 CFGBlock* LoopSuccessor = NULL;
678
679 if (Block) {
680 FinishBlock(Block);
681 LoopSuccessor = Block;
682 }
683 else LoopSuccessor = Succ;
684
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000685 // Because of short-circuit evaluation, the condition of the loop
686 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
687 // blocks that evaluate the condition.
688 CFGBlock* ExitConditionBlock = createBlock(false);
689 CFGBlock* EntryConditionBlock = ExitConditionBlock;
690
691 // Set the terminator for the "exit" condition block.
692 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000693
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000694 // Now add the actual condition to the condition block. Because the
695 // condition itself may contain control-flow, new blocks may be created.
696 if (Stmt* C = D->getCond()) {
697 Block = ExitConditionBlock;
698 EntryConditionBlock = addStmt(C);
699 if (Block) FinishBlock(EntryConditionBlock);
700 }
Ted Kremenek73543912007-08-23 21:42:29 +0000701
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000702 // The condition block is the implicit successor for the loop body as
703 // well as any code above the loop.
704 Succ = EntryConditionBlock;
705
706
Ted Kremenek73543912007-08-23 21:42:29 +0000707 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000708 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000709 {
710 assert (D->getBody());
711
712 // Save the current values for Block, Succ, and continue and break targets
713 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
714 save_continue(ContinueTargetBlock),
715 save_break(BreakTargetBlock);
716
717 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000718 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000719
720 // All breaks should go to the code following the loop.
721 BreakTargetBlock = LoopSuccessor;
722
723 // NULL out Block to force lazy instantiation of blocks for the body.
724 Block = NULL;
725
726 // Create the body. The returned block is the entry to the loop body.
727 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000728
Ted Kremenek390b9762007-08-30 18:39:40 +0000729 if (!BodyBlock)
730 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
731 else if (Block)
732 FinishBlock(BodyBlock);
733
Ted Kremenek73543912007-08-23 21:42:29 +0000734 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000735 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000736 }
737
738 // Link up the condition block with the code that follows the loop.
739 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000740 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000741
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000742 // There can be no more statements in the body block(s)
743 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000744 // lazy creation of another block.
745 Block = NULL;
746
747 // Return the loop body, which is the dominating block for the loop.
748 return BodyBlock;
749}
750
751CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
752 // "continue" is a control-flow statement. Thus we stop processing the
753 // current block.
754 if (Block) FinishBlock(Block);
755
756 // Now create a new block that ends with the continue statement.
757 Block = createBlock(false);
758 Block->setTerminator(C);
759
760 // If there is no target for the continue, then we are looking at an
761 // incomplete AST. Handle this by not registering a successor.
762 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
763
764 return Block;
765}
766
767CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
768 // "break" is a control-flow statement. Thus we stop processing the
769 // current block.
770 if (Block) FinishBlock(Block);
771
772 // Now create a new block that ends with the continue statement.
773 Block = createBlock(false);
774 Block->setTerminator(B);
775
776 // If there is no target for the break, then we are looking at an
777 // incomplete AST. Handle this by not registering a successor.
778 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
779
780 return Block;
781}
782
783CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
784 // "switch" is a control-flow statement. Thus we stop processing the
785 // current block.
786 CFGBlock* SwitchSuccessor = NULL;
787
788 if (Block) {
789 FinishBlock(Block);
790 SwitchSuccessor = Block;
791 }
792 else SwitchSuccessor = Succ;
793
794 // Save the current "switch" context.
795 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
796 save_break(BreakTargetBlock);
797
798 // Create a new block that will contain the switch statement.
799 SwitchTerminatedBlock = createBlock(false);
800
Ted Kremenek73543912007-08-23 21:42:29 +0000801 // Now process the switch body. The code after the switch is the implicit
802 // successor.
803 Succ = SwitchSuccessor;
804 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000805
806 // When visiting the body, the case statements should automatically get
807 // linked up to the switch. We also don't keep a pointer to the body,
808 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000809 assert (S->getBody() && "switch must contain a non-NULL body");
810 Block = NULL;
811 CFGBlock *BodyBlock = Visit(S->getBody());
812 if (Block) FinishBlock(BodyBlock);
813
814 // Add the terminator and condition in the switch block.
815 SwitchTerminatedBlock->setTerminator(S);
816 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000817 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000818 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000819}
820
821CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
822 // A SwitchCase is either a "default" or "case" statement. We handle
823 // both in the same way. They are essentially labels, so they are the
824 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000825
826 if (S->getSubStmt()) Visit(S->getSubStmt());
827 CFGBlock* CaseBlock = Block;
828 if (!CaseBlock) CaseBlock = createBlock();
829
Ted Kremenekec055e12007-08-29 23:20:49 +0000830 // Cases/Default statements partition block, so this is the top of
831 // the basic block we were processing (the case/default is the label).
832 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000833 FinishBlock(CaseBlock);
834
835 // Add this block to the list of successors for the block with the
836 // switch statement.
837 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
838
839 // We set Block to NULL to allow lazy creation of a new block (if necessary)
840 Block = NULL;
841
842 // This block is now the implicit successor of other blocks.
843 Succ = CaseBlock;
844
845 return CaseBlock;
846}
847
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000848CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
849 // Lazily create the indirect-goto dispatch block if there isn't one
850 // already.
851 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
852
853 if (!IBlock) {
854 IBlock = createBlock(false);
855 cfg->setIndirectGotoBlock(IBlock);
856 }
857
858 // IndirectGoto is a control-flow statement. Thus we stop processing the
859 // current block and create a new one.
860 if (Block) FinishBlock(Block);
861 Block = createBlock(false);
862 Block->setTerminator(I);
863 Block->addSuccessor(IBlock);
864 return addStmt(I->getTarget());
865}
866
Ted Kremenek73543912007-08-23 21:42:29 +0000867
Ted Kremenekd6e50602007-08-23 21:26:19 +0000868} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000869
870/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
871/// block has no successors or predecessors. If this is the first block
872/// created in the CFG, it is automatically set to be the Entry and Exit
873/// of the CFG.
874CFGBlock* CFG::createBlock(unsigned blockID) {
875 bool first_block = begin() == end();
876
877 // Create the block.
878 Blocks.push_front(CFGBlock(blockID));
879
880 // If this is the first block, set it as the Entry and Exit.
881 if (first_block) Entry = Exit = &front();
882
883 // Return the block.
884 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000885}
886
Ted Kremenek4db5b452007-08-23 16:51:22 +0000887/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
888/// CFG is returned to the caller.
889CFG* CFG::buildCFG(Stmt* Statement) {
890 CFGBuilder Builder;
891 return Builder.buildCFG(Statement);
892}
893
894/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000895void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
896
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000897
898//===----------------------------------------------------------------------===//
899// CFG pretty printing
900//===----------------------------------------------------------------------===//
901
Ted Kremenek4db5b452007-08-23 16:51:22 +0000902/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000903void CFG::dump() const { print(std::cerr); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000904
Ted Kremenek4db5b452007-08-23 16:51:22 +0000905/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000906void CFG::print(std::ostream& OS) const {
907
908 // Print the entry block.
909 getEntry().print(OS,this);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000910
Ted Kremenek4db5b452007-08-23 16:51:22 +0000911 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000912 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000913 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000914 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000915 I->print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000916 }
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000917
918 // Print the exit block.
919 getExit().print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000920}
921
Ted Kremenekd8313202007-08-22 18:22:34 +0000922namespace {
923
Ted Kremenek73543912007-08-23 21:42:29 +0000924class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
925 void > {
926 std::ostream& OS;
927public:
928 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
929
930 void VisitIfStmt(IfStmt* I) {
931 OS << "if ";
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000932 I->getCond()->printPretty(OS);
Ted Kremenek73543912007-08-23 21:42:29 +0000933 OS << "\n";
934 }
935
936 // Default case.
937 void VisitStmt(Stmt* S) { S->printPretty(OS); }
938
939 void VisitForStmt(ForStmt* F) {
940 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +0000941 if (F->getInit()) OS << "...";
942 OS << "; ";
Ted Kremenek73543912007-08-23 21:42:29 +0000943 if (Stmt* C = F->getCond()) C->printPretty(OS);
Ted Kremenek23a1d662007-08-30 21:28:02 +0000944 OS << "; ";
945 if (F->getInc()) OS << "...";
Ted Kremenek73543912007-08-23 21:42:29 +0000946 OS << ")\n";
947 }
948
949 void VisitWhileStmt(WhileStmt* W) {
950 OS << "while " ;
951 if (Stmt* C = W->getCond()) C->printPretty(OS);
952 OS << "\n";
953 }
954
955 void VisitDoStmt(DoStmt* D) {
956 OS << "do ... while ";
957 if (Stmt* C = D->getCond()) C->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000958 OS << '\n';
959 }
960
961 void VisitSwitchStmt(SwitchStmt* S) {
962 OS << "switch ";
963 S->getCond()->printPretty(OS);
964 OS << '\n';
965 }
966
Ted Kremenekcfaae762007-08-27 21:54:41 +0000967 void VisitExpr(Expr* E) {
968 E->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000969 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +0000970 }
Ted Kremenek73543912007-08-23 21:42:29 +0000971};
972} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000973
Ted Kremenek4db5b452007-08-23 16:51:22 +0000974/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000975void CFGBlock::dump(const CFG* cfg) const { print(std::cerr,cfg); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000976
Ted Kremenek4db5b452007-08-23 16:51:22 +0000977/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
978/// Generally this will only be called from CFG::print.
Ted Kremenekec055e12007-08-29 23:20:49 +0000979void CFGBlock::print(std::ostream& OS, const CFG* cfg, bool print_edges) const {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000980
981 // Print the header.
982 OS << "\n [ B" << getBlockID();
983 if (this == &cfg->getEntry()) { OS << " (ENTRY) ]\n"; }
984 else if (this == &cfg->getExit()) { OS << " (EXIT) ]\n"; }
985 else if (this == cfg->getIndirectGotoBlock()) {
986 OS << " (INDIRECT GOTO DISPATCH) ]\n";
987 }
988 else OS << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000989
Ted Kremenekec055e12007-08-29 23:20:49 +0000990 // Print the label of this block.
991 if (Stmt* S = const_cast<Stmt*>(getLabel())) {
992 if (print_edges) OS << " ";
993 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
994 OS << L->getName();
995 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
996 OS << "case ";
997 C->getLHS()->printPretty(OS);
998 if (C->getRHS()) {
999 OS << " ... ";
1000 C->getRHS()->printPretty(OS);
1001 }
1002 }
1003 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D)) {
1004 OS << "default";
1005 }
1006 else assert(false && "Invalid label statement in CFGBlock.");
1007
1008 OS << ":\n";
1009 }
1010
Ted Kremenek97f75312007-08-21 21:42:03 +00001011 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001012 unsigned j = 1;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001013 for (const_iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001014 // Print the statement # in the basic block and the statement itself.
1015 if (print_edges) OS << " ";
1016 OS << std::setw(3) << j << ": ";
1017 (*I)->printPretty(OS);
1018
Ted Kremenekc5de2222007-08-21 23:26:17 +00001019 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +00001020 if (isa<Expr>(*I)) OS << '\n';
1021 }
Ted Kremenek97f75312007-08-21 21:42:03 +00001022
Ted Kremenekec055e12007-08-29 23:20:49 +00001023 // Print the terminator of this block.
1024 if (getTerminator()) {
1025 if (print_edges) OS << " ";
1026 OS << " T: ";
1027 CFGBlockTerminatorPrint(OS).Visit(const_cast<Stmt*>(getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001028 }
1029
Ted Kremenekec055e12007-08-29 23:20:49 +00001030 if (print_edges) {
1031 // Print the predecessors of this block.
1032 OS << " Predecessors (" << pred_size() << "):";
1033 unsigned i = 0;
1034 for (const_pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i) {
1035 if (i == 8 || (i-8) == 0) {
1036 OS << "\n ";
1037 }
1038 OS << " B" << (*I)->getBlockID();
Ted Kremenek97f75312007-08-21 21:42:03 +00001039 }
Ted Kremenekec055e12007-08-29 23:20:49 +00001040 OS << '\n';
1041
1042 // Print the successors of this block.
1043 OS << " Successors (" << succ_size() << "):";
1044 i = 0;
1045 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i) {
1046 if (i == 8 || (i-8) % 10 == 0) {
1047 OS << "\n ";
1048 }
1049 OS << " B" << (*I)->getBlockID();
1050 }
1051 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001052 }
Ted Kremenek4db5b452007-08-23 16:51:22 +00001053}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001054
1055//===----------------------------------------------------------------------===//
1056// CFG Graphviz Visualization
1057//===----------------------------------------------------------------------===//
1058
1059namespace llvm {
1060template<>
1061struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1062 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1063
1064 std::ostringstream Out;
Ted Kremenekec055e12007-08-29 23:20:49 +00001065 Node->print(Out,Graph,false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001066 std::string OutStr = Out.str();
1067
1068 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1069
1070 // Process string output to make it nicer...
1071 for (unsigned i = 0; i != OutStr.length(); ++i)
1072 if (OutStr[i] == '\n') { // Left justify
1073 OutStr[i] = '\\';
1074 OutStr.insert(OutStr.begin()+i+1, 'l');
1075 }
1076
1077 return OutStr;
1078 }
1079};
1080} // end namespace llvm
1081
1082void CFG::viewCFG() const {
1083#ifndef NDEBUG
1084 llvm::ViewGraph(this,"CFG");
1085#else
1086 std::cerr << "CFG::viewCFG is only available in debug builds on "
1087 << "systems with Graphviz or gv!" << std::endl;
1088#endif
1089}