blob: 18c2074b406f4f1d0bc607d9fef5f219b114d73f [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 Kremenekeef5a9a2008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000069
Ted Kremenek19bb3562007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek19bb3562007-08-28 19:26:49 +000074 // A list of blocks that end with a "goto" that must be backpatched to
75 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek19bb3562007-08-28 19:26:49 +000079 // A list of labels whose address has been taken (for indirect gotos).
80 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
81 LabelSetTy AddressTakenLabels;
82
Ted Kremenekfddd5182007-08-21 21:42:03 +000083public:
Ted Kremenek026473c2007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000092
Ted Kremenekd4fdee32007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000095
Ted Kremenekd4fdee32007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000098
Ted Kremenekd4fdee32007-08-23 21:42:29 +000099 CFGBlock* VisitStmt(Stmt* Statement);
100 CFGBlock* VisitNullStmt(NullStmt* Statement);
101 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
102 CFGBlock* VisitIfStmt(IfStmt* I);
103 CFGBlock* VisitReturnStmt(ReturnStmt* R);
104 CFGBlock* VisitLabelStmt(LabelStmt* L);
105 CFGBlock* VisitGotoStmt(GotoStmt* G);
106 CFGBlock* VisitForStmt(ForStmt* F);
107 CFGBlock* VisitWhileStmt(WhileStmt* W);
108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitContinueStmt(ContinueStmt* C);
110 CFGBlock* VisitBreakStmt(BreakStmt* B);
111 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000112 CFGBlock* VisitCaseStmt(CaseStmt* S);
Ted Kremenek295222c2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000115
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000116private:
117 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000118 CFGBlock* addStmt(Stmt* S);
119 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
120 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000121 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000122 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000123 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000124 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000125
Ted Kremenekfddd5182007-08-21 21:42:03 +0000126};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000127
128/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
129/// represent an arbitrary statement. Examples include a single expression
130/// or a function body (compound statement). The ownership of the returned
131/// CFG is transferred to the caller. If CFG construction fails, this method
132/// returns NULL.
133CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000134 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000135 if (!Statement) return NULL;
136
137 // Create an empty block that will serve as the exit block for the CFG.
138 // Since this is the first block added to the CFG, it will be implicitly
139 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000140 Succ = createBlock();
141 assert (Succ == &cfg->getExit());
142 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000143
144 // Visit the statements and create the CFG.
145 if (CFGBlock* B = Visit(Statement)) {
146 // Finalize the last constructed block. This usually involves
147 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000148 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000149
150 // Backpatch the gotos whose label -> block mappings we didn't know
151 // when we encountered them.
152 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
153 E = BackpatchBlocks.end(); I != E; ++I ) {
154
155 CFGBlock* B = *I;
156 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
157 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
158
159 // If there is no target for the goto, then we are looking at an
160 // incomplete AST. Handle this by not registering a successor.
161 if (LI == LabelMap.end()) continue;
162
163 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000164 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000165
Ted Kremenek19bb3562007-08-28 19:26:49 +0000166 // Add successors to the Indirect Goto Dispatch block (if we have one).
167 if (CFGBlock* B = cfg->getIndirectGotoBlock())
168 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
169 E = AddressTakenLabels.end(); I != E; ++I ) {
170
171 // Lookup the target block.
172 LabelMapTy::iterator LI = LabelMap.find(*I);
173
174 // If there is no target block that contains label, then we are looking
175 // at an incomplete AST. Handle this by not registering a successor.
176 if (LI == LabelMap.end()) continue;
177
178 B->addSuccessor(LI->second);
179 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000180
Ted Kremenek94b33162007-09-17 16:18:02 +0000181 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000182 }
183
184 // Create an empty entry block that has no predecessors.
185 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000186
Ted Kremenek322f58d2007-09-26 21:23:31 +0000187 // NULL out cfg so that repeated calls to the builder will fail and that
188 // the ownership of the constructed CFG is passed to the caller.
189 CFG* t = cfg;
190 cfg = NULL;
191 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000192}
193
194/// createBlock - Used to lazily create blocks that are connected
195/// to the current (global) succcessor.
196CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000197 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000198 if (add_successor && Succ) B->addSuccessor(Succ);
199 return B;
200}
201
202/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000203/// we must reverse the statements because they have been inserted
204/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000205void CFGBuilder::FinishBlock(CFGBlock* B) {
206 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000207 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000208}
209
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000210/// addStmt - Used to add statements/expressions to the current CFGBlock
211/// "Block". This method calls WalkAST on the passed statement to see if it
212/// contains any short-circuit expressions. If so, it recursively creates
213/// the necessary blocks for such expressions. It returns the "topmost" block
214/// of the created blocks, or the original value of "Block" when this method
215/// was called if no additional blocks are created.
216CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000217 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000218 return WalkAST(S,true);
219}
220
221/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000222/// add extra blocks for ternary operators, &&, and ||. We also
223/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000224CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
225 switch (S->getStmtClass()) {
226 case Stmt::ConditionalOperatorClass: {
227 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000228
229 // Create the confluence block that will "merge" the results
230 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000231 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
232 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000233 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000234
235 // Create a block for the LHS expression if there is an LHS expression.
236 // A GCC extension allows LHS to be NULL, causing the condition to
237 // be the value that is returned instead.
238 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000239 Succ = ConfluenceBlock;
240 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000241 CFGBlock* LHSBlock = NULL;
242 if (C->getLHS()) {
243 LHSBlock = Visit(C->getLHS());
244 FinishBlock(LHSBlock);
245 Block = NULL;
246 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000247
Ted Kremenekecc04c92007-11-26 18:20:26 +0000248 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000249 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000250 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000251 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000252
Ted Kremenekecc04c92007-11-26 18:20:26 +0000253 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000254 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000255
256 if (LHSBlock)
257 Block->addSuccessor(LHSBlock);
258 else {
259 // If we have no LHS expression, add the ConfluenceBlock as a direct
260 // successor for the block containing the condition. Moreover,
261 // we need to reverse the order of the predecessors in the
262 // ConfluenceBlock because the RHSBlock will have been added to
263 // the succcessors already, and we want the first predecessor to the
264 // the block containing the expression for the case when the ternary
265 // expression evaluates to true.
266 Block->addSuccessor(ConfluenceBlock);
267 assert (ConfluenceBlock->pred_size() == 2);
268 std::reverse(ConfluenceBlock->pred_begin(),
269 ConfluenceBlock->pred_end());
270 }
271
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000272 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000273
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000274 Block->setTerminator(C);
275 return addStmt(C->getCond());
276 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000277
278 case Stmt::ChooseExprClass: {
279 ChooseExpr* C = cast<ChooseExpr>(S);
280
281 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
282 ConfluenceBlock->appendStmt(C);
283 FinishBlock(ConfluenceBlock);
284
285 Succ = ConfluenceBlock;
286 Block = NULL;
287 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000288 FinishBlock(LHSBlock);
289
Ted Kremenek49a436d2007-08-31 17:03:41 +0000290 Succ = ConfluenceBlock;
291 Block = NULL;
292 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000293 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000294
295 Block = createBlock(false);
296 Block->addSuccessor(LHSBlock);
297 Block->addSuccessor(RHSBlock);
298 Block->setTerminator(C);
299 return addStmt(C->getCond());
300 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000301
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000302 case Stmt::DeclStmtClass: {
303 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
304 Block->appendStmt(S);
305
306 StmtIterator I(D);
307 return WalkAST_VisitDeclSubExprs(I);
308 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000309
Ted Kremenek19bb3562007-08-28 19:26:49 +0000310 case Stmt::AddrLabelExprClass: {
311 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
312 AddressTakenLabels.insert(A->getLabel());
313
314 if (AlwaysAddStmt) Block->appendStmt(S);
315 return Block;
316 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000317
318 case Stmt::CallExprClass:
319 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000320
Ted Kremenek15c27a82007-08-28 18:30:10 +0000321 case Stmt::StmtExprClass:
322 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000323
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000324 case Stmt::UnaryOperatorClass: {
325 UnaryOperator* U = cast<UnaryOperator>(S);
326
327 // sizeof(expressions). For such expressions,
328 // the subexpression is not really evaluated, so
329 // we don't care about control-flow within the sizeof.
330 if (U->getOpcode() == UnaryOperator::SizeOf) {
331 Block->appendStmt(S);
332 return Block;
333 }
334
335 break;
336 }
337
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000338 case Stmt::BinaryOperatorClass: {
339 BinaryOperator* B = cast<BinaryOperator>(S);
340
341 if (B->isLogicalOp()) { // && or ||
342 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
343 ConfluenceBlock->appendStmt(B);
344 FinishBlock(ConfluenceBlock);
345
346 // create the block evaluating the LHS
347 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000348 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000349
350 // create the block evaluating the RHS
351 Succ = ConfluenceBlock;
352 Block = NULL;
353 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000354
355 // Now link the LHSBlock with RHSBlock.
356 if (B->getOpcode() == BinaryOperator::LOr) {
357 LHSBlock->addSuccessor(ConfluenceBlock);
358 LHSBlock->addSuccessor(RHSBlock);
359 }
360 else {
361 assert (B->getOpcode() == BinaryOperator::LAnd);
362 LHSBlock->addSuccessor(RHSBlock);
363 LHSBlock->addSuccessor(ConfluenceBlock);
364 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000365
366 // Generate the blocks for evaluating the LHS.
367 Block = LHSBlock;
368 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000369 }
370 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
371 Block->appendStmt(B);
372 addStmt(B->getRHS());
373 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000374 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000375
376 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000377 }
378
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000379 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000380 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000381 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000382
383 if (AlwaysAddStmt) Block->appendStmt(S);
384 return WalkAST_VisitChildren(S);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000385}
386
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000387/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
388/// DeclStmts. Because the initialization code (and sometimes the
389/// the type declarations) for DeclStmts can contain arbitrary expressions,
390/// we must linearize declarations to handle arbitrary control-flow induced by
391/// those expressions.
392CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000393 if (I == StmtIterator())
394 return Block;
395
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000396 Stmt* S = *I;
397 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000398 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000399
400 Block = addStmt(S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000401 return Block;
402}
403
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000404/// WalkAST_VisitChildren - Utility method to call WalkAST on the
405/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000406CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000407 CFGBlock* B = Block;
408 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
409 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000410 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000411
412 return B;
413}
414
Ted Kremenek15c27a82007-08-28 18:30:10 +0000415/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
416/// expressions (a GCC extension).
417CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
418 Block->appendStmt(S);
419 return VisitCompoundStmt(S->getSubStmt());
420}
421
Ted Kremenekf50ec102007-09-11 21:29:43 +0000422/// WalkAST_VisitCallExpr - Utility method to handle function calls that
423/// are nested in expressions. The idea is that each function call should
424/// appear as a distinct statement in the CFGBlock.
425CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
426 Block->appendStmt(C);
427 return WalkAST_VisitChildren(C);
428}
429
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000430/// VisitStmt - Handle statements with no branching control flow.
431CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
432 // We cannot assume that we are in the middle of a basic block, since
433 // the CFG might only be constructed for this single statement. If
434 // we have no current basic block, just create one lazily.
435 if (!Block) Block = createBlock();
436
437 // Simply add the statement to the current block. We actually
438 // insert statements in reverse order; this order is reversed later
439 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000440 addStmt(Statement);
441
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000442 return Block;
443}
444
445CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
446 return Block;
447}
448
449CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000450
Ted Kremenekd34066c2008-02-26 00:22:58 +0000451 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
452 I != E; ++I ) {
453 Visit(*I);
454 }
455
456 return Block;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000457}
458
459CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
460 // We may see an if statement in the middle of a basic block, or
461 // it may be the first statement we are processing. In either case,
462 // we create a new basic block. First, we create the blocks for
463 // the then...else statements, and then we create the block containing
464 // the if statement. If we were in the middle of a block, we
465 // stop processing that block and reverse its statements. That block
466 // is then the implicit successor for the "then" and "else" clauses.
467
468 // The block we were proccessing is now finished. Make it the
469 // successor block.
470 if (Block) {
471 Succ = Block;
472 FinishBlock(Block);
473 }
474
475 // Process the false branch. NULL out Block so that the recursive
476 // call to Visit will create a new basic block.
477 // Null out Block so that all successor
478 CFGBlock* ElseBlock = Succ;
479
480 if (Stmt* Else = I->getElse()) {
481 SaveAndRestore<CFGBlock*> sv(Succ);
482
483 // NULL out Block so that the recursive call to Visit will
484 // create a new basic block.
485 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000486 ElseBlock = Visit(Else);
487
488 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
489 ElseBlock = sv.get();
490 else if (Block)
491 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000492 }
493
494 // Process the true branch. NULL out Block so that the recursive
495 // call to Visit will create a new basic block.
496 // Null out Block so that all successor
497 CFGBlock* ThenBlock;
498 {
499 Stmt* Then = I->getThen();
500 assert (Then);
501 SaveAndRestore<CFGBlock*> sv(Succ);
502 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000503 ThenBlock = Visit(Then);
504
505 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
506 ThenBlock = sv.get();
507 else if (Block)
508 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000509 }
510
511 // Now create a new block containing the if statement.
512 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000513
514 // Set the terminator of the new block to the If statement.
515 Block->setTerminator(I);
516
517 // Now add the successors.
518 Block->addSuccessor(ThenBlock);
519 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000520
521 // Add the condition as the last statement in the new block. This
522 // may create new blocks as the condition may contain control-flow. Any
523 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000524 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000525}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000526
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000527
528CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
529 // If we were in the middle of a block we stop processing that block
530 // and reverse its statements.
531 //
532 // NOTE: If a "return" appears in the middle of a block, this means
533 // that the code afterwards is DEAD (unreachable). We still
534 // keep a basic block for that code; a simple "mark-and-sweep"
535 // from the entry block will be able to report such dead
536 // blocks.
537 if (Block) FinishBlock(Block);
538
539 // Create the new block.
540 Block = createBlock(false);
541
542 // The Exit block is the only successor.
543 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000544
545 // Add the return statement to the block. This may create new blocks
546 // if R contains control-flow (short-circuit operations).
547 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000548}
549
550CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
551 // Get the block of the labeled statement. Add it to our map.
552 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000553
554 if (!LabelBlock) // This can happen when the body is empty, i.e.
555 LabelBlock=createBlock(); // scopes that only contains NullStmts.
556
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000557 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
558 LabelMap[ L ] = LabelBlock;
559
560 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000561 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000562 // label (and we have already processed the substatement) there is no
563 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000564 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000565 FinishBlock(LabelBlock);
566
567 // We set Block to NULL to allow lazy creation of a new block
568 // (if necessary);
569 Block = NULL;
570
571 // This block is now the implicit successor of other blocks.
572 Succ = LabelBlock;
573
574 return LabelBlock;
575}
576
577CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
578 // Goto is a control-flow statement. Thus we stop processing the
579 // current block and create a new one.
580 if (Block) FinishBlock(Block);
581 Block = createBlock(false);
582 Block->setTerminator(G);
583
584 // If we already know the mapping to the label block add the
585 // successor now.
586 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
587
588 if (I == LabelMap.end())
589 // We will need to backpatch this block later.
590 BackpatchBlocks.push_back(Block);
591 else
592 Block->addSuccessor(I->second);
593
594 return Block;
595}
596
597CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
598 // "for" is a control-flow statement. Thus we stop processing the
599 // current block.
600
601 CFGBlock* LoopSuccessor = NULL;
602
603 if (Block) {
604 FinishBlock(Block);
605 LoopSuccessor = Block;
606 }
607 else LoopSuccessor = Succ;
608
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000609 // Because of short-circuit evaluation, the condition of the loop
610 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
611 // blocks that evaluate the condition.
612 CFGBlock* ExitConditionBlock = createBlock(false);
613 CFGBlock* EntryConditionBlock = ExitConditionBlock;
614
615 // Set the terminator for the "exit" condition block.
616 ExitConditionBlock->setTerminator(F);
617
618 // Now add the actual condition to the condition block. Because the
619 // condition itself may contain control-flow, new blocks may be created.
620 if (Stmt* C = F->getCond()) {
621 Block = ExitConditionBlock;
622 EntryConditionBlock = addStmt(C);
623 if (Block) FinishBlock(EntryConditionBlock);
624 }
Ted Kremenekd4fdee32007-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 Kremenek49af7cb2007-08-27 19:46:09 +0000628 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000629
630 // Now create the loop body.
631 {
632 assert (F->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 Kremenek49af7cb2007-08-27 19:46:09 +0000640 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000641
642 // All breaks should go to the code following the loop.
643 BreakTargetBlock = LoopSuccessor;
644
Ted Kremenekaf603f72007-08-30 18:39:40 +0000645 // Create a new block to contain the (bottom) of the loop body.
646 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000647
648 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000649 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000650
651 // Now populate the body block, and in the process create new blocks
652 // as we walk the body of the loop.
653 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000654
655 if (!BodyBlock)
656 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
657 else if (Block)
658 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000659
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000660 // This new body block is a successor to our "exit" condition block.
661 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000662 }
663
664 // Link up the condition block with the code that follows the loop.
665 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000666 ExitConditionBlock->addSuccessor(LoopSuccessor);
667
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000668 // If the loop contains initialization, create a new block for those
669 // statements. This block can also contain statements that precede
670 // the loop.
671 if (Stmt* I = F->getInit()) {
672 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000673 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000674 }
675 else {
676 // There is no loop initialization. We are thus basically a while
677 // loop. NULL out Block to force lazy block construction.
678 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000679 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000680 }
681}
682
683CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
684 // "while" is a control-flow statement. Thus we stop processing the
685 // current block.
686
687 CFGBlock* LoopSuccessor = NULL;
688
689 if (Block) {
690 FinishBlock(Block);
691 LoopSuccessor = Block;
692 }
693 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000694
695 // Because of short-circuit evaluation, the condition of the loop
696 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
697 // blocks that evaluate the condition.
698 CFGBlock* ExitConditionBlock = createBlock(false);
699 CFGBlock* EntryConditionBlock = ExitConditionBlock;
700
701 // Set the terminator for the "exit" condition block.
702 ExitConditionBlock->setTerminator(W);
703
704 // Now add the actual condition to the condition block. Because the
705 // condition itself may contain control-flow, new blocks may be created.
706 // Thus we update "Succ" after adding the condition.
707 if (Stmt* C = W->getCond()) {
708 Block = ExitConditionBlock;
709 EntryConditionBlock = addStmt(C);
710 if (Block) FinishBlock(EntryConditionBlock);
711 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000712
713 // The condition block is the implicit successor for the loop body as
714 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000715 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000716
717 // Process the loop body.
718 {
719 assert (W->getBody());
720
721 // Save the current values for Block, Succ, and continue and break targets
722 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
723 save_continue(ContinueTargetBlock),
724 save_break(BreakTargetBlock);
725
726 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000727 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000728
729 // All breaks should go to the code following the loop.
730 BreakTargetBlock = LoopSuccessor;
731
732 // NULL out Block to force lazy instantiation of blocks for the body.
733 Block = NULL;
734
735 // Create the body. The returned block is the entry to the loop body.
736 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000737
738 if (!BodyBlock)
739 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
740 else if (Block)
741 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000742
743 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000744 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000745 }
746
747 // Link up the condition block with the code that follows the loop.
748 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000749 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000750
751 // There can be no more statements in the condition block
752 // since we loop back to this block. NULL out Block to force
753 // lazy creation of another block.
754 Block = NULL;
755
756 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000757 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000758}
759
760CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
761 // "do...while" is a control-flow statement. Thus we stop processing the
762 // current block.
763
764 CFGBlock* LoopSuccessor = NULL;
765
766 if (Block) {
767 FinishBlock(Block);
768 LoopSuccessor = Block;
769 }
770 else LoopSuccessor = Succ;
771
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000772 // Because of short-circuit evaluation, the condition of the loop
773 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
774 // blocks that evaluate the condition.
775 CFGBlock* ExitConditionBlock = createBlock(false);
776 CFGBlock* EntryConditionBlock = ExitConditionBlock;
777
778 // Set the terminator for the "exit" condition block.
779 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000780
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000781 // Now add the actual condition to the condition block. Because the
782 // condition itself may contain control-flow, new blocks may be created.
783 if (Stmt* C = D->getCond()) {
784 Block = ExitConditionBlock;
785 EntryConditionBlock = addStmt(C);
786 if (Block) FinishBlock(EntryConditionBlock);
787 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000788
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000789 // The condition block is the implicit successor for the loop body as
790 // well as any code above the loop.
791 Succ = EntryConditionBlock;
792
793
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000794 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000795 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000796 {
797 assert (D->getBody());
798
799 // Save the current values for Block, Succ, and continue and break targets
800 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
801 save_continue(ContinueTargetBlock),
802 save_break(BreakTargetBlock);
803
804 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000805 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000806
807 // All breaks should go to the code following the loop.
808 BreakTargetBlock = LoopSuccessor;
809
810 // NULL out Block to force lazy instantiation of blocks for the body.
811 Block = NULL;
812
813 // Create the body. The returned block is the entry to the loop body.
814 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000815
Ted Kremenekaf603f72007-08-30 18:39:40 +0000816 if (!BodyBlock)
817 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
818 else if (Block)
819 FinishBlock(BodyBlock);
820
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000821 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000822 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000823 }
824
825 // Link up the condition block with the code that follows the loop.
826 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000827 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000828
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000829 // There can be no more statements in the body block(s)
830 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000831 // lazy creation of another block.
832 Block = NULL;
833
834 // Return the loop body, which is the dominating block for the loop.
835 return BodyBlock;
836}
837
838CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
839 // "continue" is a control-flow statement. Thus we stop processing the
840 // current block.
841 if (Block) FinishBlock(Block);
842
843 // Now create a new block that ends with the continue statement.
844 Block = createBlock(false);
845 Block->setTerminator(C);
846
847 // If there is no target for the continue, then we are looking at an
848 // incomplete AST. Handle this by not registering a successor.
849 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
850
851 return Block;
852}
853
854CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
855 // "break" is a control-flow statement. Thus we stop processing the
856 // current block.
857 if (Block) FinishBlock(Block);
858
859 // Now create a new block that ends with the continue statement.
860 Block = createBlock(false);
861 Block->setTerminator(B);
862
863 // If there is no target for the break, then we are looking at an
864 // incomplete AST. Handle this by not registering a successor.
865 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
866
867 return Block;
868}
869
870CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
871 // "switch" is a control-flow statement. Thus we stop processing the
872 // current block.
873 CFGBlock* SwitchSuccessor = NULL;
874
875 if (Block) {
876 FinishBlock(Block);
877 SwitchSuccessor = Block;
878 }
879 else SwitchSuccessor = Succ;
880
881 // Save the current "switch" context.
882 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000883 save_break(BreakTargetBlock),
884 save_default(DefaultCaseBlock);
885
886 // Set the "default" case to be the block after the switch statement.
887 // If the switch statement contains a "default:", this value will
888 // be overwritten with the block for that code.
889 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000890
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000891 // Create a new block that will contain the switch statement.
892 SwitchTerminatedBlock = createBlock(false);
893
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000894 // Now process the switch body. The code after the switch is the implicit
895 // successor.
896 Succ = SwitchSuccessor;
897 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000898
899 // When visiting the body, the case statements should automatically get
900 // linked up to the switch. We also don't keep a pointer to the body,
901 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000902 assert (S->getBody() && "switch must contain a non-NULL body");
903 Block = NULL;
904 CFGBlock *BodyBlock = Visit(S->getBody());
905 if (Block) FinishBlock(BodyBlock);
906
Ted Kremenek295222c2008-02-13 21:46:34 +0000907 // If we have no "default:" case, the default transition is to the
908 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000909 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000910
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000911 // Add the terminator and condition in the switch block.
912 SwitchTerminatedBlock->setTerminator(S);
913 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000914 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000915
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000916 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000917}
918
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000919CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
920 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000921 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000922
923 if (S->getSubStmt()) Visit(S->getSubStmt());
924 CFGBlock* CaseBlock = Block;
925 if (!CaseBlock) CaseBlock = createBlock();
926
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000927 // Cases statements partition blocks, so this is the top of
928 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek9cffe732007-08-29 23:20:49 +0000929 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000930 FinishBlock(CaseBlock);
931
932 // Add this block to the list of successors for the block with the
933 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000934 assert (SwitchTerminatedBlock);
935 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000936
937 // We set Block to NULL to allow lazy creation of a new block (if necessary)
938 Block = NULL;
939
940 // This block is now the implicit successor of other blocks.
941 Succ = CaseBlock;
942
943 return CaseBlock;
944}
Ted Kremenek295222c2008-02-13 21:46:34 +0000945
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000946CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
947 if (S->getSubStmt()) Visit(S->getSubStmt());
948 DefaultCaseBlock = Block;
949 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
950
951 // Default statements partition blocks, so this is the top of
952 // the basic block we were processing (the "default:" is the label).
953 DefaultCaseBlock->setLabel(S);
954 FinishBlock(DefaultCaseBlock);
955
956 // Unlike case statements, we don't add the default block to the
957 // successors for the switch statement immediately. This is done
958 // when we finish processing the switch statement. This allows for
959 // the default case (including a fall-through to the code after the
960 // switch statement) to always be the last successor of a switch-terminated
961 // block.
962
963 // We set Block to NULL to allow lazy creation of a new block (if necessary)
964 Block = NULL;
965
966 // This block is now the implicit successor of other blocks.
967 Succ = DefaultCaseBlock;
968
969 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000970}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000971
Ted Kremenek19bb3562007-08-28 19:26:49 +0000972CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
973 // Lazily create the indirect-goto dispatch block if there isn't one
974 // already.
975 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
976
977 if (!IBlock) {
978 IBlock = createBlock(false);
979 cfg->setIndirectGotoBlock(IBlock);
980 }
981
982 // IndirectGoto is a control-flow statement. Thus we stop processing the
983 // current block and create a new one.
984 if (Block) FinishBlock(Block);
985 Block = createBlock(false);
986 Block->setTerminator(I);
987 Block->addSuccessor(IBlock);
988 return addStmt(I->getTarget());
989}
990
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000991
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000992} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000993
994/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
995/// block has no successors or predecessors. If this is the first block
996/// created in the CFG, it is automatically set to be the Entry and Exit
997/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000998CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000999 bool first_block = begin() == end();
1000
1001 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001002 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001003
1004 // If this is the first block, set it as the Entry and Exit.
1005 if (first_block) Entry = Exit = &front();
1006
1007 // Return the block.
1008 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001009}
1010
Ted Kremenek026473c2007-08-23 16:51:22 +00001011/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1012/// CFG is returned to the caller.
1013CFG* CFG::buildCFG(Stmt* Statement) {
1014 CFGBuilder Builder;
1015 return Builder.buildCFG(Statement);
1016}
1017
1018/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001019void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1020
Ted Kremenek63f58872007-10-01 19:33:33 +00001021//===----------------------------------------------------------------------===//
1022// CFG: Queries for BlkExprs.
1023//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001024
Ted Kremenek63f58872007-10-01 19:33:33 +00001025namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001026 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001027}
1028
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001029static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1030 if (!S)
1031 return;
1032
1033 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1034 if (!*I) continue;
1035
1036 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1037 if (B->isAssignmentOp()) Set.insert(B);
1038
1039 FindSubExprAssignments(*I, Set);
1040 }
1041}
1042
Ted Kremenek63f58872007-10-01 19:33:33 +00001043static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1044 BlkExprMapTy* M = new BlkExprMapTy();
1045
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001046 // Look for assignments that are used as subexpressions. These are the
1047 // only assignments that we want to register as a block-level expression.
1048 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1049
Ted Kremenek63f58872007-10-01 19:33:33 +00001050 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1051 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001052 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001053
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001054 // Iterate over the statements again on identify the Expr* and Stmt* at
1055 // the block-level that are block-level expressions.
1056 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1057 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1058 if (Expr* E = dyn_cast<Expr>(*BI)) {
1059
1060 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1061 // Assignment expressions that are not nested within another
1062 // expression are really "statements" whose value is never
1063 // used by another expression.
1064 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1065 continue;
1066 }
1067 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1068 // Special handling for statement expressions. The last statement
1069 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001070 const CompoundStmt* C = S->getSubStmt();
1071 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001072 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001073 (*M)[C->body_back()] = x;
1074 }
1075 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001076
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001077 unsigned x = M->size();
1078 (*M)[E] = x;
1079 }
1080
Ted Kremenek63f58872007-10-01 19:33:33 +00001081 return M;
1082}
1083
Ted Kremenek86946742008-01-17 20:48:37 +00001084CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1085 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001086 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1087
1088 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001089 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001090
1091 if (I == M->end()) return CFG::BlkExprNumTy();
1092 else return CFG::BlkExprNumTy(I->second);
1093}
1094
1095unsigned CFG::getNumBlkExprs() {
1096 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1097 return M->size();
1098 else {
1099 // We assume callers interested in the number of BlkExprs will want
1100 // the map constructed if it doesn't already exist.
1101 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1102 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1103 }
1104}
1105
Ted Kremenek83c01da2008-01-11 00:40:29 +00001106typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1107
1108const std::pair<CFGBlock*,CFGBlock*>*
1109CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1110
1111 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1112 if (!p) p = new BlkEdgeSetTy();
1113
1114 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1115 const_cast<CFGBlock*>(B2))).first);
1116}
1117
Ted Kremenek63f58872007-10-01 19:33:33 +00001118CFG::~CFG() {
1119 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001120 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001121}
1122
Ted Kremenek7dba8602007-08-29 21:56:09 +00001123//===----------------------------------------------------------------------===//
1124// CFG pretty printing
1125//===----------------------------------------------------------------------===//
1126
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001127namespace {
1128
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001129class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001130
Ted Kremenek42a509f2007-08-31 21:30:12 +00001131 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1132 StmtMapTy StmtMap;
1133 signed CurrentBlock;
1134 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001135
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001136public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001137
Ted Kremenek42a509f2007-08-31 21:30:12 +00001138 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1139 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1140 unsigned j = 1;
1141 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1142 BI != BEnd; ++BI, ++j )
1143 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1144 }
1145 }
1146
1147 virtual ~StmtPrinterHelper() {}
1148
1149 void setBlockID(signed i) { CurrentBlock = i; }
1150 void setStmtID(unsigned i) { CurrentStmt = i; }
1151
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001152 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1153
1154 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001155
1156 if (I == StmtMap.end())
1157 return false;
1158
1159 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1160 && I->second.second == CurrentStmt)
1161 return false;
1162
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001163 OS << "[B" << I->second.first << "." << I->second.second << "]";
1164 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001165 }
1166};
1167
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001168class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1169 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1170
Ted Kremenek42a509f2007-08-31 21:30:12 +00001171 std::ostream& OS;
1172 StmtPrinterHelper* Helper;
1173public:
1174 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1175 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001176
1177 void VisitIfStmt(IfStmt* I) {
1178 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001179 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001180 }
1181
1182 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001183 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001184
1185 void VisitForStmt(ForStmt* F) {
1186 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001187 if (F->getInit()) OS << "...";
1188 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001189 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001190 OS << "; ";
1191 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001192 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001193 }
1194
1195 void VisitWhileStmt(WhileStmt* W) {
1196 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001197 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001198 }
1199
1200 void VisitDoStmt(DoStmt* D) {
1201 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001202 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001203 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001204
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001205 void VisitSwitchStmt(SwitchStmt* S) {
1206 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001207 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001208 }
1209
Ted Kremenek805e9a82007-08-31 21:49:40 +00001210 void VisitConditionalOperator(ConditionalOperator* C) {
1211 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001212 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001213 }
1214
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001215 void VisitChooseExpr(ChooseExpr* C) {
1216 OS << "__builtin_choose_expr( ";
1217 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001218 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001219 }
1220
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001221 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1222 OS << "goto *";
1223 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001224 }
1225
Ted Kremenek805e9a82007-08-31 21:49:40 +00001226 void VisitBinaryOperator(BinaryOperator* B) {
1227 if (!B->isLogicalOp()) {
1228 VisitExpr(B);
1229 return;
1230 }
1231
1232 B->getLHS()->printPretty(OS,Helper);
1233
1234 switch (B->getOpcode()) {
1235 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001236 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001237 return;
1238 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001239 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001240 return;
1241 default:
1242 assert(false && "Invalid logical operator.");
1243 }
1244 }
1245
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001246 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001247 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001248 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001249};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001250
1251
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001252void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1253 if (Helper) {
1254 // special printing for statement-expressions.
1255 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1256 CompoundStmt* Sub = SE->getSubStmt();
1257
1258 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001259 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001260 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001261 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001262 return;
1263 }
1264 }
1265
1266 // special printing for comma expressions.
1267 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1268 if (B->getOpcode() == BinaryOperator::Comma) {
1269 OS << "... , ";
1270 Helper->handledStmt(B->getRHS(),OS);
1271 OS << '\n';
1272 return;
1273 }
1274 }
1275 }
1276
1277 S->printPretty(OS, Helper);
1278
1279 // Expressions need a newline.
1280 if (isa<Expr>(S)) OS << '\n';
1281}
1282
Ted Kremenek42a509f2007-08-31 21:30:12 +00001283void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1284 StmtPrinterHelper* Helper, bool print_edges) {
1285
1286 if (Helper) Helper->setBlockID(B.getBlockID());
1287
Ted Kremenek7dba8602007-08-29 21:56:09 +00001288 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001289 OS << "\n [ B" << B.getBlockID();
1290
1291 if (&B == &cfg->getEntry())
1292 OS << " (ENTRY) ]\n";
1293 else if (&B == &cfg->getExit())
1294 OS << " (EXIT) ]\n";
1295 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001296 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001297 else
1298 OS << " ]\n";
1299
Ted Kremenek9cffe732007-08-29 23:20:49 +00001300 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001301 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1302
1303 if (print_edges)
1304 OS << " ";
1305
Ted Kremenek9cffe732007-08-29 23:20:49 +00001306 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1307 OS << L->getName();
1308 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1309 OS << "case ";
1310 C->getLHS()->printPretty(OS);
1311 if (C->getRHS()) {
1312 OS << " ... ";
1313 C->getRHS()->printPretty(OS);
1314 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001315 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001316 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001317 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001318 else
1319 assert(false && "Invalid label statement in CFGBlock.");
1320
Ted Kremenek9cffe732007-08-29 23:20:49 +00001321 OS << ":\n";
1322 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001323
Ted Kremenekfddd5182007-08-21 21:42:03 +00001324 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001325 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001326
1327 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1328 I != E ; ++I, ++j ) {
1329
Ted Kremenek9cffe732007-08-29 23:20:49 +00001330 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001331 if (print_edges)
1332 OS << " ";
1333
1334 OS << std::setw(3) << j << ": ";
1335
1336 if (Helper)
1337 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001338
1339 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001340 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001341
Ted Kremenek9cffe732007-08-29 23:20:49 +00001342 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001343 if (B.getTerminator()) {
1344 if (print_edges)
1345 OS << " ";
1346
Ted Kremenek9cffe732007-08-29 23:20:49 +00001347 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001348
1349 if (Helper) Helper->setBlockID(-1);
1350
1351 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1352 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001353 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001354 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001355
Ted Kremenek9cffe732007-08-29 23:20:49 +00001356 if (print_edges) {
1357 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001358 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001359 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001360
Ted Kremenek42a509f2007-08-31 21:30:12 +00001361 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1362 I != E; ++I, ++i) {
1363
1364 if (i == 8 || (i-8) == 0)
1365 OS << "\n ";
1366
Ted Kremenek9cffe732007-08-29 23:20:49 +00001367 OS << " B" << (*I)->getBlockID();
1368 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001369
1370 OS << '\n';
1371
1372 // Print the successors of this block.
1373 OS << " Successors (" << B.succ_size() << "):";
1374 i = 0;
1375
1376 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1377 I != E; ++I, ++i) {
1378
1379 if (i == 8 || (i-8) % 10 == 0)
1380 OS << "\n ";
1381
1382 OS << " B" << (*I)->getBlockID();
1383 }
1384
Ted Kremenek9cffe732007-08-29 23:20:49 +00001385 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001386 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001387}
1388
1389} // end anonymous namespace
1390
1391/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001392void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001393
1394/// print - A simple pretty printer of a CFG that outputs to an ostream.
1395void CFG::print(std::ostream& OS) const {
1396
1397 StmtPrinterHelper Helper(this);
1398
1399 // Print the entry block.
1400 print_block(OS, this, getEntry(), &Helper, true);
1401
1402 // Iterate through the CFGBlocks and print them one by one.
1403 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1404 // Skip the entry block, because we already printed it.
1405 if (&(*I) == &getEntry() || &(*I) == &getExit())
1406 continue;
1407
1408 print_block(OS, this, *I, &Helper, true);
1409 }
1410
1411 // Print the exit block.
1412 print_block(OS, this, getExit(), &Helper, true);
1413}
1414
1415/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001416void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001417
1418/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1419/// Generally this will only be called from CFG::print.
1420void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1421 StmtPrinterHelper Helper(cfg);
1422 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001423}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001424
Ted Kremeneka2925852008-01-30 23:02:42 +00001425/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1426void CFGBlock::printTerminator(std::ostream& OS) const {
1427 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1428 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1429}
1430
1431
Ted Kremenek7dba8602007-08-29 21:56:09 +00001432//===----------------------------------------------------------------------===//
1433// CFG Graphviz Visualization
1434//===----------------------------------------------------------------------===//
1435
Ted Kremenek42a509f2007-08-31 21:30:12 +00001436
1437#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001438static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001439#endif
1440
1441void CFG::viewCFG() const {
1442#ifndef NDEBUG
1443 StmtPrinterHelper H(this);
1444 GraphHelper = &H;
1445 llvm::ViewGraph(this,"CFG");
1446 GraphHelper = NULL;
1447#else
1448 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001449 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001450#endif
1451}
1452
Ted Kremenek7dba8602007-08-29 21:56:09 +00001453namespace llvm {
1454template<>
1455struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1456 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1457
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001458#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001459 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001460 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001461 std::string OutStr = Out.str();
1462
1463 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1464
1465 // Process string output to make it nicer...
1466 for (unsigned i = 0; i != OutStr.length(); ++i)
1467 if (OutStr[i] == '\n') { // Left justify
1468 OutStr[i] = '\\';
1469 OutStr.insert(OutStr.begin()+i+1, 'l');
1470 }
1471
1472 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001473#else
1474 return "";
1475#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001476 }
1477};
1478} // end namespace llvm