blob: e2aba6b3ff34fe3b6c5578230cb2eb97d16d8b27 [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>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000028#include <iostream>
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 Kremenek4102af92008-03-13 03:04:22 +0000116 // FIXME: Add support for ObjC-specific control-flow structures.
117
118 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
119 badCFG = true;
120 return Block;
121 }
122
123 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
124 badCFG = true;
125 return Block;
126 }
127
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000128private:
129 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000130 CFGBlock* addStmt(Stmt* S);
131 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
132 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000133 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000134 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000135 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000136
Ted Kremenek4102af92008-03-13 03:04:22 +0000137 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000138};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000139
140/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
141/// represent an arbitrary statement. Examples include a single expression
142/// or a function body (compound statement). The ownership of the returned
143/// CFG is transferred to the caller. If CFG construction fails, this method
144/// returns NULL.
145CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000146 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000147 if (!Statement) return NULL;
148
Ted Kremenek4102af92008-03-13 03:04:22 +0000149 badCFG = false;
150
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000151 // Create an empty block that will serve as the exit block for the CFG.
152 // Since this is the first block added to the CFG, it will be implicitly
153 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000154 Succ = createBlock();
155 assert (Succ == &cfg->getExit());
156 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000157
158 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000159 CFGBlock* B = Visit(Statement);
160 if (!B) B = Succ;
161
162 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000163 // Finalize the last constructed block. This usually involves
164 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000165 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000166
167 // Backpatch the gotos whose label -> block mappings we didn't know
168 // when we encountered them.
169 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
170 E = BackpatchBlocks.end(); I != E; ++I ) {
171
172 CFGBlock* B = *I;
173 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
174 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
175
176 // If there is no target for the goto, then we are looking at an
177 // incomplete AST. Handle this by not registering a successor.
178 if (LI == LabelMap.end()) continue;
179
180 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000181 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000182
Ted Kremenek19bb3562007-08-28 19:26:49 +0000183 // Add successors to the Indirect Goto Dispatch block (if we have one).
184 if (CFGBlock* B = cfg->getIndirectGotoBlock())
185 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
186 E = AddressTakenLabels.end(); I != E; ++I ) {
187
188 // Lookup the target block.
189 LabelMapTy::iterator LI = LabelMap.find(*I);
190
191 // If there is no target block that contains label, then we are looking
192 // at an incomplete AST. Handle this by not registering a successor.
193 if (LI == LabelMap.end()) continue;
194
195 B->addSuccessor(LI->second);
196 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000197
Ted Kremenek94b33162007-09-17 16:18:02 +0000198 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000199 }
200
201 // Create an empty entry block that has no predecessors.
202 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000203
Ted Kremenek4102af92008-03-13 03:04:22 +0000204 if (badCFG) {
205 delete cfg;
206 cfg = NULL;
207 return NULL;
208 }
209
Ted Kremenek322f58d2007-09-26 21:23:31 +0000210 // NULL out cfg so that repeated calls to the builder will fail and that
211 // the ownership of the constructed CFG is passed to the caller.
212 CFG* t = cfg;
213 cfg = NULL;
214 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000215}
216
217/// createBlock - Used to lazily create blocks that are connected
218/// to the current (global) succcessor.
219CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000220 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000221 if (add_successor && Succ) B->addSuccessor(Succ);
222 return B;
223}
224
225/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000226/// we must reverse the statements because they have been inserted
227/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000228void CFGBuilder::FinishBlock(CFGBlock* B) {
229 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000230 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000231}
232
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000233/// addStmt - Used to add statements/expressions to the current CFGBlock
234/// "Block". This method calls WalkAST on the passed statement to see if it
235/// contains any short-circuit expressions. If so, it recursively creates
236/// the necessary blocks for such expressions. It returns the "topmost" block
237/// of the created blocks, or the original value of "Block" when this method
238/// was called if no additional blocks are created.
239CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000240 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000241 return WalkAST(S,true);
242}
243
244/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000245/// add extra blocks for ternary operators, &&, and ||. We also
246/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000247CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
248 switch (S->getStmtClass()) {
249 case Stmt::ConditionalOperatorClass: {
250 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000251
252 // Create the confluence block that will "merge" the results
253 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000254 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
255 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000256 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000257
258 // Create a block for the LHS expression if there is an LHS expression.
259 // A GCC extension allows LHS to be NULL, causing the condition to
260 // be the value that is returned instead.
261 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000262 Succ = ConfluenceBlock;
263 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000264 CFGBlock* LHSBlock = NULL;
265 if (C->getLHS()) {
266 LHSBlock = Visit(C->getLHS());
267 FinishBlock(LHSBlock);
268 Block = NULL;
269 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000270
Ted Kremenekecc04c92007-11-26 18:20:26 +0000271 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000272 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000273 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000274 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000275
Ted Kremenekecc04c92007-11-26 18:20:26 +0000276 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000277 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000278
279 if (LHSBlock)
280 Block->addSuccessor(LHSBlock);
281 else {
282 // If we have no LHS expression, add the ConfluenceBlock as a direct
283 // successor for the block containing the condition. Moreover,
284 // we need to reverse the order of the predecessors in the
285 // ConfluenceBlock because the RHSBlock will have been added to
286 // the succcessors already, and we want the first predecessor to the
287 // the block containing the expression for the case when the ternary
288 // expression evaluates to true.
289 Block->addSuccessor(ConfluenceBlock);
290 assert (ConfluenceBlock->pred_size() == 2);
291 std::reverse(ConfluenceBlock->pred_begin(),
292 ConfluenceBlock->pred_end());
293 }
294
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000295 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000296
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000297 Block->setTerminator(C);
298 return addStmt(C->getCond());
299 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000300
301 case Stmt::ChooseExprClass: {
302 ChooseExpr* C = cast<ChooseExpr>(S);
303
304 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
305 ConfluenceBlock->appendStmt(C);
306 FinishBlock(ConfluenceBlock);
307
308 Succ = ConfluenceBlock;
309 Block = NULL;
310 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000311 FinishBlock(LHSBlock);
312
Ted Kremenek49a436d2007-08-31 17:03:41 +0000313 Succ = ConfluenceBlock;
314 Block = NULL;
315 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000316 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000317
318 Block = createBlock(false);
319 Block->addSuccessor(LHSBlock);
320 Block->addSuccessor(RHSBlock);
321 Block->setTerminator(C);
322 return addStmt(C->getCond());
323 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000324
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000325 case Stmt::DeclStmtClass: {
326 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
327 Block->appendStmt(S);
328
329 StmtIterator I(D);
330 return WalkAST_VisitDeclSubExprs(I);
331 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000332
Ted Kremenek19bb3562007-08-28 19:26:49 +0000333 case Stmt::AddrLabelExprClass: {
334 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
335 AddressTakenLabels.insert(A->getLabel());
336
337 if (AlwaysAddStmt) Block->appendStmt(S);
338 return Block;
339 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000340
Ted Kremenek15c27a82007-08-28 18:30:10 +0000341 case Stmt::StmtExprClass:
342 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000343
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000344 case Stmt::UnaryOperatorClass: {
345 UnaryOperator* U = cast<UnaryOperator>(S);
346
347 // sizeof(expressions). For such expressions,
348 // the subexpression is not really evaluated, so
349 // we don't care about control-flow within the sizeof.
350 if (U->getOpcode() == UnaryOperator::SizeOf) {
351 Block->appendStmt(S);
352 return Block;
353 }
354
355 break;
356 }
357
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000358 case Stmt::BinaryOperatorClass: {
359 BinaryOperator* B = cast<BinaryOperator>(S);
360
361 if (B->isLogicalOp()) { // && or ||
362 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
363 ConfluenceBlock->appendStmt(B);
364 FinishBlock(ConfluenceBlock);
365
366 // create the block evaluating the LHS
367 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000368 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000369
370 // create the block evaluating the RHS
371 Succ = ConfluenceBlock;
372 Block = NULL;
373 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000374
375 // Now link the LHSBlock with RHSBlock.
376 if (B->getOpcode() == BinaryOperator::LOr) {
377 LHSBlock->addSuccessor(ConfluenceBlock);
378 LHSBlock->addSuccessor(RHSBlock);
379 }
380 else {
381 assert (B->getOpcode() == BinaryOperator::LAnd);
382 LHSBlock->addSuccessor(RHSBlock);
383 LHSBlock->addSuccessor(ConfluenceBlock);
384 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000385
386 // Generate the blocks for evaluating the LHS.
387 Block = LHSBlock;
388 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000389 }
390 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
391 Block->appendStmt(B);
392 addStmt(B->getRHS());
393 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000394 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000395
396 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000397 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000398
399 case Stmt::ParenExprClass:
400 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000401
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000402 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000403 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000404 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000405
406 if (AlwaysAddStmt) Block->appendStmt(S);
407 return WalkAST_VisitChildren(S);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000408}
409
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000410/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
411/// DeclStmts. Because the initialization code (and sometimes the
412/// the type declarations) for DeclStmts can contain arbitrary expressions,
413/// we must linearize declarations to handle arbitrary control-flow induced by
414/// those expressions.
415CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000416 if (I == StmtIterator())
417 return Block;
418
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000419 Stmt* S = *I;
420 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000421 WalkAST_VisitDeclSubExprs(I);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000422
423 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000424
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000425 switch (S->getStmtClass()) {
426 case Stmt::IntegerLiteralClass:
427 case Stmt::CharacterLiteralClass:
428 case Stmt::StringLiteralClass:
429 break;
430
431 // All other cases.
432
433 default:
434 Block = addStmt(S);
435 }
436
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000437 return Block;
438}
439
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000440/// WalkAST_VisitChildren - Utility method to call WalkAST on the
441/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000442CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000443 CFGBlock* B = Block;
444 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
445 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000446 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000447
448 return B;
449}
450
Ted Kremenek15c27a82007-08-28 18:30:10 +0000451/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
452/// expressions (a GCC extension).
453CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
454 Block->appendStmt(S);
455 return VisitCompoundStmt(S->getSubStmt());
456}
457
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000458/// VisitStmt - Handle statements with no branching control flow.
459CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
460 // We cannot assume that we are in the middle of a basic block, since
461 // the CFG might only be constructed for this single statement. If
462 // we have no current basic block, just create one lazily.
463 if (!Block) Block = createBlock();
464
465 // Simply add the statement to the current block. We actually
466 // insert statements in reverse order; this order is reversed later
467 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000468 addStmt(Statement);
469
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000470 return Block;
471}
472
473CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
474 return Block;
475}
476
477CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000478
Ted Kremenekd34066c2008-02-26 00:22:58 +0000479 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
480 I != E; ++I ) {
481 Visit(*I);
482 }
483
484 return Block;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000485}
486
487CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
488 // We may see an if statement in the middle of a basic block, or
489 // it may be the first statement we are processing. In either case,
490 // we create a new basic block. First, we create the blocks for
491 // the then...else statements, and then we create the block containing
492 // the if statement. If we were in the middle of a block, we
493 // stop processing that block and reverse its statements. That block
494 // is then the implicit successor for the "then" and "else" clauses.
495
496 // The block we were proccessing is now finished. Make it the
497 // successor block.
498 if (Block) {
499 Succ = Block;
500 FinishBlock(Block);
501 }
502
503 // Process the false branch. NULL out Block so that the recursive
504 // call to Visit will create a new basic block.
505 // Null out Block so that all successor
506 CFGBlock* ElseBlock = Succ;
507
508 if (Stmt* Else = I->getElse()) {
509 SaveAndRestore<CFGBlock*> sv(Succ);
510
511 // NULL out Block so that the recursive call to Visit will
512 // create a new basic block.
513 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000514 ElseBlock = Visit(Else);
515
516 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
517 ElseBlock = sv.get();
518 else if (Block)
519 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000520 }
521
522 // Process the true branch. NULL out Block so that the recursive
523 // call to Visit will create a new basic block.
524 // Null out Block so that all successor
525 CFGBlock* ThenBlock;
526 {
527 Stmt* Then = I->getThen();
528 assert (Then);
529 SaveAndRestore<CFGBlock*> sv(Succ);
530 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000531 ThenBlock = Visit(Then);
532
533 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
534 ThenBlock = sv.get();
535 else if (Block)
536 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000537 }
538
539 // Now create a new block containing the if statement.
540 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000541
542 // Set the terminator of the new block to the If statement.
543 Block->setTerminator(I);
544
545 // Now add the successors.
546 Block->addSuccessor(ThenBlock);
547 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000548
549 // Add the condition as the last statement in the new block. This
550 // may create new blocks as the condition may contain control-flow. Any
551 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000552 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000553}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000554
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000555
556CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
557 // If we were in the middle of a block we stop processing that block
558 // and reverse its statements.
559 //
560 // NOTE: If a "return" appears in the middle of a block, this means
561 // that the code afterwards is DEAD (unreachable). We still
562 // keep a basic block for that code; a simple "mark-and-sweep"
563 // from the entry block will be able to report such dead
564 // blocks.
565 if (Block) FinishBlock(Block);
566
567 // Create the new block.
568 Block = createBlock(false);
569
570 // The Exit block is the only successor.
571 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000572
573 // Add the return statement to the block. This may create new blocks
574 // if R contains control-flow (short-circuit operations).
575 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000576}
577
578CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
579 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000580 Visit(L->getSubStmt());
581 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000582
583 if (!LabelBlock) // This can happen when the body is empty, i.e.
584 LabelBlock=createBlock(); // scopes that only contains NullStmts.
585
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000586 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
587 LabelMap[ L ] = LabelBlock;
588
589 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000590 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000591 // label (and we have already processed the substatement) there is no
592 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000593 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000594 FinishBlock(LabelBlock);
595
596 // We set Block to NULL to allow lazy creation of a new block
597 // (if necessary);
598 Block = NULL;
599
600 // This block is now the implicit successor of other blocks.
601 Succ = LabelBlock;
602
603 return LabelBlock;
604}
605
606CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
607 // Goto is a control-flow statement. Thus we stop processing the
608 // current block and create a new one.
609 if (Block) FinishBlock(Block);
610 Block = createBlock(false);
611 Block->setTerminator(G);
612
613 // If we already know the mapping to the label block add the
614 // successor now.
615 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
616
617 if (I == LabelMap.end())
618 // We will need to backpatch this block later.
619 BackpatchBlocks.push_back(Block);
620 else
621 Block->addSuccessor(I->second);
622
623 return Block;
624}
625
626CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
627 // "for" is a control-flow statement. Thus we stop processing the
628 // current block.
629
630 CFGBlock* LoopSuccessor = NULL;
631
632 if (Block) {
633 FinishBlock(Block);
634 LoopSuccessor = Block;
635 }
636 else LoopSuccessor = Succ;
637
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000638 // Because of short-circuit evaluation, the condition of the loop
639 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
640 // blocks that evaluate the condition.
641 CFGBlock* ExitConditionBlock = createBlock(false);
642 CFGBlock* EntryConditionBlock = ExitConditionBlock;
643
644 // Set the terminator for the "exit" condition block.
645 ExitConditionBlock->setTerminator(F);
646
647 // Now add the actual condition to the condition block. Because the
648 // condition itself may contain control-flow, new blocks may be created.
649 if (Stmt* C = F->getCond()) {
650 Block = ExitConditionBlock;
651 EntryConditionBlock = addStmt(C);
652 if (Block) FinishBlock(EntryConditionBlock);
653 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000654
655 // The condition block is the implicit successor for the loop body as
656 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000657 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000658
659 // Now create the loop body.
660 {
661 assert (F->getBody());
662
663 // Save the current values for Block, Succ, and continue and break targets
664 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
665 save_continue(ContinueTargetBlock),
666 save_break(BreakTargetBlock);
667
668 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000669 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000670
671 // All breaks should go to the code following the loop.
672 BreakTargetBlock = LoopSuccessor;
673
Ted Kremenekaf603f72007-08-30 18:39:40 +0000674 // Create a new block to contain the (bottom) of the loop body.
675 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000676
677 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000678 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000679
680 // Now populate the body block, and in the process create new blocks
681 // as we walk the body of the loop.
682 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000683
684 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000685 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000686 else if (Block)
687 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000688
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000689 // This new body block is a successor to our "exit" condition block.
690 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000691 }
692
693 // Link up the condition block with the code that follows the loop.
694 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000695 ExitConditionBlock->addSuccessor(LoopSuccessor);
696
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000697 // If the loop contains initialization, create a new block for those
698 // statements. This block can also contain statements that precede
699 // the loop.
700 if (Stmt* I = F->getInit()) {
701 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000702 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000703 }
704 else {
705 // There is no loop initialization. We are thus basically a while
706 // loop. NULL out Block to force lazy block construction.
707 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000708 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000709 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000710 }
711}
712
713CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
714 // "while" is a control-flow statement. Thus we stop processing the
715 // current block.
716
717 CFGBlock* LoopSuccessor = NULL;
718
719 if (Block) {
720 FinishBlock(Block);
721 LoopSuccessor = Block;
722 }
723 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000724
725 // Because of short-circuit evaluation, the condition of the loop
726 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
727 // blocks that evaluate the condition.
728 CFGBlock* ExitConditionBlock = createBlock(false);
729 CFGBlock* EntryConditionBlock = ExitConditionBlock;
730
731 // Set the terminator for the "exit" condition block.
732 ExitConditionBlock->setTerminator(W);
733
734 // Now add the actual condition to the condition block. Because the
735 // condition itself may contain control-flow, new blocks may be created.
736 // Thus we update "Succ" after adding the condition.
737 if (Stmt* C = W->getCond()) {
738 Block = ExitConditionBlock;
739 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000740 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000741 if (Block) FinishBlock(EntryConditionBlock);
742 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000743
744 // The condition block is the implicit successor for the loop body as
745 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000746 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000747
748 // Process the loop body.
749 {
750 assert (W->getBody());
751
752 // Save the current values for Block, Succ, and continue and break targets
753 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
754 save_continue(ContinueTargetBlock),
755 save_break(BreakTargetBlock);
756
757 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000758 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000759
760 // All breaks should go to the code following the loop.
761 BreakTargetBlock = LoopSuccessor;
762
763 // NULL out Block to force lazy instantiation of blocks for the body.
764 Block = NULL;
765
766 // Create the body. The returned block is the entry to the loop body.
767 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000768
769 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000770 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000771 else if (Block)
772 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000773
774 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000775 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000776 }
777
778 // Link up the condition block with the code that follows the loop.
779 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000780 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000781
782 // There can be no more statements in the condition block
783 // since we loop back to this block. NULL out Block to force
784 // lazy creation of another block.
785 Block = NULL;
786
787 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000788 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000789 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000790}
791
792CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
793 // "do...while" is a control-flow statement. Thus we stop processing the
794 // current block.
795
796 CFGBlock* LoopSuccessor = NULL;
797
798 if (Block) {
799 FinishBlock(Block);
800 LoopSuccessor = Block;
801 }
802 else LoopSuccessor = Succ;
803
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000804 // Because of short-circuit evaluation, the condition of the loop
805 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
806 // blocks that evaluate the condition.
807 CFGBlock* ExitConditionBlock = createBlock(false);
808 CFGBlock* EntryConditionBlock = ExitConditionBlock;
809
810 // Set the terminator for the "exit" condition block.
811 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000812
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000813 // Now add the actual condition to the condition block. Because the
814 // condition itself may contain control-flow, new blocks may be created.
815 if (Stmt* C = D->getCond()) {
816 Block = ExitConditionBlock;
817 EntryConditionBlock = addStmt(C);
818 if (Block) FinishBlock(EntryConditionBlock);
819 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000820
Ted Kremenek54827132008-02-27 07:20:00 +0000821 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000822 Succ = EntryConditionBlock;
823
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000824 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000825 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000826 {
827 assert (D->getBody());
828
829 // Save the current values for Block, Succ, and continue and break targets
830 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
831 save_continue(ContinueTargetBlock),
832 save_break(BreakTargetBlock);
833
834 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000835 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000836
837 // All breaks should go to the code following the loop.
838 BreakTargetBlock = LoopSuccessor;
839
840 // NULL out Block to force lazy instantiation of blocks for the body.
841 Block = NULL;
842
843 // Create the body. The returned block is the entry to the loop body.
844 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000845
Ted Kremenekaf603f72007-08-30 18:39:40 +0000846 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000847 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000848 else if (Block)
849 FinishBlock(BodyBlock);
850
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000851 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000852 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000853 }
854
855 // Link up the condition block with the code that follows the loop.
856 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000857 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000858
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000859 // There can be no more statements in the body block(s)
860 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000861 // lazy creation of another block.
862 Block = NULL;
863
864 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000865 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000866 return BodyBlock;
867}
868
869CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
870 // "continue" is a control-flow statement. Thus we stop processing the
871 // current block.
872 if (Block) FinishBlock(Block);
873
874 // Now create a new block that ends with the continue statement.
875 Block = createBlock(false);
876 Block->setTerminator(C);
877
878 // If there is no target for the continue, then we are looking at an
879 // incomplete AST. Handle this by not registering a successor.
880 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
881
882 return Block;
883}
884
885CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
886 // "break" is a control-flow statement. Thus we stop processing the
887 // current block.
888 if (Block) FinishBlock(Block);
889
890 // Now create a new block that ends with the continue statement.
891 Block = createBlock(false);
892 Block->setTerminator(B);
893
894 // If there is no target for the break, then we are looking at an
895 // incomplete AST. Handle this by not registering a successor.
896 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
897
898 return Block;
899}
900
901CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
902 // "switch" is a control-flow statement. Thus we stop processing the
903 // current block.
904 CFGBlock* SwitchSuccessor = NULL;
905
906 if (Block) {
907 FinishBlock(Block);
908 SwitchSuccessor = Block;
909 }
910 else SwitchSuccessor = Succ;
911
912 // Save the current "switch" context.
913 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000914 save_break(BreakTargetBlock),
915 save_default(DefaultCaseBlock);
916
917 // Set the "default" case to be the block after the switch statement.
918 // If the switch statement contains a "default:", this value will
919 // be overwritten with the block for that code.
920 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000921
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000922 // Create a new block that will contain the switch statement.
923 SwitchTerminatedBlock = createBlock(false);
924
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000925 // Now process the switch body. The code after the switch is the implicit
926 // successor.
927 Succ = SwitchSuccessor;
928 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000929
930 // When visiting the body, the case statements should automatically get
931 // linked up to the switch. We also don't keep a pointer to the body,
932 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000933 assert (S->getBody() && "switch must contain a non-NULL body");
934 Block = NULL;
935 CFGBlock *BodyBlock = Visit(S->getBody());
936 if (Block) FinishBlock(BodyBlock);
937
Ted Kremenek295222c2008-02-13 21:46:34 +0000938 // If we have no "default:" case, the default transition is to the
939 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000940 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000941
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000942 // Add the terminator and condition in the switch block.
943 SwitchTerminatedBlock->setTerminator(S);
944 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000945 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000946
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000947 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000948}
949
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000950CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
951 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000952 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000953
954 if (S->getSubStmt()) Visit(S->getSubStmt());
955 CFGBlock* CaseBlock = Block;
956 if (!CaseBlock) CaseBlock = createBlock();
957
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000958 // Cases statements partition blocks, so this is the top of
959 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek9cffe732007-08-29 23:20:49 +0000960 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000961 FinishBlock(CaseBlock);
962
963 // Add this block to the list of successors for the block with the
964 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000965 assert (SwitchTerminatedBlock);
966 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000967
968 // We set Block to NULL to allow lazy creation of a new block (if necessary)
969 Block = NULL;
970
971 // This block is now the implicit successor of other blocks.
972 Succ = CaseBlock;
973
Ted Kremenek2677ea82008-03-15 07:45:02 +0000974 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000975}
Ted Kremenek295222c2008-02-13 21:46:34 +0000976
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000977CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
978 if (S->getSubStmt()) Visit(S->getSubStmt());
979 DefaultCaseBlock = Block;
980 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
981
982 // Default statements partition blocks, so this is the top of
983 // the basic block we were processing (the "default:" is the label).
984 DefaultCaseBlock->setLabel(S);
985 FinishBlock(DefaultCaseBlock);
986
987 // Unlike case statements, we don't add the default block to the
988 // successors for the switch statement immediately. This is done
989 // when we finish processing the switch statement. This allows for
990 // the default case (including a fall-through to the code after the
991 // switch statement) to always be the last successor of a switch-terminated
992 // block.
993
994 // We set Block to NULL to allow lazy creation of a new block (if necessary)
995 Block = NULL;
996
997 // This block is now the implicit successor of other blocks.
998 Succ = DefaultCaseBlock;
999
1000 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001001}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001002
Ted Kremenek19bb3562007-08-28 19:26:49 +00001003CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1004 // Lazily create the indirect-goto dispatch block if there isn't one
1005 // already.
1006 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1007
1008 if (!IBlock) {
1009 IBlock = createBlock(false);
1010 cfg->setIndirectGotoBlock(IBlock);
1011 }
1012
1013 // IndirectGoto is a control-flow statement. Thus we stop processing the
1014 // current block and create a new one.
1015 if (Block) FinishBlock(Block);
1016 Block = createBlock(false);
1017 Block->setTerminator(I);
1018 Block->addSuccessor(IBlock);
1019 return addStmt(I->getTarget());
1020}
1021
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001022
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001023} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001024
1025/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1026/// block has no successors or predecessors. If this is the first block
1027/// created in the CFG, it is automatically set to be the Entry and Exit
1028/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001029CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001030 bool first_block = begin() == end();
1031
1032 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001033 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001034
1035 // If this is the first block, set it as the Entry and Exit.
1036 if (first_block) Entry = Exit = &front();
1037
1038 // Return the block.
1039 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001040}
1041
Ted Kremenek026473c2007-08-23 16:51:22 +00001042/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1043/// CFG is returned to the caller.
1044CFG* CFG::buildCFG(Stmt* Statement) {
1045 CFGBuilder Builder;
1046 return Builder.buildCFG(Statement);
1047}
1048
1049/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001050void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1051
Ted Kremenek63f58872007-10-01 19:33:33 +00001052//===----------------------------------------------------------------------===//
1053// CFG: Queries for BlkExprs.
1054//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001055
Ted Kremenek63f58872007-10-01 19:33:33 +00001056namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001057 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001058}
1059
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001060static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1061 if (!S)
1062 return;
1063
1064 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1065 if (!*I) continue;
1066
1067 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1068 if (B->isAssignmentOp()) Set.insert(B);
1069
1070 FindSubExprAssignments(*I, Set);
1071 }
1072}
1073
Ted Kremenek63f58872007-10-01 19:33:33 +00001074static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1075 BlkExprMapTy* M = new BlkExprMapTy();
1076
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001077 // Look for assignments that are used as subexpressions. These are the
1078 // only assignments that we want to register as a block-level expression.
1079 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1080
Ted Kremenek63f58872007-10-01 19:33:33 +00001081 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1082 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001083 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001084
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001085 // Iterate over the statements again on identify the Expr* and Stmt* at
1086 // the block-level that are block-level expressions.
1087 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1088 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1089 if (Expr* E = dyn_cast<Expr>(*BI)) {
1090
1091 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1092 // Assignment expressions that are not nested within another
1093 // expression are really "statements" whose value is never
1094 // used by another expression.
1095 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1096 continue;
1097 }
1098 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1099 // Special handling for statement expressions. The last statement
1100 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001101 const CompoundStmt* C = S->getSubStmt();
1102 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001103 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001104 (*M)[C->body_back()] = x;
1105 }
1106 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001107
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001108 unsigned x = M->size();
1109 (*M)[E] = x;
1110 }
1111
Ted Kremenek63f58872007-10-01 19:33:33 +00001112 return M;
1113}
1114
Ted Kremenek86946742008-01-17 20:48:37 +00001115CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1116 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001117 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1118
1119 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001120 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001121
1122 if (I == M->end()) return CFG::BlkExprNumTy();
1123 else return CFG::BlkExprNumTy(I->second);
1124}
1125
1126unsigned CFG::getNumBlkExprs() {
1127 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1128 return M->size();
1129 else {
1130 // We assume callers interested in the number of BlkExprs will want
1131 // the map constructed if it doesn't already exist.
1132 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1133 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1134 }
1135}
1136
Ted Kremenek83c01da2008-01-11 00:40:29 +00001137typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1138
1139const std::pair<CFGBlock*,CFGBlock*>*
1140CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1141
1142 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1143 if (!p) p = new BlkEdgeSetTy();
1144
1145 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1146 const_cast<CFGBlock*>(B2))).first);
1147}
1148
Ted Kremenek63f58872007-10-01 19:33:33 +00001149CFG::~CFG() {
1150 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001151 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001152}
1153
Ted Kremenek7dba8602007-08-29 21:56:09 +00001154//===----------------------------------------------------------------------===//
1155// CFG pretty printing
1156//===----------------------------------------------------------------------===//
1157
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001158namespace {
1159
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001160class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001161
Ted Kremenek42a509f2007-08-31 21:30:12 +00001162 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1163 StmtMapTy StmtMap;
1164 signed CurrentBlock;
1165 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001166
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001167public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001168
Ted Kremenek42a509f2007-08-31 21:30:12 +00001169 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1170 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1171 unsigned j = 1;
1172 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1173 BI != BEnd; ++BI, ++j )
1174 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1175 }
1176 }
1177
1178 virtual ~StmtPrinterHelper() {}
1179
1180 void setBlockID(signed i) { CurrentBlock = i; }
1181 void setStmtID(unsigned i) { CurrentStmt = i; }
1182
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001183 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1184
1185 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001186
1187 if (I == StmtMap.end())
1188 return false;
1189
1190 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1191 && I->second.second == CurrentStmt)
1192 return false;
1193
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001194 OS << "[B" << I->second.first << "." << I->second.second << "]";
1195 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001196 }
1197};
1198
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001199class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1200 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1201
Ted Kremenek42a509f2007-08-31 21:30:12 +00001202 std::ostream& OS;
1203 StmtPrinterHelper* Helper;
1204public:
1205 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1206 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001207
1208 void VisitIfStmt(IfStmt* I) {
1209 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001210 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001211 }
1212
1213 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001214 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001215
1216 void VisitForStmt(ForStmt* F) {
1217 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001218 if (F->getInit()) OS << "...";
1219 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001220 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001221 OS << "; ";
1222 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001223 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001224 }
1225
1226 void VisitWhileStmt(WhileStmt* W) {
1227 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001228 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001229 }
1230
1231 void VisitDoStmt(DoStmt* D) {
1232 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001233 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001234 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001235
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001236 void VisitSwitchStmt(SwitchStmt* S) {
1237 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001238 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001239 }
1240
Ted Kremenek805e9a82007-08-31 21:49:40 +00001241 void VisitConditionalOperator(ConditionalOperator* C) {
1242 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001243 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001244 }
1245
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001246 void VisitChooseExpr(ChooseExpr* C) {
1247 OS << "__builtin_choose_expr( ";
1248 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001249 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001250 }
1251
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001252 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1253 OS << "goto *";
1254 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001255 }
1256
Ted Kremenek805e9a82007-08-31 21:49:40 +00001257 void VisitBinaryOperator(BinaryOperator* B) {
1258 if (!B->isLogicalOp()) {
1259 VisitExpr(B);
1260 return;
1261 }
1262
1263 B->getLHS()->printPretty(OS,Helper);
1264
1265 switch (B->getOpcode()) {
1266 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001267 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001268 return;
1269 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001270 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001271 return;
1272 default:
1273 assert(false && "Invalid logical operator.");
1274 }
1275 }
1276
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001277 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001278 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001279 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001280};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001281
1282
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001283void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1284 if (Helper) {
1285 // special printing for statement-expressions.
1286 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1287 CompoundStmt* Sub = SE->getSubStmt();
1288
1289 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001290 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001291 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001292 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001293 return;
1294 }
1295 }
1296
1297 // special printing for comma expressions.
1298 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1299 if (B->getOpcode() == BinaryOperator::Comma) {
1300 OS << "... , ";
1301 Helper->handledStmt(B->getRHS(),OS);
1302 OS << '\n';
1303 return;
1304 }
1305 }
1306 }
1307
1308 S->printPretty(OS, Helper);
1309
1310 // Expressions need a newline.
1311 if (isa<Expr>(S)) OS << '\n';
1312}
1313
Ted Kremenek42a509f2007-08-31 21:30:12 +00001314void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1315 StmtPrinterHelper* Helper, bool print_edges) {
1316
1317 if (Helper) Helper->setBlockID(B.getBlockID());
1318
Ted Kremenek7dba8602007-08-29 21:56:09 +00001319 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001320 OS << "\n [ B" << B.getBlockID();
1321
1322 if (&B == &cfg->getEntry())
1323 OS << " (ENTRY) ]\n";
1324 else if (&B == &cfg->getExit())
1325 OS << " (EXIT) ]\n";
1326 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001327 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001328 else
1329 OS << " ]\n";
1330
Ted Kremenek9cffe732007-08-29 23:20:49 +00001331 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001332 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1333
1334 if (print_edges)
1335 OS << " ";
1336
Ted Kremenek9cffe732007-08-29 23:20:49 +00001337 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1338 OS << L->getName();
1339 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1340 OS << "case ";
1341 C->getLHS()->printPretty(OS);
1342 if (C->getRHS()) {
1343 OS << " ... ";
1344 C->getRHS()->printPretty(OS);
1345 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001346 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001347 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001348 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001349 else
1350 assert(false && "Invalid label statement in CFGBlock.");
1351
Ted Kremenek9cffe732007-08-29 23:20:49 +00001352 OS << ":\n";
1353 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001354
Ted Kremenekfddd5182007-08-21 21:42:03 +00001355 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001356 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001357
1358 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1359 I != E ; ++I, ++j ) {
1360
Ted Kremenek9cffe732007-08-29 23:20:49 +00001361 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001362 if (print_edges)
1363 OS << " ";
1364
1365 OS << std::setw(3) << j << ": ";
1366
1367 if (Helper)
1368 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001369
1370 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001371 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001372
Ted Kremenek9cffe732007-08-29 23:20:49 +00001373 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001374 if (B.getTerminator()) {
1375 if (print_edges)
1376 OS << " ";
1377
Ted Kremenek9cffe732007-08-29 23:20:49 +00001378 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001379
1380 if (Helper) Helper->setBlockID(-1);
1381
1382 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1383 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001384 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001385 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001386
Ted Kremenek9cffe732007-08-29 23:20:49 +00001387 if (print_edges) {
1388 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001389 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001390 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001391
Ted Kremenek42a509f2007-08-31 21:30:12 +00001392 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1393 I != E; ++I, ++i) {
1394
1395 if (i == 8 || (i-8) == 0)
1396 OS << "\n ";
1397
Ted Kremenek9cffe732007-08-29 23:20:49 +00001398 OS << " B" << (*I)->getBlockID();
1399 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001400
1401 OS << '\n';
1402
1403 // Print the successors of this block.
1404 OS << " Successors (" << B.succ_size() << "):";
1405 i = 0;
1406
1407 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1408 I != E; ++I, ++i) {
1409
1410 if (i == 8 || (i-8) % 10 == 0)
1411 OS << "\n ";
1412
1413 OS << " B" << (*I)->getBlockID();
1414 }
1415
Ted Kremenek9cffe732007-08-29 23:20:49 +00001416 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001417 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001418}
1419
1420} // end anonymous namespace
1421
1422/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001423void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001424
1425/// print - A simple pretty printer of a CFG that outputs to an ostream.
1426void CFG::print(std::ostream& OS) const {
1427
1428 StmtPrinterHelper Helper(this);
1429
1430 // Print the entry block.
1431 print_block(OS, this, getEntry(), &Helper, true);
1432
1433 // Iterate through the CFGBlocks and print them one by one.
1434 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1435 // Skip the entry block, because we already printed it.
1436 if (&(*I) == &getEntry() || &(*I) == &getExit())
1437 continue;
1438
1439 print_block(OS, this, *I, &Helper, true);
1440 }
1441
1442 // Print the exit block.
1443 print_block(OS, this, getExit(), &Helper, true);
1444}
1445
1446/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001447void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001448
1449/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1450/// Generally this will only be called from CFG::print.
1451void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1452 StmtPrinterHelper Helper(cfg);
1453 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001454}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001455
Ted Kremeneka2925852008-01-30 23:02:42 +00001456/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1457void CFGBlock::printTerminator(std::ostream& OS) const {
1458 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1459 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1460}
1461
1462
Ted Kremenek7dba8602007-08-29 21:56:09 +00001463//===----------------------------------------------------------------------===//
1464// CFG Graphviz Visualization
1465//===----------------------------------------------------------------------===//
1466
Ted Kremenek42a509f2007-08-31 21:30:12 +00001467
1468#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001469static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001470#endif
1471
1472void CFG::viewCFG() const {
1473#ifndef NDEBUG
1474 StmtPrinterHelper H(this);
1475 GraphHelper = &H;
1476 llvm::ViewGraph(this,"CFG");
1477 GraphHelper = NULL;
1478#else
1479 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001480 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001481#endif
1482}
1483
Ted Kremenek7dba8602007-08-29 21:56:09 +00001484namespace llvm {
1485template<>
1486struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1487 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1488
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001489#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001490 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001491 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001492 std::string OutStr = Out.str();
1493
1494 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1495
1496 // Process string output to make it nicer...
1497 for (unsigned i = 0; i != OutStr.length(); ++i)
1498 if (OutStr[i] == '\n') { // Left justify
1499 OutStr[i] = '\\';
1500 OutStr.insert(OutStr.begin()+i+1, 'l');
1501 }
1502
1503 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001504#else
1505 return "";
1506#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001507 }
1508};
1509} // end namespace llvm