blob: 51b8cb5240a83025eca5979a5490da1523e5dc0d [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenekfddd5182007-08-21 21:42:03 +00007//
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 Kremenekc310e932007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek83c01da2008-01-11 00:40:29 +000024#include <set>
Ted Kremenekfddd5182007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000027#include <sstream>
28
Ted Kremenek83c01da2008-01-11 00:40:29 +000029
Ted Kremenekfddd5182007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekbefef2f2007-08-23 21:26:19 +000034// SaveAndRestore - A utility class that uses RIIA to save and restore
35// the value of a variable.
36template<typename T>
Ted Kremenek6fa9b882008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekbefef2f2007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenekfddd5182007-08-21 21:42:03 +000045
46/// CFGBuilder - This class is implements CFG construction from an AST.
47/// The builder is stateful: an instance of the builder should be used to only
48/// construct a single CFG.
49///
50/// Example usage:
51///
52/// CFGBuilder builder;
53/// CFG* cfg = builder.BuildAST(stmt1);
54///
Ted Kremenekc310e932007-08-21 22:06:14 +000055/// CFG construction is done via a recursive walk of an AST.
56/// We actually parse the AST in reverse order so that the successor
57/// of a basic block is constructed prior to its predecessor. This
58/// allows us to nicely capture implicit fall-throughs without extra
59/// basic blocks.
60///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000068
Ted Kremenek19bb3562007-08-28 19:26:49 +000069 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000070 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
71 LabelMapTy LabelMap;
72
Ted Kremenek19bb3562007-08-28 19:26:49 +000073 // A list of blocks that end with a "goto" that must be backpatched to
74 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000075 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000076 BackpatchBlocksTy BackpatchBlocks;
77
Ted Kremenek19bb3562007-08-28 19:26:49 +000078 // A list of labels whose address has been taken (for indirect gotos).
79 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
80 LabelSetTy AddressTakenLabels;
81
Ted Kremenekfddd5182007-08-21 21:42:03 +000082public:
Ted Kremenek026473c2007-08-23 16:51:22 +000083 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000084 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek94382522007-09-05 20:02:05 +000085 SwitchTerminatedBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000086 // Create an empty CFG.
87 cfg = new CFG();
88 }
89
90 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000091
Ted Kremenekd4fdee32007-08-23 21:42:29 +000092 // buildCFG - Used by external clients to construct the CFG.
93 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000094
Ted Kremenekd4fdee32007-08-23 21:42:29 +000095 // Visitors to walk an AST and construct the CFG. Called by
96 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000097
Ted Kremenekd4fdee32007-08-23 21:42:29 +000098 CFGBlock* VisitStmt(Stmt* Statement);
99 CFGBlock* VisitNullStmt(NullStmt* Statement);
100 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
101 CFGBlock* VisitIfStmt(IfStmt* I);
102 CFGBlock* VisitReturnStmt(ReturnStmt* R);
103 CFGBlock* VisitLabelStmt(LabelStmt* L);
104 CFGBlock* VisitGotoStmt(GotoStmt* G);
105 CFGBlock* VisitForStmt(ForStmt* F);
106 CFGBlock* VisitWhileStmt(WhileStmt* W);
107 CFGBlock* VisitDoStmt(DoStmt* D);
108 CFGBlock* VisitContinueStmt(ContinueStmt* C);
109 CFGBlock* VisitBreakStmt(BreakStmt* B);
110 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
111 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000112 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000113
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000114private:
115 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000116 CFGBlock* addStmt(Stmt* S);
117 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
118 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000119 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000120 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000121 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000122 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000123
Ted Kremenekfddd5182007-08-21 21:42:03 +0000124};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000125
126/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
127/// represent an arbitrary statement. Examples include a single expression
128/// or a function body (compound statement). The ownership of the returned
129/// CFG is transferred to the caller. If CFG construction fails, this method
130/// returns NULL.
131CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000132 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000133 if (!Statement) return NULL;
134
135 // Create an empty block that will serve as the exit block for the CFG.
136 // Since this is the first block added to the CFG, it will be implicitly
137 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000138 Succ = createBlock();
139 assert (Succ == &cfg->getExit());
140 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000141
142 // Visit the statements and create the CFG.
143 if (CFGBlock* B = Visit(Statement)) {
144 // Finalize the last constructed block. This usually involves
145 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000146 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000147
148 // Backpatch the gotos whose label -> block mappings we didn't know
149 // when we encountered them.
150 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
151 E = BackpatchBlocks.end(); I != E; ++I ) {
152
153 CFGBlock* B = *I;
154 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
155 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
156
157 // If there is no target for the goto, then we are looking at an
158 // incomplete AST. Handle this by not registering a successor.
159 if (LI == LabelMap.end()) continue;
160
161 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000162 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000163
Ted Kremenek19bb3562007-08-28 19:26:49 +0000164 // Add successors to the Indirect Goto Dispatch block (if we have one).
165 if (CFGBlock* B = cfg->getIndirectGotoBlock())
166 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
167 E = AddressTakenLabels.end(); I != E; ++I ) {
168
169 // Lookup the target block.
170 LabelMapTy::iterator LI = LabelMap.find(*I);
171
172 // If there is no target block that contains label, then we are looking
173 // at an incomplete AST. Handle this by not registering a successor.
174 if (LI == LabelMap.end()) continue;
175
176 B->addSuccessor(LI->second);
177 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000178
Ted Kremenek94b33162007-09-17 16:18:02 +0000179 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000180 }
181
182 // Create an empty entry block that has no predecessors.
183 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000184
Ted Kremenek322f58d2007-09-26 21:23:31 +0000185 // NULL out cfg so that repeated calls to the builder will fail and that
186 // the ownership of the constructed CFG is passed to the caller.
187 CFG* t = cfg;
188 cfg = NULL;
189 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000190}
191
192/// createBlock - Used to lazily create blocks that are connected
193/// to the current (global) succcessor.
194CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000195 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000196 if (add_successor && Succ) B->addSuccessor(Succ);
197 return B;
198}
199
200/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000201/// we must reverse the statements because they have been inserted
202/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203void CFGBuilder::FinishBlock(CFGBlock* B) {
204 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000205 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000206}
207
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000208/// addStmt - Used to add statements/expressions to the current CFGBlock
209/// "Block". This method calls WalkAST on the passed statement to see if it
210/// contains any short-circuit expressions. If so, it recursively creates
211/// the necessary blocks for such expressions. It returns the "topmost" block
212/// of the created blocks, or the original value of "Block" when this method
213/// was called if no additional blocks are created.
214CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000215 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000216 return WalkAST(S,true);
217}
218
219/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000220/// add extra blocks for ternary operators, &&, and ||. We also
221/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000222CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
223 switch (S->getStmtClass()) {
224 case Stmt::ConditionalOperatorClass: {
225 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000226
227 // Create the confluence block that will "merge" the results
228 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000229 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
230 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000231 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000232
233 // Create a block for the LHS expression if there is an LHS expression.
234 // A GCC extension allows LHS to be NULL, causing the condition to
235 // be the value that is returned instead.
236 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000237 Succ = ConfluenceBlock;
238 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000239 CFGBlock* LHSBlock = NULL;
240 if (C->getLHS()) {
241 LHSBlock = Visit(C->getLHS());
242 FinishBlock(LHSBlock);
243 Block = NULL;
244 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000245
Ted Kremenekecc04c92007-11-26 18:20:26 +0000246 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000247 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000248 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000249 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000250
Ted Kremenekecc04c92007-11-26 18:20:26 +0000251 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000252 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000253
254 if (LHSBlock)
255 Block->addSuccessor(LHSBlock);
256 else {
257 // If we have no LHS expression, add the ConfluenceBlock as a direct
258 // successor for the block containing the condition. Moreover,
259 // we need to reverse the order of the predecessors in the
260 // ConfluenceBlock because the RHSBlock will have been added to
261 // the succcessors already, and we want the first predecessor to the
262 // the block containing the expression for the case when the ternary
263 // expression evaluates to true.
264 Block->addSuccessor(ConfluenceBlock);
265 assert (ConfluenceBlock->pred_size() == 2);
266 std::reverse(ConfluenceBlock->pred_begin(),
267 ConfluenceBlock->pred_end());
268 }
269
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000270 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000271
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000272 Block->setTerminator(C);
273 return addStmt(C->getCond());
274 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000275
276 case Stmt::ChooseExprClass: {
277 ChooseExpr* C = cast<ChooseExpr>(S);
278
279 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
280 ConfluenceBlock->appendStmt(C);
281 FinishBlock(ConfluenceBlock);
282
283 Succ = ConfluenceBlock;
284 Block = NULL;
285 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000286 FinishBlock(LHSBlock);
287
Ted Kremenek49a436d2007-08-31 17:03:41 +0000288 Succ = ConfluenceBlock;
289 Block = NULL;
290 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000291 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000292
293 Block = createBlock(false);
294 Block->addSuccessor(LHSBlock);
295 Block->addSuccessor(RHSBlock);
296 Block->setTerminator(C);
297 return addStmt(C->getCond());
298 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000299
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000300 case Stmt::DeclStmtClass: {
301 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
302 Block->appendStmt(S);
303
304 StmtIterator I(D);
305 return WalkAST_VisitDeclSubExprs(I);
306 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000307
Ted Kremenek19bb3562007-08-28 19:26:49 +0000308 case Stmt::AddrLabelExprClass: {
309 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
310 AddressTakenLabels.insert(A->getLabel());
311
312 if (AlwaysAddStmt) Block->appendStmt(S);
313 return Block;
314 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000315
316 case Stmt::CallExprClass:
317 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000318
Ted Kremenek15c27a82007-08-28 18:30:10 +0000319 case Stmt::StmtExprClass:
320 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000321
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000322 case Stmt::UnaryOperatorClass: {
323 UnaryOperator* U = cast<UnaryOperator>(S);
324
325 // sizeof(expressions). For such expressions,
326 // the subexpression is not really evaluated, so
327 // we don't care about control-flow within the sizeof.
328 if (U->getOpcode() == UnaryOperator::SizeOf) {
329 Block->appendStmt(S);
330 return Block;
331 }
332
333 break;
334 }
335
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000336 case Stmt::BinaryOperatorClass: {
337 BinaryOperator* B = cast<BinaryOperator>(S);
338
339 if (B->isLogicalOp()) { // && or ||
340 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
341 ConfluenceBlock->appendStmt(B);
342 FinishBlock(ConfluenceBlock);
343
344 // create the block evaluating the LHS
345 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000346 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000347
348 // create the block evaluating the RHS
349 Succ = ConfluenceBlock;
350 Block = NULL;
351 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000352
353 // Now link the LHSBlock with RHSBlock.
354 if (B->getOpcode() == BinaryOperator::LOr) {
355 LHSBlock->addSuccessor(ConfluenceBlock);
356 LHSBlock->addSuccessor(RHSBlock);
357 }
358 else {
359 assert (B->getOpcode() == BinaryOperator::LAnd);
360 LHSBlock->addSuccessor(RHSBlock);
361 LHSBlock->addSuccessor(ConfluenceBlock);
362 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000363
364 // Generate the blocks for evaluating the LHS.
365 Block = LHSBlock;
366 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000367 }
368 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
369 Block->appendStmt(B);
370 addStmt(B->getRHS());
371 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000372 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000373
374 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000375 }
376
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000377 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000378 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000379 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000380
381 if (AlwaysAddStmt) Block->appendStmt(S);
382 return WalkAST_VisitChildren(S);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000383}
384
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000385/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
386/// DeclStmts. Because the initialization code (and sometimes the
387/// the type declarations) for DeclStmts can contain arbitrary expressions,
388/// we must linearize declarations to handle arbitrary control-flow induced by
389/// those expressions.
390CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000391 if (I == StmtIterator())
392 return Block;
393
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000394 Stmt* S = *I;
395 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000396 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000397
398 Block = addStmt(S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000399 return Block;
400}
401
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000402/// WalkAST_VisitChildren - Utility method to call WalkAST on the
403/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000404CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000405 CFGBlock* B = Block;
406 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
407 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000408 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000409
410 return B;
411}
412
Ted Kremenek15c27a82007-08-28 18:30:10 +0000413/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
414/// expressions (a GCC extension).
415CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
416 Block->appendStmt(S);
417 return VisitCompoundStmt(S->getSubStmt());
418}
419
Ted Kremenekf50ec102007-09-11 21:29:43 +0000420/// WalkAST_VisitCallExpr - Utility method to handle function calls that
421/// are nested in expressions. The idea is that each function call should
422/// appear as a distinct statement in the CFGBlock.
423CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
424 Block->appendStmt(C);
425 return WalkAST_VisitChildren(C);
426}
427
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000428/// VisitStmt - Handle statements with no branching control flow.
429CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
430 // We cannot assume that we are in the middle of a basic block, since
431 // the CFG might only be constructed for this single statement. If
432 // we have no current basic block, just create one lazily.
433 if (!Block) Block = createBlock();
434
435 // Simply add the statement to the current block. We actually
436 // insert statements in reverse order; this order is reversed later
437 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000438 addStmt(Statement);
439
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000440 return Block;
441}
442
443CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
444 return Block;
445}
446
447CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
448 // The value returned from this function is the last created CFGBlock
449 // that represents the "entry" point for the translated AST node.
Chris Lattner271f1a62007-09-27 15:15:46 +0000450 CFGBlock* LastBlock = 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000451
452 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
453 E = C->body_rend(); I != E; ++I )
454 // Add the statement to the current block.
455 if (!(LastBlock=Visit(*I)))
456 return NULL;
457
458 return LastBlock;
459}
460
461CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
462 // We may see an if statement in the middle of a basic block, or
463 // it may be the first statement we are processing. In either case,
464 // we create a new basic block. First, we create the blocks for
465 // the then...else statements, and then we create the block containing
466 // the if statement. If we were in the middle of a block, we
467 // stop processing that block and reverse its statements. That block
468 // is then the implicit successor for the "then" and "else" clauses.
469
470 // The block we were proccessing is now finished. Make it the
471 // successor block.
472 if (Block) {
473 Succ = Block;
474 FinishBlock(Block);
475 }
476
477 // Process the false branch. NULL out Block so that the recursive
478 // call to Visit will create a new basic block.
479 // Null out Block so that all successor
480 CFGBlock* ElseBlock = Succ;
481
482 if (Stmt* Else = I->getElse()) {
483 SaveAndRestore<CFGBlock*> sv(Succ);
484
485 // NULL out Block so that the recursive call to Visit will
486 // create a new basic block.
487 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000488 ElseBlock = Visit(Else);
489
490 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
491 ElseBlock = sv.get();
492 else if (Block)
493 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000494 }
495
496 // Process the true branch. NULL out Block so that the recursive
497 // call to Visit will create a new basic block.
498 // Null out Block so that all successor
499 CFGBlock* ThenBlock;
500 {
501 Stmt* Then = I->getThen();
502 assert (Then);
503 SaveAndRestore<CFGBlock*> sv(Succ);
504 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000505 ThenBlock = Visit(Then);
506
507 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
508 ThenBlock = sv.get();
509 else if (Block)
510 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000511 }
512
513 // Now create a new block containing the if statement.
514 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000515
516 // Set the terminator of the new block to the If statement.
517 Block->setTerminator(I);
518
519 // Now add the successors.
520 Block->addSuccessor(ThenBlock);
521 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000522
523 // Add the condition as the last statement in the new block. This
524 // may create new blocks as the condition may contain control-flow. Any
525 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000526 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000527}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000528
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000529
530CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
531 // If we were in the middle of a block we stop processing that block
532 // and reverse its statements.
533 //
534 // NOTE: If a "return" appears in the middle of a block, this means
535 // that the code afterwards is DEAD (unreachable). We still
536 // keep a basic block for that code; a simple "mark-and-sweep"
537 // from the entry block will be able to report such dead
538 // blocks.
539 if (Block) FinishBlock(Block);
540
541 // Create the new block.
542 Block = createBlock(false);
543
544 // The Exit block is the only successor.
545 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000546
547 // Add the return statement to the block. This may create new blocks
548 // if R contains control-flow (short-circuit operations).
549 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000550}
551
552CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
553 // Get the block of the labeled statement. Add it to our map.
554 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000555
556 if (!LabelBlock) // This can happen when the body is empty, i.e.
557 LabelBlock=createBlock(); // scopes that only contains NullStmts.
558
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000559 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
560 LabelMap[ L ] = LabelBlock;
561
562 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000563 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000564 // label (and we have already processed the substatement) there is no
565 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000566 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000567 FinishBlock(LabelBlock);
568
569 // We set Block to NULL to allow lazy creation of a new block
570 // (if necessary);
571 Block = NULL;
572
573 // This block is now the implicit successor of other blocks.
574 Succ = LabelBlock;
575
576 return LabelBlock;
577}
578
579CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
580 // Goto is a control-flow statement. Thus we stop processing the
581 // current block and create a new one.
582 if (Block) FinishBlock(Block);
583 Block = createBlock(false);
584 Block->setTerminator(G);
585
586 // If we already know the mapping to the label block add the
587 // successor now.
588 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
589
590 if (I == LabelMap.end())
591 // We will need to backpatch this block later.
592 BackpatchBlocks.push_back(Block);
593 else
594 Block->addSuccessor(I->second);
595
596 return Block;
597}
598
599CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
600 // "for" is a control-flow statement. Thus we stop processing the
601 // current block.
602
603 CFGBlock* LoopSuccessor = NULL;
604
605 if (Block) {
606 FinishBlock(Block);
607 LoopSuccessor = Block;
608 }
609 else LoopSuccessor = Succ;
610
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000611 // Because of short-circuit evaluation, the condition of the loop
612 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
613 // blocks that evaluate the condition.
614 CFGBlock* ExitConditionBlock = createBlock(false);
615 CFGBlock* EntryConditionBlock = ExitConditionBlock;
616
617 // Set the terminator for the "exit" condition block.
618 ExitConditionBlock->setTerminator(F);
619
620 // Now add the actual condition to the condition block. Because the
621 // condition itself may contain control-flow, new blocks may be created.
622 if (Stmt* C = F->getCond()) {
623 Block = ExitConditionBlock;
624 EntryConditionBlock = addStmt(C);
625 if (Block) FinishBlock(EntryConditionBlock);
626 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000627
628 // The condition block is the implicit successor for the loop body as
629 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000630 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000631
632 // Now create the loop body.
633 {
634 assert (F->getBody());
635
636 // Save the current values for Block, Succ, and continue and break targets
637 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
638 save_continue(ContinueTargetBlock),
639 save_break(BreakTargetBlock);
640
641 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000642 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000643
644 // All breaks should go to the code following the loop.
645 BreakTargetBlock = LoopSuccessor;
646
Ted Kremenekaf603f72007-08-30 18:39:40 +0000647 // Create a new block to contain the (bottom) of the loop body.
648 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000649
650 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000651 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000652
653 // Now populate the body block, and in the process create new blocks
654 // as we walk the body of the loop.
655 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000656
657 if (!BodyBlock)
658 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
659 else if (Block)
660 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000661
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000662 // This new body block is a successor to our "exit" condition block.
663 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000664 }
665
666 // Link up the condition block with the code that follows the loop.
667 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000668 ExitConditionBlock->addSuccessor(LoopSuccessor);
669
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000670 // If the loop contains initialization, create a new block for those
671 // statements. This block can also contain statements that precede
672 // the loop.
673 if (Stmt* I = F->getInit()) {
674 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000675 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000676 }
677 else {
678 // There is no loop initialization. We are thus basically a while
679 // loop. NULL out Block to force lazy block construction.
680 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000681 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000682 }
683}
684
685CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
686 // "while" is a control-flow statement. Thus we stop processing the
687 // current block.
688
689 CFGBlock* LoopSuccessor = NULL;
690
691 if (Block) {
692 FinishBlock(Block);
693 LoopSuccessor = Block;
694 }
695 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000696
697 // Because of short-circuit evaluation, the condition of the loop
698 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
699 // blocks that evaluate the condition.
700 CFGBlock* ExitConditionBlock = createBlock(false);
701 CFGBlock* EntryConditionBlock = ExitConditionBlock;
702
703 // Set the terminator for the "exit" condition block.
704 ExitConditionBlock->setTerminator(W);
705
706 // Now add the actual condition to the condition block. Because the
707 // condition itself may contain control-flow, new blocks may be created.
708 // Thus we update "Succ" after adding the condition.
709 if (Stmt* C = W->getCond()) {
710 Block = ExitConditionBlock;
711 EntryConditionBlock = addStmt(C);
712 if (Block) FinishBlock(EntryConditionBlock);
713 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000714
715 // The condition block is the implicit successor for the loop body as
716 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000717 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000718
719 // Process the loop body.
720 {
721 assert (W->getBody());
722
723 // Save the current values for Block, Succ, and continue and break targets
724 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
725 save_continue(ContinueTargetBlock),
726 save_break(BreakTargetBlock);
727
728 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000729 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000730
731 // All breaks should go to the code following the loop.
732 BreakTargetBlock = LoopSuccessor;
733
734 // NULL out Block to force lazy instantiation of blocks for the body.
735 Block = NULL;
736
737 // Create the body. The returned block is the entry to the loop body.
738 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000739
740 if (!BodyBlock)
741 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
742 else if (Block)
743 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000744
745 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000746 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000747 }
748
749 // Link up the condition block with the code that follows the loop.
750 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000751 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000752
753 // There can be no more statements in the condition block
754 // since we loop back to this block. NULL out Block to force
755 // lazy creation of another block.
756 Block = NULL;
757
758 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000759 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000760}
761
762CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
763 // "do...while" is a control-flow statement. Thus we stop processing the
764 // current block.
765
766 CFGBlock* LoopSuccessor = NULL;
767
768 if (Block) {
769 FinishBlock(Block);
770 LoopSuccessor = Block;
771 }
772 else LoopSuccessor = Succ;
773
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000774 // Because of short-circuit evaluation, the condition of the loop
775 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
776 // blocks that evaluate the condition.
777 CFGBlock* ExitConditionBlock = createBlock(false);
778 CFGBlock* EntryConditionBlock = ExitConditionBlock;
779
780 // Set the terminator for the "exit" condition block.
781 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000782
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000783 // Now add the actual condition to the condition block. Because the
784 // condition itself may contain control-flow, new blocks may be created.
785 if (Stmt* C = D->getCond()) {
786 Block = ExitConditionBlock;
787 EntryConditionBlock = addStmt(C);
788 if (Block) FinishBlock(EntryConditionBlock);
789 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000790
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000791 // The condition block is the implicit successor for the loop body as
792 // well as any code above the loop.
793 Succ = EntryConditionBlock;
794
795
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000796 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000797 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000798 {
799 assert (D->getBody());
800
801 // Save the current values for Block, Succ, and continue and break targets
802 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
803 save_continue(ContinueTargetBlock),
804 save_break(BreakTargetBlock);
805
806 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000807 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000808
809 // All breaks should go to the code following the loop.
810 BreakTargetBlock = LoopSuccessor;
811
812 // NULL out Block to force lazy instantiation of blocks for the body.
813 Block = NULL;
814
815 // Create the body. The returned block is the entry to the loop body.
816 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000817
Ted Kremenekaf603f72007-08-30 18:39:40 +0000818 if (!BodyBlock)
819 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
820 else if (Block)
821 FinishBlock(BodyBlock);
822
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000823 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000824 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000825 }
826
827 // Link up the condition block with the code that follows the loop.
828 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000829 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000830
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000831 // There can be no more statements in the body block(s)
832 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000833 // lazy creation of another block.
834 Block = NULL;
835
836 // Return the loop body, which is the dominating block for the loop.
837 return BodyBlock;
838}
839
840CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
841 // "continue" is a control-flow statement. Thus we stop processing the
842 // current block.
843 if (Block) FinishBlock(Block);
844
845 // Now create a new block that ends with the continue statement.
846 Block = createBlock(false);
847 Block->setTerminator(C);
848
849 // If there is no target for the continue, then we are looking at an
850 // incomplete AST. Handle this by not registering a successor.
851 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
852
853 return Block;
854}
855
856CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
857 // "break" is a control-flow statement. Thus we stop processing the
858 // current block.
859 if (Block) FinishBlock(Block);
860
861 // Now create a new block that ends with the continue statement.
862 Block = createBlock(false);
863 Block->setTerminator(B);
864
865 // If there is no target for the break, then we are looking at an
866 // incomplete AST. Handle this by not registering a successor.
867 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
868
869 return Block;
870}
871
872CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
873 // "switch" is a control-flow statement. Thus we stop processing the
874 // current block.
875 CFGBlock* SwitchSuccessor = NULL;
876
877 if (Block) {
878 FinishBlock(Block);
879 SwitchSuccessor = Block;
880 }
881 else SwitchSuccessor = Succ;
882
883 // Save the current "switch" context.
884 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
885 save_break(BreakTargetBlock);
886
887 // Create a new block that will contain the switch statement.
888 SwitchTerminatedBlock = createBlock(false);
889
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000890 // Now process the switch body. The code after the switch is the implicit
891 // successor.
892 Succ = SwitchSuccessor;
893 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000894
895 // When visiting the body, the case statements should automatically get
896 // linked up to the switch. We also don't keep a pointer to the body,
897 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000898 assert (S->getBody() && "switch must contain a non-NULL body");
899 Block = NULL;
900 CFGBlock *BodyBlock = Visit(S->getBody());
901 if (Block) FinishBlock(BodyBlock);
902
903 // Add the terminator and condition in the switch block.
904 SwitchTerminatedBlock->setTerminator(S);
905 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000906 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000907 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000908}
909
910CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
911 // A SwitchCase is either a "default" or "case" statement. We handle
912 // both in the same way. They are essentially labels, so they are the
913 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000914
915 if (S->getSubStmt()) Visit(S->getSubStmt());
916 CFGBlock* CaseBlock = Block;
917 if (!CaseBlock) CaseBlock = createBlock();
918
Ted Kremenek9cffe732007-08-29 23:20:49 +0000919 // Cases/Default statements partition block, so this is the top of
920 // the basic block we were processing (the case/default is the label).
921 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000922 FinishBlock(CaseBlock);
923
924 // Add this block to the list of successors for the block with the
925 // switch statement.
926 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
927
928 // We set Block to NULL to allow lazy creation of a new block (if necessary)
929 Block = NULL;
930
931 // This block is now the implicit successor of other blocks.
932 Succ = CaseBlock;
933
934 return CaseBlock;
935}
936
Ted Kremenek19bb3562007-08-28 19:26:49 +0000937CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
938 // Lazily create the indirect-goto dispatch block if there isn't one
939 // already.
940 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
941
942 if (!IBlock) {
943 IBlock = createBlock(false);
944 cfg->setIndirectGotoBlock(IBlock);
945 }
946
947 // IndirectGoto is a control-flow statement. Thus we stop processing the
948 // current block and create a new one.
949 if (Block) FinishBlock(Block);
950 Block = createBlock(false);
951 Block->setTerminator(I);
952 Block->addSuccessor(IBlock);
953 return addStmt(I->getTarget());
954}
955
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000956
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000957} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000958
959/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
960/// block has no successors or predecessors. If this is the first block
961/// created in the CFG, it is automatically set to be the Entry and Exit
962/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000963CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000964 bool first_block = begin() == end();
965
966 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000967 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000968
969 // If this is the first block, set it as the Entry and Exit.
970 if (first_block) Entry = Exit = &front();
971
972 // Return the block.
973 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000974}
975
Ted Kremenek026473c2007-08-23 16:51:22 +0000976/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
977/// CFG is returned to the caller.
978CFG* CFG::buildCFG(Stmt* Statement) {
979 CFGBuilder Builder;
980 return Builder.buildCFG(Statement);
981}
982
983/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000984void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
985
Ted Kremenek63f58872007-10-01 19:33:33 +0000986//===----------------------------------------------------------------------===//
987// CFG: Queries for BlkExprs.
988//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +0000989
Ted Kremenek63f58872007-10-01 19:33:33 +0000990namespace {
Ted Kremenek86946742008-01-17 20:48:37 +0000991 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +0000992}
993
Ted Kremenek33d4aab2008-01-26 00:03:27 +0000994static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
995 if (!S)
996 return;
997
998 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
999 if (!*I) continue;
1000
1001 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1002 if (B->isAssignmentOp()) Set.insert(B);
1003
1004 FindSubExprAssignments(*I, Set);
1005 }
1006}
1007
Ted Kremenek63f58872007-10-01 19:33:33 +00001008static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1009 BlkExprMapTy* M = new BlkExprMapTy();
1010
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001011 // Look for assignments that are used as subexpressions. These are the
1012 // only assignments that we want to register as a block-level expression.
1013 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1014
Ted Kremenek63f58872007-10-01 19:33:33 +00001015 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1016 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001017 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001018
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001019 // Iterate over the statements again on identify the Expr* and Stmt* at
1020 // the block-level that are block-level expressions.
1021 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1022 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1023 if (Expr* E = dyn_cast<Expr>(*BI)) {
1024
1025 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1026 // Assignment expressions that are not nested within another
1027 // expression are really "statements" whose value is never
1028 // used by another expression.
1029 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1030 continue;
1031 }
1032 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1033 // Special handling for statement expressions. The last statement
1034 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001035 const CompoundStmt* C = S->getSubStmt();
1036 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001037 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001038 (*M)[C->body_back()] = x;
1039 }
1040 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001041
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001042 unsigned x = M->size();
1043 (*M)[E] = x;
1044 }
1045
Ted Kremenek63f58872007-10-01 19:33:33 +00001046 return M;
1047}
1048
Ted Kremenek86946742008-01-17 20:48:37 +00001049CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1050 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001051 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1052
1053 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001054 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001055
1056 if (I == M->end()) return CFG::BlkExprNumTy();
1057 else return CFG::BlkExprNumTy(I->second);
1058}
1059
1060unsigned CFG::getNumBlkExprs() {
1061 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1062 return M->size();
1063 else {
1064 // We assume callers interested in the number of BlkExprs will want
1065 // the map constructed if it doesn't already exist.
1066 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1067 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1068 }
1069}
1070
Ted Kremenek83c01da2008-01-11 00:40:29 +00001071typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1072
1073const std::pair<CFGBlock*,CFGBlock*>*
1074CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1075
1076 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1077 if (!p) p = new BlkEdgeSetTy();
1078
1079 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1080 const_cast<CFGBlock*>(B2))).first);
1081}
1082
Ted Kremenek63f58872007-10-01 19:33:33 +00001083CFG::~CFG() {
1084 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001085 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001086}
1087
Ted Kremenek7dba8602007-08-29 21:56:09 +00001088//===----------------------------------------------------------------------===//
1089// CFG pretty printing
1090//===----------------------------------------------------------------------===//
1091
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001092namespace {
1093
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001094class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001095
Ted Kremenek42a509f2007-08-31 21:30:12 +00001096 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1097 StmtMapTy StmtMap;
1098 signed CurrentBlock;
1099 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001100
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001101public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001102
Ted Kremenek42a509f2007-08-31 21:30:12 +00001103 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1104 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1105 unsigned j = 1;
1106 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1107 BI != BEnd; ++BI, ++j )
1108 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1109 }
1110 }
1111
1112 virtual ~StmtPrinterHelper() {}
1113
1114 void setBlockID(signed i) { CurrentBlock = i; }
1115 void setStmtID(unsigned i) { CurrentStmt = i; }
1116
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001117 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1118
1119 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001120
1121 if (I == StmtMap.end())
1122 return false;
1123
1124 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1125 && I->second.second == CurrentStmt)
1126 return false;
1127
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001128 OS << "[B" << I->second.first << "." << I->second.second << "]";
1129 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001130 }
1131};
1132
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001133class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1134 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1135
Ted Kremenek42a509f2007-08-31 21:30:12 +00001136 std::ostream& OS;
1137 StmtPrinterHelper* Helper;
1138public:
1139 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1140 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001141
1142 void VisitIfStmt(IfStmt* I) {
1143 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001144 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001145 }
1146
1147 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001148 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001149
1150 void VisitForStmt(ForStmt* F) {
1151 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001152 if (F->getInit()) OS << "...";
1153 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001154 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001155 OS << "; ";
1156 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001157 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001158 }
1159
1160 void VisitWhileStmt(WhileStmt* W) {
1161 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001162 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001163 }
1164
1165 void VisitDoStmt(DoStmt* D) {
1166 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001167 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001168 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001169
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001170 void VisitSwitchStmt(SwitchStmt* S) {
1171 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001172 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001173 }
1174
Ted Kremenek805e9a82007-08-31 21:49:40 +00001175 void VisitConditionalOperator(ConditionalOperator* C) {
1176 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001177 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001178 }
1179
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001180 void VisitChooseExpr(ChooseExpr* C) {
1181 OS << "__builtin_choose_expr( ";
1182 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001183 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001184 }
1185
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001186 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1187 OS << "goto *";
1188 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001189 }
1190
Ted Kremenek805e9a82007-08-31 21:49:40 +00001191 void VisitBinaryOperator(BinaryOperator* B) {
1192 if (!B->isLogicalOp()) {
1193 VisitExpr(B);
1194 return;
1195 }
1196
1197 B->getLHS()->printPretty(OS,Helper);
1198
1199 switch (B->getOpcode()) {
1200 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001201 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001202 return;
1203 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001204 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001205 return;
1206 default:
1207 assert(false && "Invalid logical operator.");
1208 }
1209 }
1210
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001211 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001212 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001213 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001214};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001215
1216
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001217void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1218 if (Helper) {
1219 // special printing for statement-expressions.
1220 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1221 CompoundStmt* Sub = SE->getSubStmt();
1222
1223 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001224 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001225 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001226 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001227 return;
1228 }
1229 }
1230
1231 // special printing for comma expressions.
1232 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1233 if (B->getOpcode() == BinaryOperator::Comma) {
1234 OS << "... , ";
1235 Helper->handledStmt(B->getRHS(),OS);
1236 OS << '\n';
1237 return;
1238 }
1239 }
1240 }
1241
1242 S->printPretty(OS, Helper);
1243
1244 // Expressions need a newline.
1245 if (isa<Expr>(S)) OS << '\n';
1246}
1247
Ted Kremenek42a509f2007-08-31 21:30:12 +00001248void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1249 StmtPrinterHelper* Helper, bool print_edges) {
1250
1251 if (Helper) Helper->setBlockID(B.getBlockID());
1252
Ted Kremenek7dba8602007-08-29 21:56:09 +00001253 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001254 OS << "\n [ B" << B.getBlockID();
1255
1256 if (&B == &cfg->getEntry())
1257 OS << " (ENTRY) ]\n";
1258 else if (&B == &cfg->getExit())
1259 OS << " (EXIT) ]\n";
1260 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001261 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001262 else
1263 OS << " ]\n";
1264
Ted Kremenek9cffe732007-08-29 23:20:49 +00001265 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001266 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1267
1268 if (print_edges)
1269 OS << " ";
1270
Ted Kremenek9cffe732007-08-29 23:20:49 +00001271 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1272 OS << L->getName();
1273 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1274 OS << "case ";
1275 C->getLHS()->printPretty(OS);
1276 if (C->getRHS()) {
1277 OS << " ... ";
1278 C->getRHS()->printPretty(OS);
1279 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001280 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001281 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001282 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001283 else
1284 assert(false && "Invalid label statement in CFGBlock.");
1285
Ted Kremenek9cffe732007-08-29 23:20:49 +00001286 OS << ":\n";
1287 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001288
Ted Kremenekfddd5182007-08-21 21:42:03 +00001289 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001290 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001291
1292 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1293 I != E ; ++I, ++j ) {
1294
Ted Kremenek9cffe732007-08-29 23:20:49 +00001295 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001296 if (print_edges)
1297 OS << " ";
1298
1299 OS << std::setw(3) << j << ": ";
1300
1301 if (Helper)
1302 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001303
1304 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001305 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001306
Ted Kremenek9cffe732007-08-29 23:20:49 +00001307 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001308 if (B.getTerminator()) {
1309 if (print_edges)
1310 OS << " ";
1311
Ted Kremenek9cffe732007-08-29 23:20:49 +00001312 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001313
1314 if (Helper) Helper->setBlockID(-1);
1315
1316 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1317 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001318 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001319 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001320
Ted Kremenek9cffe732007-08-29 23:20:49 +00001321 if (print_edges) {
1322 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001323 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001324 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001325
Ted Kremenek42a509f2007-08-31 21:30:12 +00001326 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1327 I != E; ++I, ++i) {
1328
1329 if (i == 8 || (i-8) == 0)
1330 OS << "\n ";
1331
Ted Kremenek9cffe732007-08-29 23:20:49 +00001332 OS << " B" << (*I)->getBlockID();
1333 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001334
1335 OS << '\n';
1336
1337 // Print the successors of this block.
1338 OS << " Successors (" << B.succ_size() << "):";
1339 i = 0;
1340
1341 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1342 I != E; ++I, ++i) {
1343
1344 if (i == 8 || (i-8) % 10 == 0)
1345 OS << "\n ";
1346
1347 OS << " B" << (*I)->getBlockID();
1348 }
1349
Ted Kremenek9cffe732007-08-29 23:20:49 +00001350 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001351 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001352}
1353
1354} // end anonymous namespace
1355
1356/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001357void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001358
1359/// print - A simple pretty printer of a CFG that outputs to an ostream.
1360void CFG::print(std::ostream& OS) const {
1361
1362 StmtPrinterHelper Helper(this);
1363
1364 // Print the entry block.
1365 print_block(OS, this, getEntry(), &Helper, true);
1366
1367 // Iterate through the CFGBlocks and print them one by one.
1368 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1369 // Skip the entry block, because we already printed it.
1370 if (&(*I) == &getEntry() || &(*I) == &getExit())
1371 continue;
1372
1373 print_block(OS, this, *I, &Helper, true);
1374 }
1375
1376 // Print the exit block.
1377 print_block(OS, this, getExit(), &Helper, true);
1378}
1379
1380/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001381void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001382
1383/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1384/// Generally this will only be called from CFG::print.
1385void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1386 StmtPrinterHelper Helper(cfg);
1387 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001388}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001389
Ted Kremeneka2925852008-01-30 23:02:42 +00001390/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1391void CFGBlock::printTerminator(std::ostream& OS) const {
1392 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1393 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1394}
1395
1396
Ted Kremenek7dba8602007-08-29 21:56:09 +00001397//===----------------------------------------------------------------------===//
1398// CFG Graphviz Visualization
1399//===----------------------------------------------------------------------===//
1400
Ted Kremenek42a509f2007-08-31 21:30:12 +00001401
1402#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001403static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001404#endif
1405
1406void CFG::viewCFG() const {
1407#ifndef NDEBUG
1408 StmtPrinterHelper H(this);
1409 GraphHelper = &H;
1410 llvm::ViewGraph(this,"CFG");
1411 GraphHelper = NULL;
1412#else
1413 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001414 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001415#endif
1416}
1417
Ted Kremenek7dba8602007-08-29 21:56:09 +00001418namespace llvm {
1419template<>
1420struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1421 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1422
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001423#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001424 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001425 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001426 std::string OutStr = Out.str();
1427
1428 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1429
1430 // Process string output to make it nicer...
1431 for (unsigned i = 0; i != OutStr.length(); ++i)
1432 if (OutStr[i] == '\n') { // Left justify
1433 OutStr[i] = '\\';
1434 OutStr.insert(OutStr.begin()+i+1, 'l');
1435 }
1436
1437 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001438#else
1439 return "";
1440#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001441 }
1442};
1443} // end namespace llvm