blob: 431b2e23af14c25b58b548ede0da275cd3938b08 [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Kremenek97f75312007-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 Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek5ee98a72008-01-11 00:40:29 +000024#include <set>
Ted Kremenek97f75312007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000027#include <sstream>
28
Ted Kremenek5ee98a72008-01-11 00:40:29 +000029
Ted Kremenek97f75312007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekd6e50602007-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 Kremenek98cee3a2008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekd6e50602007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenek97f75312007-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 Kremenek95e854d2007-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 Kremenek98cee3a2008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000069
Ted Kremenek0edd3a92007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek0edd3a92007-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 Kremenekf5392b72007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek0edd3a92007-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 Kremenek97f75312007-08-21 21:42:03 +000083public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000098
Ted Kremenek73543912007-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 Kremenek97bc3422008-02-13 22:05:39 +0000112 CFGBlock* VisitCaseStmt(CaseStmt* S);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000115
Ted Kremenek73543912007-08-23 21:42:29 +0000116private:
117 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000118 CFGBlock* addStmt(Stmt* S);
119 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
120 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000121 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000122 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekd11620d2007-09-11 21:29:43 +0000123 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenek73543912007-08-23 21:42:29 +0000124 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000125
Ted Kremenek97f75312007-08-21 21:42:03 +0000126};
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000134 assert (cfg);
Ted Kremenek73543912007-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 Kremenekcfee50c2007-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 Kremenek73543912007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000148 if (Block) FinishBlock(B);
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000164 }
Ted Kremenek73543912007-08-23 21:42:29 +0000165
Ted Kremenek0edd3a92007-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 Kremenek680fcb82007-09-26 21:23:31 +0000180
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000181 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000182 }
183
184 // Create an empty entry block that has no predecessors.
185 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000186
Ted Kremenek680fcb82007-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 Kremenek73543912007-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 Kremenek14594572007-09-05 20:02:05 +0000197 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000203/// we must reverse the statements because they have been inserted
204/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000205void CFGBuilder::FinishBlock(CFGBlock* B) {
206 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000207 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000208}
209
Ted Kremenek65cfa562007-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 Kremenek390b9762007-08-30 18:39:40 +0000217 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-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 Kremeneke822b622007-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 Kremenek65cfa562007-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 Kremenekc0980cd2007-11-26 18:20:26 +0000228
229 // Create the confluence block that will "merge" the results
230 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000231 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
232 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000233 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-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 Kremenek65cfa562007-08-27 21:27:44 +0000239 Succ = ConfluenceBlock;
240 Block = NULL;
Ted Kremenekc0980cd2007-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 Kremenek65cfa562007-08-27 21:27:44 +0000247
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000248 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000249 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000250 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000251 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000252
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000253 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000254 Block = createBlock(false);
Ted Kremenekc0980cd2007-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 Kremenek65cfa562007-08-27 21:27:44 +0000272 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000273
Ted Kremenek65cfa562007-08-27 21:27:44 +0000274 Block->setTerminator(C);
275 return addStmt(C->getCond());
276 }
Ted Kremenek7f788422007-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 Kremenekd11620d2007-09-11 21:29:43 +0000288 FinishBlock(LHSBlock);
289
Ted Kremenek7f788422007-08-31 17:03:41 +0000290 Succ = ConfluenceBlock;
291 Block = NULL;
292 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000293 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-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 Kremenek666a6af2007-08-28 16:18:58 +0000301
Ted Kremenek7c6c0fd2007-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 Kremenek6fca3e02007-08-28 18:30:10 +0000309
Ted Kremenek0edd3a92007-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 Kremenekd11620d2007-09-11 21:29:43 +0000317
318 case Stmt::CallExprClass:
319 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000320
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000321 case Stmt::StmtExprClass:
322 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000323
Ted Kremenekd1a80f72007-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 Kremenekcfaae762007-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 Kremenekb2348522007-12-21 19:49:00 +0000348 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-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 Kremenekb2348522007-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 Kremenekcfaae762007-08-27 21:54:41 +0000365
366 // Generate the blocks for evaluating the LHS.
367 Block = LHSBlock;
368 return addStmt(B->getLHS());
Ted Kremeneke822b622007-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 Kremenek3a819822007-10-01 19:33:33 +0000374 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000375
376 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000377 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000378
379 case Stmt::ParenExprClass:
380 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000381
Ted Kremenek65cfa562007-08-27 21:27:44 +0000382 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000383 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000384 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000385
386 if (AlwaysAddStmt) Block->appendStmt(S);
387 return WalkAST_VisitChildren(S);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000388}
389
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000390/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
391/// DeclStmts. Because the initialization code (and sometimes the
392/// the type declarations) for DeclStmts can contain arbitrary expressions,
393/// we must linearize declarations to handle arbitrary control-flow induced by
394/// those expressions.
395CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000396 if (I == StmtIterator())
397 return Block;
398
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000399 Stmt* S = *I;
400 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000401 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000402
403 Block = addStmt(S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000404 return Block;
405}
406
Ted Kremenek65cfa562007-08-27 21:27:44 +0000407/// WalkAST_VisitChildren - Utility method to call WalkAST on the
408/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000409CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000410 CFGBlock* B = Block;
411 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
412 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000413 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000414
415 return B;
416}
417
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000418/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
419/// expressions (a GCC extension).
420CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
421 Block->appendStmt(S);
422 return VisitCompoundStmt(S->getSubStmt());
423}
424
Ted Kremenekd11620d2007-09-11 21:29:43 +0000425/// WalkAST_VisitCallExpr - Utility method to handle function calls that
426/// are nested in expressions. The idea is that each function call should
427/// appear as a distinct statement in the CFGBlock.
428CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
429 Block->appendStmt(C);
430 return WalkAST_VisitChildren(C);
431}
432
Ted Kremenek73543912007-08-23 21:42:29 +0000433/// VisitStmt - Handle statements with no branching control flow.
434CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
435 // We cannot assume that we are in the middle of a basic block, since
436 // the CFG might only be constructed for this single statement. If
437 // we have no current basic block, just create one lazily.
438 if (!Block) Block = createBlock();
439
440 // Simply add the statement to the current block. We actually
441 // insert statements in reverse order; this order is reversed later
442 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000443 addStmt(Statement);
444
Ted Kremenek73543912007-08-23 21:42:29 +0000445 return Block;
446}
447
448CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
449 return Block;
450}
451
452CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek73543912007-08-23 21:42:29 +0000453
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000454 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
455 I != E; ++I ) {
456 Visit(*I);
457 }
458
459 return Block;
Ted Kremenek73543912007-08-23 21:42:29 +0000460}
461
462CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
463 // We may see an if statement in the middle of a basic block, or
464 // it may be the first statement we are processing. In either case,
465 // we create a new basic block. First, we create the blocks for
466 // the then...else statements, and then we create the block containing
467 // the if statement. If we were in the middle of a block, we
468 // stop processing that block and reverse its statements. That block
469 // is then the implicit successor for the "then" and "else" clauses.
470
471 // The block we were proccessing is now finished. Make it the
472 // successor block.
473 if (Block) {
474 Succ = Block;
475 FinishBlock(Block);
476 }
477
478 // Process the false branch. NULL out Block so that the recursive
479 // call to Visit will create a new basic block.
480 // Null out Block so that all successor
481 CFGBlock* ElseBlock = Succ;
482
483 if (Stmt* Else = I->getElse()) {
484 SaveAndRestore<CFGBlock*> sv(Succ);
485
486 // NULL out Block so that the recursive call to Visit will
487 // create a new basic block.
488 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000489 ElseBlock = Visit(Else);
490
491 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
492 ElseBlock = sv.get();
493 else if (Block)
494 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000495 }
496
497 // Process the true branch. NULL out Block so that the recursive
498 // call to Visit will create a new basic block.
499 // Null out Block so that all successor
500 CFGBlock* ThenBlock;
501 {
502 Stmt* Then = I->getThen();
503 assert (Then);
504 SaveAndRestore<CFGBlock*> sv(Succ);
505 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000506 ThenBlock = Visit(Then);
507
508 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
509 ThenBlock = sv.get();
510 else if (Block)
511 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000512 }
513
514 // Now create a new block containing the if statement.
515 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000516
517 // Set the terminator of the new block to the If statement.
518 Block->setTerminator(I);
519
520 // Now add the successors.
521 Block->addSuccessor(ThenBlock);
522 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000523
524 // Add the condition as the last statement in the new block. This
525 // may create new blocks as the condition may contain control-flow. Any
526 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000527 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000528}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000529
Ted Kremenek73543912007-08-23 21:42:29 +0000530
531CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
532 // If we were in the middle of a block we stop processing that block
533 // and reverse its statements.
534 //
535 // NOTE: If a "return" appears in the middle of a block, this means
536 // that the code afterwards is DEAD (unreachable). We still
537 // keep a basic block for that code; a simple "mark-and-sweep"
538 // from the entry block will be able to report such dead
539 // blocks.
540 if (Block) FinishBlock(Block);
541
542 // Create the new block.
543 Block = createBlock(false);
544
545 // The Exit block is the only successor.
546 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000547
548 // Add the return statement to the block. This may create new blocks
549 // if R contains control-flow (short-circuit operations).
550 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000551}
552
553CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
554 // Get the block of the labeled statement. Add it to our map.
555 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000556
557 if (!LabelBlock) // This can happen when the body is empty, i.e.
558 LabelBlock=createBlock(); // scopes that only contains NullStmts.
559
Ted Kremenek73543912007-08-23 21:42:29 +0000560 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
561 LabelMap[ L ] = LabelBlock;
562
563 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000564 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000565 // label (and we have already processed the substatement) there is no
566 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000567 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000568 FinishBlock(LabelBlock);
569
570 // We set Block to NULL to allow lazy creation of a new block
571 // (if necessary);
572 Block = NULL;
573
574 // This block is now the implicit successor of other blocks.
575 Succ = LabelBlock;
576
577 return LabelBlock;
578}
579
580CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
581 // Goto is a control-flow statement. Thus we stop processing the
582 // current block and create a new one.
583 if (Block) FinishBlock(Block);
584 Block = createBlock(false);
585 Block->setTerminator(G);
586
587 // If we already know the mapping to the label block add the
588 // successor now.
589 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
590
591 if (I == LabelMap.end())
592 // We will need to backpatch this block later.
593 BackpatchBlocks.push_back(Block);
594 else
595 Block->addSuccessor(I->second);
596
597 return Block;
598}
599
600CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
601 // "for" is a control-flow statement. Thus we stop processing the
602 // current block.
603
604 CFGBlock* LoopSuccessor = NULL;
605
606 if (Block) {
607 FinishBlock(Block);
608 LoopSuccessor = Block;
609 }
610 else LoopSuccessor = Succ;
611
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000612 // Because of short-circuit evaluation, the condition of the loop
613 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
614 // blocks that evaluate the condition.
615 CFGBlock* ExitConditionBlock = createBlock(false);
616 CFGBlock* EntryConditionBlock = ExitConditionBlock;
617
618 // Set the terminator for the "exit" condition block.
619 ExitConditionBlock->setTerminator(F);
620
621 // Now add the actual condition to the condition block. Because the
622 // condition itself may contain control-flow, new blocks may be created.
623 if (Stmt* C = F->getCond()) {
624 Block = ExitConditionBlock;
625 EntryConditionBlock = addStmt(C);
626 if (Block) FinishBlock(EntryConditionBlock);
627 }
Ted Kremenek73543912007-08-23 21:42:29 +0000628
629 // The condition block is the implicit successor for the loop body as
630 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000631 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000632
633 // Now create the loop body.
634 {
635 assert (F->getBody());
636
637 // Save the current values for Block, Succ, and continue and break targets
638 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
639 save_continue(ContinueTargetBlock),
640 save_break(BreakTargetBlock);
641
642 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000643 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000644
645 // All breaks should go to the code following the loop.
646 BreakTargetBlock = LoopSuccessor;
647
Ted Kremenek390b9762007-08-30 18:39:40 +0000648 // Create a new block to contain the (bottom) of the loop body.
649 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000650
651 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000652 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000653
654 // Now populate the body block, and in the process create new blocks
655 // as we walk the body of the loop.
656 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000657
658 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000659 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000660 else if (Block)
661 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000662
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000663 // This new body block is a successor to our "exit" condition block.
664 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000665 }
666
667 // Link up the condition block with the code that follows the loop.
668 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000669 ExitConditionBlock->addSuccessor(LoopSuccessor);
670
Ted Kremenek73543912007-08-23 21:42:29 +0000671 // If the loop contains initialization, create a new block for those
672 // statements. This block can also contain statements that precede
673 // the loop.
674 if (Stmt* I = F->getInit()) {
675 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000676 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000677 }
678 else {
679 // There is no loop initialization. We are thus basically a while
680 // loop. NULL out Block to force lazy block construction.
681 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000682 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000683 }
684}
685
686CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
687 // "while" is a control-flow statement. Thus we stop processing the
688 // current block.
689
690 CFGBlock* LoopSuccessor = NULL;
691
692 if (Block) {
693 FinishBlock(Block);
694 LoopSuccessor = Block;
695 }
696 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000697
698 // Because of short-circuit evaluation, the condition of the loop
699 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
700 // blocks that evaluate the condition.
701 CFGBlock* ExitConditionBlock = createBlock(false);
702 CFGBlock* EntryConditionBlock = ExitConditionBlock;
703
704 // Set the terminator for the "exit" condition block.
705 ExitConditionBlock->setTerminator(W);
706
707 // Now add the actual condition to the condition block. Because the
708 // condition itself may contain control-flow, new blocks may be created.
709 // Thus we update "Succ" after adding the condition.
710 if (Stmt* C = W->getCond()) {
711 Block = ExitConditionBlock;
712 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000713 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000714 if (Block) FinishBlock(EntryConditionBlock);
715 }
Ted Kremenek73543912007-08-23 21:42:29 +0000716
717 // The condition block is the implicit successor for the loop body as
718 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000719 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000720
721 // Process the loop body.
722 {
723 assert (W->getBody());
724
725 // Save the current values for Block, Succ, and continue and break targets
726 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
727 save_continue(ContinueTargetBlock),
728 save_break(BreakTargetBlock);
729
730 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000731 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000732
733 // All breaks should go to the code following the loop.
734 BreakTargetBlock = LoopSuccessor;
735
736 // NULL out Block to force lazy instantiation of blocks for the body.
737 Block = NULL;
738
739 // Create the body. The returned block is the entry to the loop body.
740 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000741
742 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000743 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000744 else if (Block)
745 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000746
747 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000748 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000749 }
750
751 // Link up the condition block with the code that follows the loop.
752 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000753 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000754
755 // There can be no more statements in the condition block
756 // since we loop back to this block. NULL out Block to force
757 // lazy creation of another block.
758 Block = NULL;
759
760 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000761 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000762}
763
764CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
765 // "do...while" is a control-flow statement. Thus we stop processing the
766 // current block.
767
768 CFGBlock* LoopSuccessor = NULL;
769
770 if (Block) {
771 FinishBlock(Block);
772 LoopSuccessor = Block;
773 }
774 else LoopSuccessor = Succ;
775
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000776 // Because of short-circuit evaluation, the condition of the loop
777 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
778 // blocks that evaluate the condition.
779 CFGBlock* ExitConditionBlock = createBlock(false);
780 CFGBlock* EntryConditionBlock = ExitConditionBlock;
781
782 // Set the terminator for the "exit" condition block.
783 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000784
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000785 // Now add the actual condition to the condition block. Because the
786 // condition itself may contain control-flow, new blocks may be created.
787 if (Stmt* C = D->getCond()) {
788 Block = ExitConditionBlock;
789 EntryConditionBlock = addStmt(C);
790 if (Block) FinishBlock(EntryConditionBlock);
791 }
Ted Kremenek73543912007-08-23 21:42:29 +0000792
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000793 // The condition block is the implicit successor for the loop body as
794 // well as any code above the loop.
795 Succ = EntryConditionBlock;
796
797
Ted Kremenek73543912007-08-23 21:42:29 +0000798 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000799 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000800 {
801 assert (D->getBody());
802
803 // Save the current values for Block, Succ, and continue and break targets
804 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
805 save_continue(ContinueTargetBlock),
806 save_break(BreakTargetBlock);
807
808 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000809 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000810
811 // All breaks should go to the code following the loop.
812 BreakTargetBlock = LoopSuccessor;
813
814 // NULL out Block to force lazy instantiation of blocks for the body.
815 Block = NULL;
816
817 // Create the body. The returned block is the entry to the loop body.
818 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000819
Ted Kremenek390b9762007-08-30 18:39:40 +0000820 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000821 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000822 else if (Block)
823 FinishBlock(BodyBlock);
824
Ted Kremenek73543912007-08-23 21:42:29 +0000825 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000826 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000827 }
828
829 // Link up the condition block with the code that follows the loop.
830 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000831 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000832
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000833 // There can be no more statements in the body block(s)
834 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000835 // lazy creation of another block.
836 Block = NULL;
837
838 // Return the loop body, which is the dominating block for the loop.
839 return BodyBlock;
840}
841
842CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
843 // "continue" is a control-flow statement. Thus we stop processing the
844 // current block.
845 if (Block) FinishBlock(Block);
846
847 // Now create a new block that ends with the continue statement.
848 Block = createBlock(false);
849 Block->setTerminator(C);
850
851 // If there is no target for the continue, then we are looking at an
852 // incomplete AST. Handle this by not registering a successor.
853 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
854
855 return Block;
856}
857
858CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
859 // "break" is a control-flow statement. Thus we stop processing the
860 // current block.
861 if (Block) FinishBlock(Block);
862
863 // Now create a new block that ends with the continue statement.
864 Block = createBlock(false);
865 Block->setTerminator(B);
866
867 // If there is no target for the break, then we are looking at an
868 // incomplete AST. Handle this by not registering a successor.
869 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
870
871 return Block;
872}
873
874CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
875 // "switch" is a control-flow statement. Thus we stop processing the
876 // current block.
877 CFGBlock* SwitchSuccessor = NULL;
878
879 if (Block) {
880 FinishBlock(Block);
881 SwitchSuccessor = Block;
882 }
883 else SwitchSuccessor = Succ;
884
885 // Save the current "switch" context.
886 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000887 save_break(BreakTargetBlock),
888 save_default(DefaultCaseBlock);
889
890 // Set the "default" case to be the block after the switch statement.
891 // If the switch statement contains a "default:", this value will
892 // be overwritten with the block for that code.
893 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000894
Ted Kremenek73543912007-08-23 21:42:29 +0000895 // Create a new block that will contain the switch statement.
896 SwitchTerminatedBlock = createBlock(false);
897
Ted Kremenek73543912007-08-23 21:42:29 +0000898 // Now process the switch body. The code after the switch is the implicit
899 // successor.
900 Succ = SwitchSuccessor;
901 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000902
903 // When visiting the body, the case statements should automatically get
904 // linked up to the switch. We also don't keep a pointer to the body,
905 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000906 assert (S->getBody() && "switch must contain a non-NULL body");
907 Block = NULL;
908 CFGBlock *BodyBlock = Visit(S->getBody());
909 if (Block) FinishBlock(BodyBlock);
910
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000911 // If we have no "default:" case, the default transition is to the
912 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000913 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000914
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000915 // Add the terminator and condition in the switch block.
916 SwitchTerminatedBlock->setTerminator(S);
917 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000918 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000919
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000920 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000921}
922
Ted Kremenek97bc3422008-02-13 22:05:39 +0000923CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
924 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +0000925 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000926
927 if (S->getSubStmt()) Visit(S->getSubStmt());
928 CFGBlock* CaseBlock = Block;
929 if (!CaseBlock) CaseBlock = createBlock();
930
Ted Kremenek97bc3422008-02-13 22:05:39 +0000931 // Cases statements partition blocks, so this is the top of
932 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenekec055e12007-08-29 23:20:49 +0000933 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000934 FinishBlock(CaseBlock);
935
936 // Add this block to the list of successors for the block with the
937 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000938 assert (SwitchTerminatedBlock);
939 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000940
941 // We set Block to NULL to allow lazy creation of a new block (if necessary)
942 Block = NULL;
943
944 // This block is now the implicit successor of other blocks.
945 Succ = CaseBlock;
946
947 return CaseBlock;
948}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000949
Ted Kremenek97bc3422008-02-13 22:05:39 +0000950CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
951 if (S->getSubStmt()) Visit(S->getSubStmt());
952 DefaultCaseBlock = Block;
953 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
954
955 // Default statements partition blocks, so this is the top of
956 // the basic block we were processing (the "default:" is the label).
957 DefaultCaseBlock->setLabel(S);
958 FinishBlock(DefaultCaseBlock);
959
960 // Unlike case statements, we don't add the default block to the
961 // successors for the switch statement immediately. This is done
962 // when we finish processing the switch statement. This allows for
963 // the default case (including a fall-through to the code after the
964 // switch statement) to always be the last successor of a switch-terminated
965 // block.
966
967 // We set Block to NULL to allow lazy creation of a new block (if necessary)
968 Block = NULL;
969
970 // This block is now the implicit successor of other blocks.
971 Succ = DefaultCaseBlock;
972
973 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000974}
Ted Kremenek73543912007-08-23 21:42:29 +0000975
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000976CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
977 // Lazily create the indirect-goto dispatch block if there isn't one
978 // already.
979 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
980
981 if (!IBlock) {
982 IBlock = createBlock(false);
983 cfg->setIndirectGotoBlock(IBlock);
984 }
985
986 // IndirectGoto is a control-flow statement. Thus we stop processing the
987 // current block and create a new one.
988 if (Block) FinishBlock(Block);
989 Block = createBlock(false);
990 Block->setTerminator(I);
991 Block->addSuccessor(IBlock);
992 return addStmt(I->getTarget());
993}
994
Ted Kremenek73543912007-08-23 21:42:29 +0000995
Ted Kremenekd6e50602007-08-23 21:26:19 +0000996} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000997
998/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
999/// block has no successors or predecessors. If this is the first block
1000/// created in the CFG, it is automatically set to be the Entry and Exit
1001/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001002CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001003 bool first_block = begin() == end();
1004
1005 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001006 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001007
1008 // If this is the first block, set it as the Entry and Exit.
1009 if (first_block) Entry = Exit = &front();
1010
1011 // Return the block.
1012 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001013}
1014
Ted Kremenek4db5b452007-08-23 16:51:22 +00001015/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1016/// CFG is returned to the caller.
1017CFG* CFG::buildCFG(Stmt* Statement) {
1018 CFGBuilder Builder;
1019 return Builder.buildCFG(Statement);
1020}
1021
1022/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001023void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1024
Ted Kremenek3a819822007-10-01 19:33:33 +00001025//===----------------------------------------------------------------------===//
1026// CFG: Queries for BlkExprs.
1027//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001028
Ted Kremenek3a819822007-10-01 19:33:33 +00001029namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001030 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001031}
1032
Ted Kremenekc6fda602008-01-26 00:03:27 +00001033static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1034 if (!S)
1035 return;
1036
1037 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1038 if (!*I) continue;
1039
1040 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1041 if (B->isAssignmentOp()) Set.insert(B);
1042
1043 FindSubExprAssignments(*I, Set);
1044 }
1045}
1046
Ted Kremenek3a819822007-10-01 19:33:33 +00001047static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1048 BlkExprMapTy* M = new BlkExprMapTy();
1049
Ted Kremenekc6fda602008-01-26 00:03:27 +00001050 // Look for assignments that are used as subexpressions. These are the
1051 // only assignments that we want to register as a block-level expression.
1052 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1053
Ted Kremenek3a819822007-10-01 19:33:33 +00001054 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1055 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001056 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001057
Ted Kremenekc6fda602008-01-26 00:03:27 +00001058 // Iterate over the statements again on identify the Expr* and Stmt* at
1059 // the block-level that are block-level expressions.
1060 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1061 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1062 if (Expr* E = dyn_cast<Expr>(*BI)) {
1063
1064 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1065 // Assignment expressions that are not nested within another
1066 // expression are really "statements" whose value is never
1067 // used by another expression.
1068 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1069 continue;
1070 }
1071 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1072 // Special handling for statement expressions. The last statement
1073 // in the statement expression is also a block-level expr.
Ted Kremenekab6c5902008-01-17 20:48:37 +00001074 const CompoundStmt* C = S->getSubStmt();
1075 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001076 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001077 (*M)[C->body_back()] = x;
1078 }
1079 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001080
Ted Kremenekc6fda602008-01-26 00:03:27 +00001081 unsigned x = M->size();
1082 (*M)[E] = x;
1083 }
1084
Ted Kremenek3a819822007-10-01 19:33:33 +00001085 return M;
1086}
1087
Ted Kremenekab6c5902008-01-17 20:48:37 +00001088CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1089 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001090 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1091
1092 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001093 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001094
1095 if (I == M->end()) return CFG::BlkExprNumTy();
1096 else return CFG::BlkExprNumTy(I->second);
1097}
1098
1099unsigned CFG::getNumBlkExprs() {
1100 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1101 return M->size();
1102 else {
1103 // We assume callers interested in the number of BlkExprs will want
1104 // the map constructed if it doesn't already exist.
1105 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1106 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1107 }
1108}
1109
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001110typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1111
1112const std::pair<CFGBlock*,CFGBlock*>*
1113CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1114
1115 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1116 if (!p) p = new BlkEdgeSetTy();
1117
1118 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1119 const_cast<CFGBlock*>(B2))).first);
1120}
1121
Ted Kremenek3a819822007-10-01 19:33:33 +00001122CFG::~CFG() {
1123 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001124 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001125}
1126
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001127//===----------------------------------------------------------------------===//
1128// CFG pretty printing
1129//===----------------------------------------------------------------------===//
1130
Ted Kremenekd8313202007-08-22 18:22:34 +00001131namespace {
1132
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001133class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001134
Ted Kremenek08176a52007-08-31 21:30:12 +00001135 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1136 StmtMapTy StmtMap;
1137 signed CurrentBlock;
1138 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001139
Ted Kremenek73543912007-08-23 21:42:29 +00001140public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001141
Ted Kremenek08176a52007-08-31 21:30:12 +00001142 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1143 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1144 unsigned j = 1;
1145 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1146 BI != BEnd; ++BI, ++j )
1147 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1148 }
1149 }
1150
1151 virtual ~StmtPrinterHelper() {}
1152
1153 void setBlockID(signed i) { CurrentBlock = i; }
1154 void setStmtID(unsigned i) { CurrentStmt = i; }
1155
Ted Kremenek86afc042007-08-31 22:26:13 +00001156 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1157
1158 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +00001159
1160 if (I == StmtMap.end())
1161 return false;
1162
1163 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1164 && I->second.second == CurrentStmt)
1165 return false;
1166
Ted Kremenek86afc042007-08-31 22:26:13 +00001167 OS << "[B" << I->second.first << "." << I->second.second << "]";
1168 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001169 }
1170};
1171
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001172class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1173 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1174
Ted Kremenek08176a52007-08-31 21:30:12 +00001175 std::ostream& OS;
1176 StmtPrinterHelper* Helper;
1177public:
1178 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1179 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001180
1181 void VisitIfStmt(IfStmt* I) {
1182 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001183 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001184 }
1185
1186 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +00001187 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001188
1189 void VisitForStmt(ForStmt* F) {
1190 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001191 if (F->getInit()) OS << "...";
1192 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001193 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001194 OS << "; ";
1195 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001196 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001197 }
1198
1199 void VisitWhileStmt(WhileStmt* W) {
1200 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001201 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001202 }
1203
1204 void VisitDoStmt(DoStmt* D) {
1205 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001206 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001207 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001208
Ted Kremenek65cfa562007-08-27 21:27:44 +00001209 void VisitSwitchStmt(SwitchStmt* S) {
1210 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001211 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001212 }
1213
Ted Kremenek621e1592007-08-31 21:49:40 +00001214 void VisitConditionalOperator(ConditionalOperator* C) {
1215 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001216 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001217 }
1218
Ted Kremenek2025cc92007-08-31 22:29:13 +00001219 void VisitChooseExpr(ChooseExpr* C) {
1220 OS << "__builtin_choose_expr( ";
1221 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001222 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001223 }
1224
Ted Kremenek86afc042007-08-31 22:26:13 +00001225 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1226 OS << "goto *";
1227 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001228 }
1229
Ted Kremenek621e1592007-08-31 21:49:40 +00001230 void VisitBinaryOperator(BinaryOperator* B) {
1231 if (!B->isLogicalOp()) {
1232 VisitExpr(B);
1233 return;
1234 }
1235
1236 B->getLHS()->printPretty(OS,Helper);
1237
1238 switch (B->getOpcode()) {
1239 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001240 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001241 return;
1242 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001243 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001244 return;
1245 default:
1246 assert(false && "Invalid logical operator.");
1247 }
1248 }
1249
Ted Kremenekcfaae762007-08-27 21:54:41 +00001250 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001251 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001252 }
Ted Kremenek73543912007-08-23 21:42:29 +00001253};
Ted Kremenek08176a52007-08-31 21:30:12 +00001254
1255
Ted Kremenek86afc042007-08-31 22:26:13 +00001256void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1257 if (Helper) {
1258 // special printing for statement-expressions.
1259 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1260 CompoundStmt* Sub = SE->getSubStmt();
1261
1262 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001263 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001264 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001265 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001266 return;
1267 }
1268 }
1269
1270 // special printing for comma expressions.
1271 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1272 if (B->getOpcode() == BinaryOperator::Comma) {
1273 OS << "... , ";
1274 Helper->handledStmt(B->getRHS(),OS);
1275 OS << '\n';
1276 return;
1277 }
1278 }
1279 }
1280
1281 S->printPretty(OS, Helper);
1282
1283 // Expressions need a newline.
1284 if (isa<Expr>(S)) OS << '\n';
1285}
1286
Ted Kremenek08176a52007-08-31 21:30:12 +00001287void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1288 StmtPrinterHelper* Helper, bool print_edges) {
1289
1290 if (Helper) Helper->setBlockID(B.getBlockID());
1291
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001292 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001293 OS << "\n [ B" << B.getBlockID();
1294
1295 if (&B == &cfg->getEntry())
1296 OS << " (ENTRY) ]\n";
1297 else if (&B == &cfg->getExit())
1298 OS << " (EXIT) ]\n";
1299 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001300 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001301 else
1302 OS << " ]\n";
1303
Ted Kremenekec055e12007-08-29 23:20:49 +00001304 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001305 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1306
1307 if (print_edges)
1308 OS << " ";
1309
Ted Kremenekec055e12007-08-29 23:20:49 +00001310 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1311 OS << L->getName();
1312 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1313 OS << "case ";
1314 C->getLHS()->printPretty(OS);
1315 if (C->getRHS()) {
1316 OS << " ... ";
1317 C->getRHS()->printPretty(OS);
1318 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001319 }
Chris Lattner1501e122007-09-16 19:11:53 +00001320 else if (isa<DefaultStmt>(S))
Ted Kremenekec055e12007-08-29 23:20:49 +00001321 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001322 else
1323 assert(false && "Invalid label statement in CFGBlock.");
1324
Ted Kremenekec055e12007-08-29 23:20:49 +00001325 OS << ":\n";
1326 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001327
Ted Kremenek97f75312007-08-21 21:42:03 +00001328 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001329 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001330
1331 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1332 I != E ; ++I, ++j ) {
1333
Ted Kremenekec055e12007-08-29 23:20:49 +00001334 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001335 if (print_edges)
1336 OS << " ";
1337
1338 OS << std::setw(3) << j << ": ";
1339
1340 if (Helper)
1341 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001342
1343 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001344 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001345
Ted Kremenekec055e12007-08-29 23:20:49 +00001346 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001347 if (B.getTerminator()) {
1348 if (print_edges)
1349 OS << " ";
1350
Ted Kremenekec055e12007-08-29 23:20:49 +00001351 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001352
1353 if (Helper) Helper->setBlockID(-1);
1354
1355 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1356 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001357 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001358 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001359
Ted Kremenekec055e12007-08-29 23:20:49 +00001360 if (print_edges) {
1361 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001362 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001363 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001364
Ted Kremenek08176a52007-08-31 21:30:12 +00001365 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1366 I != E; ++I, ++i) {
1367
1368 if (i == 8 || (i-8) == 0)
1369 OS << "\n ";
1370
Ted Kremenekec055e12007-08-29 23:20:49 +00001371 OS << " B" << (*I)->getBlockID();
1372 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001373
1374 OS << '\n';
1375
1376 // Print the successors of this block.
1377 OS << " Successors (" << B.succ_size() << "):";
1378 i = 0;
1379
1380 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1381 I != E; ++I, ++i) {
1382
1383 if (i == 8 || (i-8) % 10 == 0)
1384 OS << "\n ";
1385
1386 OS << " B" << (*I)->getBlockID();
1387 }
1388
Ted Kremenekec055e12007-08-29 23:20:49 +00001389 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001390 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001391}
1392
1393} // end anonymous namespace
1394
1395/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001396void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001397
1398/// print - A simple pretty printer of a CFG that outputs to an ostream.
1399void CFG::print(std::ostream& OS) const {
1400
1401 StmtPrinterHelper Helper(this);
1402
1403 // Print the entry block.
1404 print_block(OS, this, getEntry(), &Helper, true);
1405
1406 // Iterate through the CFGBlocks and print them one by one.
1407 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1408 // Skip the entry block, because we already printed it.
1409 if (&(*I) == &getEntry() || &(*I) == &getExit())
1410 continue;
1411
1412 print_block(OS, this, *I, &Helper, true);
1413 }
1414
1415 // Print the exit block.
1416 print_block(OS, this, getExit(), &Helper, true);
1417}
1418
1419/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001420void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001421
1422/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1423/// Generally this will only be called from CFG::print.
1424void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1425 StmtPrinterHelper Helper(cfg);
1426 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001427}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001428
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001429/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1430void CFGBlock::printTerminator(std::ostream& OS) const {
1431 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1432 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1433}
1434
1435
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001436//===----------------------------------------------------------------------===//
1437// CFG Graphviz Visualization
1438//===----------------------------------------------------------------------===//
1439
Ted Kremenek08176a52007-08-31 21:30:12 +00001440
1441#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001442static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001443#endif
1444
1445void CFG::viewCFG() const {
1446#ifndef NDEBUG
1447 StmtPrinterHelper H(this);
1448 GraphHelper = &H;
1449 llvm::ViewGraph(this,"CFG");
1450 GraphHelper = NULL;
1451#else
1452 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001453 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001454#endif
1455}
1456
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001457namespace llvm {
1458template<>
1459struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1460 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1461
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001462#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001463 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001464 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001465 std::string OutStr = Out.str();
1466
1467 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1468
1469 // Process string output to make it nicer...
1470 for (unsigned i = 0; i != OutStr.length(); ++i)
1471 if (OutStr[i] == '\n') { // Left justify
1472 OutStr[i] = '\\';
1473 OutStr.insert(OutStr.begin()+i+1, 'l');
1474 }
1475
1476 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001477#else
1478 return "";
1479#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001480 }
1481};
1482} // end namespace llvm