blob: d8c5f1ce6955a93b43b521859ce7be0860750890 [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 Kremeneka716d7a2008-03-17 17:19:44 +0000478
479 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000480
Ted Kremenekd34066c2008-02-26 00:22:58 +0000481 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
482 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000483 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000484 }
485
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000486 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000487}
488
489CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
490 // We may see an if statement in the middle of a basic block, or
491 // it may be the first statement we are processing. In either case,
492 // we create a new basic block. First, we create the blocks for
493 // the then...else statements, and then we create the block containing
494 // the if statement. If we were in the middle of a block, we
495 // stop processing that block and reverse its statements. That block
496 // is then the implicit successor for the "then" and "else" clauses.
497
498 // The block we were proccessing is now finished. Make it the
499 // successor block.
500 if (Block) {
501 Succ = Block;
502 FinishBlock(Block);
503 }
504
505 // Process the false branch. NULL out Block so that the recursive
506 // call to Visit will create a new basic block.
507 // Null out Block so that all successor
508 CFGBlock* ElseBlock = Succ;
509
510 if (Stmt* Else = I->getElse()) {
511 SaveAndRestore<CFGBlock*> sv(Succ);
512
513 // NULL out Block so that the recursive call to Visit will
514 // create a new basic block.
515 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000516 ElseBlock = Visit(Else);
517
518 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
519 ElseBlock = sv.get();
520 else if (Block)
521 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000522 }
523
524 // Process the true branch. NULL out Block so that the recursive
525 // call to Visit will create a new basic block.
526 // Null out Block so that all successor
527 CFGBlock* ThenBlock;
528 {
529 Stmt* Then = I->getThen();
530 assert (Then);
531 SaveAndRestore<CFGBlock*> sv(Succ);
532 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000533 ThenBlock = Visit(Then);
534
535 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
536 ThenBlock = sv.get();
537 else if (Block)
538 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000539 }
540
541 // Now create a new block containing the if statement.
542 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000543
544 // Set the terminator of the new block to the If statement.
545 Block->setTerminator(I);
546
547 // Now add the successors.
548 Block->addSuccessor(ThenBlock);
549 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000550
551 // Add the condition as the last statement in the new block. This
552 // may create new blocks as the condition may contain control-flow. Any
553 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000554 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000555}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000556
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000557
558CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
559 // If we were in the middle of a block we stop processing that block
560 // and reverse its statements.
561 //
562 // NOTE: If a "return" appears in the middle of a block, this means
563 // that the code afterwards is DEAD (unreachable). We still
564 // keep a basic block for that code; a simple "mark-and-sweep"
565 // from the entry block will be able to report such dead
566 // blocks.
567 if (Block) FinishBlock(Block);
568
569 // Create the new block.
570 Block = createBlock(false);
571
572 // The Exit block is the only successor.
573 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000574
575 // Add the return statement to the block. This may create new blocks
576 // if R contains control-flow (short-circuit operations).
577 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000578}
579
580CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
581 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000582 Visit(L->getSubStmt());
583 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000584
585 if (!LabelBlock) // This can happen when the body is empty, i.e.
586 LabelBlock=createBlock(); // scopes that only contains NullStmts.
587
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000588 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
589 LabelMap[ L ] = LabelBlock;
590
591 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000592 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000593 // label (and we have already processed the substatement) there is no
594 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000595 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000596 FinishBlock(LabelBlock);
597
598 // We set Block to NULL to allow lazy creation of a new block
599 // (if necessary);
600 Block = NULL;
601
602 // This block is now the implicit successor of other blocks.
603 Succ = LabelBlock;
604
605 return LabelBlock;
606}
607
608CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
609 // Goto is a control-flow statement. Thus we stop processing the
610 // current block and create a new one.
611 if (Block) FinishBlock(Block);
612 Block = createBlock(false);
613 Block->setTerminator(G);
614
615 // If we already know the mapping to the label block add the
616 // successor now.
617 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
618
619 if (I == LabelMap.end())
620 // We will need to backpatch this block later.
621 BackpatchBlocks.push_back(Block);
622 else
623 Block->addSuccessor(I->second);
624
625 return Block;
626}
627
628CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
629 // "for" is a control-flow statement. Thus we stop processing the
630 // current block.
631
632 CFGBlock* LoopSuccessor = NULL;
633
634 if (Block) {
635 FinishBlock(Block);
636 LoopSuccessor = Block;
637 }
638 else LoopSuccessor = Succ;
639
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000640 // Because of short-circuit evaluation, the condition of the loop
641 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
642 // blocks that evaluate the condition.
643 CFGBlock* ExitConditionBlock = createBlock(false);
644 CFGBlock* EntryConditionBlock = ExitConditionBlock;
645
646 // Set the terminator for the "exit" condition block.
647 ExitConditionBlock->setTerminator(F);
648
649 // Now add the actual condition to the condition block. Because the
650 // condition itself may contain control-flow, new blocks may be created.
651 if (Stmt* C = F->getCond()) {
652 Block = ExitConditionBlock;
653 EntryConditionBlock = addStmt(C);
654 if (Block) FinishBlock(EntryConditionBlock);
655 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000656
657 // The condition block is the implicit successor for the loop body as
658 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000659 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000660
661 // Now create the loop body.
662 {
663 assert (F->getBody());
664
665 // Save the current values for Block, Succ, and continue and break targets
666 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
667 save_continue(ContinueTargetBlock),
668 save_break(BreakTargetBlock);
669
670 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000671 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000672
673 // All breaks should go to the code following the loop.
674 BreakTargetBlock = LoopSuccessor;
675
Ted Kremenekaf603f72007-08-30 18:39:40 +0000676 // Create a new block to contain the (bottom) of the loop body.
677 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000678
679 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000680 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000681
682 // Now populate the body block, and in the process create new blocks
683 // as we walk the body of the loop.
684 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000685
686 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000687 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000688 else if (Block)
689 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000690
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000691 // This new body block is a successor to our "exit" condition block.
692 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000693 }
694
695 // Link up the condition block with the code that follows the loop.
696 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000697 ExitConditionBlock->addSuccessor(LoopSuccessor);
698
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000699 // If the loop contains initialization, create a new block for those
700 // statements. This block can also contain statements that precede
701 // the loop.
702 if (Stmt* I = F->getInit()) {
703 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000704 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000705 }
706 else {
707 // There is no loop initialization. We are thus basically a while
708 // loop. NULL out Block to force lazy block construction.
709 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000710 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000711 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000712 }
713}
714
715CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
716 // "while" is a control-flow statement. Thus we stop processing the
717 // current block.
718
719 CFGBlock* LoopSuccessor = NULL;
720
721 if (Block) {
722 FinishBlock(Block);
723 LoopSuccessor = Block;
724 }
725 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000726
727 // Because of short-circuit evaluation, the condition of the loop
728 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
729 // blocks that evaluate the condition.
730 CFGBlock* ExitConditionBlock = createBlock(false);
731 CFGBlock* EntryConditionBlock = ExitConditionBlock;
732
733 // Set the terminator for the "exit" condition block.
734 ExitConditionBlock->setTerminator(W);
735
736 // Now add the actual condition to the condition block. Because the
737 // condition itself may contain control-flow, new blocks may be created.
738 // Thus we update "Succ" after adding the condition.
739 if (Stmt* C = W->getCond()) {
740 Block = ExitConditionBlock;
741 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000742 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000743 if (Block) FinishBlock(EntryConditionBlock);
744 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000745
746 // The condition block is the implicit successor for the loop body as
747 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000748 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000749
750 // Process the loop body.
751 {
752 assert (W->getBody());
753
754 // Save the current values for Block, Succ, and continue and break targets
755 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
756 save_continue(ContinueTargetBlock),
757 save_break(BreakTargetBlock);
758
759 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000760 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000761
762 // All breaks should go to the code following the loop.
763 BreakTargetBlock = LoopSuccessor;
764
765 // NULL out Block to force lazy instantiation of blocks for the body.
766 Block = NULL;
767
768 // Create the body. The returned block is the entry to the loop body.
769 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000770
771 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000772 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000773 else if (Block)
774 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000775
776 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000777 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000778 }
779
780 // Link up the condition block with the code that follows the loop.
781 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000782 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000783
784 // There can be no more statements in the condition block
785 // since we loop back to this block. NULL out Block to force
786 // lazy creation of another block.
787 Block = NULL;
788
789 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000790 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000791 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000792}
793
794CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
795 // "do...while" is a control-flow statement. Thus we stop processing the
796 // current block.
797
798 CFGBlock* LoopSuccessor = NULL;
799
800 if (Block) {
801 FinishBlock(Block);
802 LoopSuccessor = Block;
803 }
804 else LoopSuccessor = Succ;
805
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000806 // Because of short-circuit evaluation, the condition of the loop
807 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
808 // blocks that evaluate the condition.
809 CFGBlock* ExitConditionBlock = createBlock(false);
810 CFGBlock* EntryConditionBlock = ExitConditionBlock;
811
812 // Set the terminator for the "exit" condition block.
813 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000814
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000815 // Now add the actual condition to the condition block. Because the
816 // condition itself may contain control-flow, new blocks may be created.
817 if (Stmt* C = D->getCond()) {
818 Block = ExitConditionBlock;
819 EntryConditionBlock = addStmt(C);
820 if (Block) FinishBlock(EntryConditionBlock);
821 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000822
Ted Kremenek54827132008-02-27 07:20:00 +0000823 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000824 Succ = EntryConditionBlock;
825
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000826 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000827 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000828 {
829 assert (D->getBody());
830
831 // Save the current values for Block, Succ, and continue and break targets
832 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
833 save_continue(ContinueTargetBlock),
834 save_break(BreakTargetBlock);
835
836 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000837 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000838
839 // All breaks should go to the code following the loop.
840 BreakTargetBlock = LoopSuccessor;
841
842 // NULL out Block to force lazy instantiation of blocks for the body.
843 Block = NULL;
844
845 // Create the body. The returned block is the entry to the loop body.
846 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000847
Ted Kremenekaf603f72007-08-30 18:39:40 +0000848 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000849 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000850 else if (Block)
851 FinishBlock(BodyBlock);
852
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000853 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000854 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000855 }
856
857 // Link up the condition block with the code that follows the loop.
858 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000859 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000860
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000861 // There can be no more statements in the body block(s)
862 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000863 // lazy creation of another block.
864 Block = NULL;
865
866 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000867 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000868 return BodyBlock;
869}
870
871CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
872 // "continue" is a control-flow statement. Thus we stop processing the
873 // current block.
874 if (Block) FinishBlock(Block);
875
876 // Now create a new block that ends with the continue statement.
877 Block = createBlock(false);
878 Block->setTerminator(C);
879
880 // If there is no target for the continue, then we are looking at an
881 // incomplete AST. Handle this by not registering a successor.
882 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
883
884 return Block;
885}
886
887CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
888 // "break" is a control-flow statement. Thus we stop processing the
889 // current block.
890 if (Block) FinishBlock(Block);
891
892 // Now create a new block that ends with the continue statement.
893 Block = createBlock(false);
894 Block->setTerminator(B);
895
896 // If there is no target for the break, then we are looking at an
897 // incomplete AST. Handle this by not registering a successor.
898 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
899
900 return Block;
901}
902
903CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
904 // "switch" is a control-flow statement. Thus we stop processing the
905 // current block.
906 CFGBlock* SwitchSuccessor = NULL;
907
908 if (Block) {
909 FinishBlock(Block);
910 SwitchSuccessor = Block;
911 }
912 else SwitchSuccessor = Succ;
913
914 // Save the current "switch" context.
915 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000916 save_break(BreakTargetBlock),
917 save_default(DefaultCaseBlock);
918
919 // Set the "default" case to be the block after the switch statement.
920 // If the switch statement contains a "default:", this value will
921 // be overwritten with the block for that code.
922 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000923
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000924 // Create a new block that will contain the switch statement.
925 SwitchTerminatedBlock = createBlock(false);
926
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000927 // Now process the switch body. The code after the switch is the implicit
928 // successor.
929 Succ = SwitchSuccessor;
930 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000931
932 // When visiting the body, the case statements should automatically get
933 // linked up to the switch. We also don't keep a pointer to the body,
934 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000935 assert (S->getBody() && "switch must contain a non-NULL body");
936 Block = NULL;
937 CFGBlock *BodyBlock = Visit(S->getBody());
938 if (Block) FinishBlock(BodyBlock);
939
Ted Kremenek295222c2008-02-13 21:46:34 +0000940 // If we have no "default:" case, the default transition is to the
941 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000942 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000943
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000944 // Add the terminator and condition in the switch block.
945 SwitchTerminatedBlock->setTerminator(S);
946 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000947 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000948
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000949 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000950}
951
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000952CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
953 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000954 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000955
956 if (S->getSubStmt()) Visit(S->getSubStmt());
957 CFGBlock* CaseBlock = Block;
958 if (!CaseBlock) CaseBlock = createBlock();
959
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000960 // Cases statements partition blocks, so this is the top of
961 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek9cffe732007-08-29 23:20:49 +0000962 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000963 FinishBlock(CaseBlock);
964
965 // Add this block to the list of successors for the block with the
966 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000967 assert (SwitchTerminatedBlock);
968 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000969
970 // We set Block to NULL to allow lazy creation of a new block (if necessary)
971 Block = NULL;
972
973 // This block is now the implicit successor of other blocks.
974 Succ = CaseBlock;
975
Ted Kremenek2677ea82008-03-15 07:45:02 +0000976 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000977}
Ted Kremenek295222c2008-02-13 21:46:34 +0000978
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000979CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
980 if (S->getSubStmt()) Visit(S->getSubStmt());
981 DefaultCaseBlock = Block;
982 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
983
984 // Default statements partition blocks, so this is the top of
985 // the basic block we were processing (the "default:" is the label).
986 DefaultCaseBlock->setLabel(S);
987 FinishBlock(DefaultCaseBlock);
988
989 // Unlike case statements, we don't add the default block to the
990 // successors for the switch statement immediately. This is done
991 // when we finish processing the switch statement. This allows for
992 // the default case (including a fall-through to the code after the
993 // switch statement) to always be the last successor of a switch-terminated
994 // block.
995
996 // We set Block to NULL to allow lazy creation of a new block (if necessary)
997 Block = NULL;
998
999 // This block is now the implicit successor of other blocks.
1000 Succ = DefaultCaseBlock;
1001
1002 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001003}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001004
Ted Kremenek19bb3562007-08-28 19:26:49 +00001005CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1006 // Lazily create the indirect-goto dispatch block if there isn't one
1007 // already.
1008 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1009
1010 if (!IBlock) {
1011 IBlock = createBlock(false);
1012 cfg->setIndirectGotoBlock(IBlock);
1013 }
1014
1015 // IndirectGoto is a control-flow statement. Thus we stop processing the
1016 // current block and create a new one.
1017 if (Block) FinishBlock(Block);
1018 Block = createBlock(false);
1019 Block->setTerminator(I);
1020 Block->addSuccessor(IBlock);
1021 return addStmt(I->getTarget());
1022}
1023
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001024
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001025} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001026
1027/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1028/// block has no successors or predecessors. If this is the first block
1029/// created in the CFG, it is automatically set to be the Entry and Exit
1030/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001031CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001032 bool first_block = begin() == end();
1033
1034 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001035 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001036
1037 // If this is the first block, set it as the Entry and Exit.
1038 if (first_block) Entry = Exit = &front();
1039
1040 // Return the block.
1041 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001042}
1043
Ted Kremenek026473c2007-08-23 16:51:22 +00001044/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1045/// CFG is returned to the caller.
1046CFG* CFG::buildCFG(Stmt* Statement) {
1047 CFGBuilder Builder;
1048 return Builder.buildCFG(Statement);
1049}
1050
1051/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001052void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1053
Ted Kremenek63f58872007-10-01 19:33:33 +00001054//===----------------------------------------------------------------------===//
1055// CFG: Queries for BlkExprs.
1056//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001057
Ted Kremenek63f58872007-10-01 19:33:33 +00001058namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001059 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001060}
1061
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001062static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1063 if (!S)
1064 return;
1065
1066 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1067 if (!*I) continue;
1068
1069 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1070 if (B->isAssignmentOp()) Set.insert(B);
1071
1072 FindSubExprAssignments(*I, Set);
1073 }
1074}
1075
Ted Kremenek63f58872007-10-01 19:33:33 +00001076static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1077 BlkExprMapTy* M = new BlkExprMapTy();
1078
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001079 // Look for assignments that are used as subexpressions. These are the
1080 // only assignments that we want to register as a block-level expression.
1081 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1082
Ted Kremenek63f58872007-10-01 19:33:33 +00001083 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1084 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001085 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001086
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001087 // Iterate over the statements again on identify the Expr* and Stmt* at
1088 // the block-level that are block-level expressions.
1089 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1090 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1091 if (Expr* E = dyn_cast<Expr>(*BI)) {
1092
1093 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1094 // Assignment expressions that are not nested within another
1095 // expression are really "statements" whose value is never
1096 // used by another expression.
1097 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1098 continue;
1099 }
1100 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1101 // Special handling for statement expressions. The last statement
1102 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001103 const CompoundStmt* C = S->getSubStmt();
1104 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001105 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001106 (*M)[C->body_back()] = x;
1107 }
1108 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001109
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001110 unsigned x = M->size();
1111 (*M)[E] = x;
1112 }
1113
Ted Kremenek63f58872007-10-01 19:33:33 +00001114 return M;
1115}
1116
Ted Kremenek86946742008-01-17 20:48:37 +00001117CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1118 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001119 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1120
1121 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001122 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001123
1124 if (I == M->end()) return CFG::BlkExprNumTy();
1125 else return CFG::BlkExprNumTy(I->second);
1126}
1127
1128unsigned CFG::getNumBlkExprs() {
1129 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1130 return M->size();
1131 else {
1132 // We assume callers interested in the number of BlkExprs will want
1133 // the map constructed if it doesn't already exist.
1134 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1135 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1136 }
1137}
1138
Ted Kremenek83c01da2008-01-11 00:40:29 +00001139typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1140
1141const std::pair<CFGBlock*,CFGBlock*>*
1142CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1143
1144 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1145 if (!p) p = new BlkEdgeSetTy();
1146
1147 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1148 const_cast<CFGBlock*>(B2))).first);
1149}
1150
Ted Kremenek63f58872007-10-01 19:33:33 +00001151CFG::~CFG() {
1152 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001153 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001154}
1155
Ted Kremenek7dba8602007-08-29 21:56:09 +00001156//===----------------------------------------------------------------------===//
1157// CFG pretty printing
1158//===----------------------------------------------------------------------===//
1159
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001160namespace {
1161
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001162class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001163
Ted Kremenek42a509f2007-08-31 21:30:12 +00001164 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1165 StmtMapTy StmtMap;
1166 signed CurrentBlock;
1167 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001168
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001169public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001170
Ted Kremenek42a509f2007-08-31 21:30:12 +00001171 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1172 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1173 unsigned j = 1;
1174 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1175 BI != BEnd; ++BI, ++j )
1176 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1177 }
1178 }
1179
1180 virtual ~StmtPrinterHelper() {}
1181
1182 void setBlockID(signed i) { CurrentBlock = i; }
1183 void setStmtID(unsigned i) { CurrentStmt = i; }
1184
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001185 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1186
1187 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001188
1189 if (I == StmtMap.end())
1190 return false;
1191
1192 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1193 && I->second.second == CurrentStmt)
1194 return false;
1195
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001196 OS << "[B" << I->second.first << "." << I->second.second << "]";
1197 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001198 }
1199};
1200
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001201class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1202 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1203
Ted Kremenek42a509f2007-08-31 21:30:12 +00001204 std::ostream& OS;
1205 StmtPrinterHelper* Helper;
1206public:
1207 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1208 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001209
1210 void VisitIfStmt(IfStmt* I) {
1211 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001212 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001213 }
1214
1215 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001216 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001217
1218 void VisitForStmt(ForStmt* F) {
1219 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001220 if (F->getInit()) OS << "...";
1221 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001222 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001223 OS << "; ";
1224 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001225 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001226 }
1227
1228 void VisitWhileStmt(WhileStmt* W) {
1229 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001230 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001231 }
1232
1233 void VisitDoStmt(DoStmt* D) {
1234 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001235 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001236 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001237
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001238 void VisitSwitchStmt(SwitchStmt* S) {
1239 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001240 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001241 }
1242
Ted Kremenek805e9a82007-08-31 21:49:40 +00001243 void VisitConditionalOperator(ConditionalOperator* C) {
1244 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001245 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001246 }
1247
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001248 void VisitChooseExpr(ChooseExpr* C) {
1249 OS << "__builtin_choose_expr( ";
1250 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001251 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001252 }
1253
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001254 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1255 OS << "goto *";
1256 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001257 }
1258
Ted Kremenek805e9a82007-08-31 21:49:40 +00001259 void VisitBinaryOperator(BinaryOperator* B) {
1260 if (!B->isLogicalOp()) {
1261 VisitExpr(B);
1262 return;
1263 }
1264
1265 B->getLHS()->printPretty(OS,Helper);
1266
1267 switch (B->getOpcode()) {
1268 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001269 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001270 return;
1271 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001272 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001273 return;
1274 default:
1275 assert(false && "Invalid logical operator.");
1276 }
1277 }
1278
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001279 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001280 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001281 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001282};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001283
1284
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001285void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1286 if (Helper) {
1287 // special printing for statement-expressions.
1288 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1289 CompoundStmt* Sub = SE->getSubStmt();
1290
1291 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001292 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001293 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001294 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001295 return;
1296 }
1297 }
1298
1299 // special printing for comma expressions.
1300 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1301 if (B->getOpcode() == BinaryOperator::Comma) {
1302 OS << "... , ";
1303 Helper->handledStmt(B->getRHS(),OS);
1304 OS << '\n';
1305 return;
1306 }
1307 }
1308 }
1309
1310 S->printPretty(OS, Helper);
1311
1312 // Expressions need a newline.
1313 if (isa<Expr>(S)) OS << '\n';
1314}
1315
Ted Kremenek42a509f2007-08-31 21:30:12 +00001316void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1317 StmtPrinterHelper* Helper, bool print_edges) {
1318
1319 if (Helper) Helper->setBlockID(B.getBlockID());
1320
Ted Kremenek7dba8602007-08-29 21:56:09 +00001321 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001322 OS << "\n [ B" << B.getBlockID();
1323
1324 if (&B == &cfg->getEntry())
1325 OS << " (ENTRY) ]\n";
1326 else if (&B == &cfg->getExit())
1327 OS << " (EXIT) ]\n";
1328 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001329 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001330 else
1331 OS << " ]\n";
1332
Ted Kremenek9cffe732007-08-29 23:20:49 +00001333 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001334 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1335
1336 if (print_edges)
1337 OS << " ";
1338
Ted Kremenek9cffe732007-08-29 23:20:49 +00001339 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1340 OS << L->getName();
1341 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1342 OS << "case ";
1343 C->getLHS()->printPretty(OS);
1344 if (C->getRHS()) {
1345 OS << " ... ";
1346 C->getRHS()->printPretty(OS);
1347 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001348 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001349 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001350 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001351 else
1352 assert(false && "Invalid label statement in CFGBlock.");
1353
Ted Kremenek9cffe732007-08-29 23:20:49 +00001354 OS << ":\n";
1355 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001356
Ted Kremenekfddd5182007-08-21 21:42:03 +00001357 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001358 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001359
1360 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1361 I != E ; ++I, ++j ) {
1362
Ted Kremenek9cffe732007-08-29 23:20:49 +00001363 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001364 if (print_edges)
1365 OS << " ";
1366
1367 OS << std::setw(3) << j << ": ";
1368
1369 if (Helper)
1370 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001371
1372 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001373 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001374
Ted Kremenek9cffe732007-08-29 23:20:49 +00001375 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001376 if (B.getTerminator()) {
1377 if (print_edges)
1378 OS << " ";
1379
Ted Kremenek9cffe732007-08-29 23:20:49 +00001380 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001381
1382 if (Helper) Helper->setBlockID(-1);
1383
1384 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1385 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001386 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001387 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001388
Ted Kremenek9cffe732007-08-29 23:20:49 +00001389 if (print_edges) {
1390 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001391 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001392 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001393
Ted Kremenek42a509f2007-08-31 21:30:12 +00001394 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1395 I != E; ++I, ++i) {
1396
1397 if (i == 8 || (i-8) == 0)
1398 OS << "\n ";
1399
Ted Kremenek9cffe732007-08-29 23:20:49 +00001400 OS << " B" << (*I)->getBlockID();
1401 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001402
1403 OS << '\n';
1404
1405 // Print the successors of this block.
1406 OS << " Successors (" << B.succ_size() << "):";
1407 i = 0;
1408
1409 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1410 I != E; ++I, ++i) {
1411
1412 if (i == 8 || (i-8) % 10 == 0)
1413 OS << "\n ";
1414
1415 OS << " B" << (*I)->getBlockID();
1416 }
1417
Ted Kremenek9cffe732007-08-29 23:20:49 +00001418 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001419 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001420}
1421
1422} // end anonymous namespace
1423
1424/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001425void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426
1427/// print - A simple pretty printer of a CFG that outputs to an ostream.
1428void CFG::print(std::ostream& OS) const {
1429
1430 StmtPrinterHelper Helper(this);
1431
1432 // Print the entry block.
1433 print_block(OS, this, getEntry(), &Helper, true);
1434
1435 // Iterate through the CFGBlocks and print them one by one.
1436 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1437 // Skip the entry block, because we already printed it.
1438 if (&(*I) == &getEntry() || &(*I) == &getExit())
1439 continue;
1440
1441 print_block(OS, this, *I, &Helper, true);
1442 }
1443
1444 // Print the exit block.
1445 print_block(OS, this, getExit(), &Helper, true);
1446}
1447
1448/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001449void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001450
1451/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1452/// Generally this will only be called from CFG::print.
1453void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1454 StmtPrinterHelper Helper(cfg);
1455 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001456}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001457
Ted Kremeneka2925852008-01-30 23:02:42 +00001458/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1459void CFGBlock::printTerminator(std::ostream& OS) const {
1460 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1461 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1462}
1463
1464
Ted Kremenek7dba8602007-08-29 21:56:09 +00001465//===----------------------------------------------------------------------===//
1466// CFG Graphviz Visualization
1467//===----------------------------------------------------------------------===//
1468
Ted Kremenek42a509f2007-08-31 21:30:12 +00001469
1470#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001471static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001472#endif
1473
1474void CFG::viewCFG() const {
1475#ifndef NDEBUG
1476 StmtPrinterHelper H(this);
1477 GraphHelper = &H;
1478 llvm::ViewGraph(this,"CFG");
1479 GraphHelper = NULL;
1480#else
1481 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001482 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001483#endif
1484}
1485
Ted Kremenek7dba8602007-08-29 21:56:09 +00001486namespace llvm {
1487template<>
1488struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1489 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1490
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001491#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001492 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001493 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001494 std::string OutStr = Out.str();
1495
1496 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1497
1498 // Process string output to make it nicer...
1499 for (unsigned i = 0; i != OutStr.length(); ++i)
1500 if (OutStr[i] == '\n') { // Left justify
1501 OutStr[i] = '\\';
1502 OutStr.insert(OutStr.begin()+i+1, 'l');
1503 }
1504
1505 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001506#else
1507 return "";
1508#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001509 }
1510};
1511} // end namespace llvm