blob: 42f401b84755a61065e7e3ef7834c449fe25e74b [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//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Kremenekfddd5182007-08-21 21:42:03 +000022#include <iostream>
23#include <iomanip>
24#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000025#include <sstream>
26
Ted Kremenekfddd5182007-08-21 21:42:03 +000027using namespace clang;
28
29namespace {
30
Ted Kremenekbefef2f2007-08-23 21:26:19 +000031// SaveAndRestore - A utility class that uses RIIA to save and restore
32// the value of a variable.
33template<typename T>
34struct SaveAndRestore {
35 SaveAndRestore(T& x) : X(x), old_value(x) {}
36 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000037 T get() { return old_value; }
38
Ted Kremenekbefef2f2007-08-23 21:26:19 +000039 T& X;
40 T old_value;
41};
Ted Kremenekfddd5182007-08-21 21:42:03 +000042
43/// CFGBuilder - This class is implements CFG construction from an AST.
44/// The builder is stateful: an instance of the builder should be used to only
45/// construct a single CFG.
46///
47/// Example usage:
48///
49/// CFGBuilder builder;
50/// CFG* cfg = builder.BuildAST(stmt1);
51///
Ted Kremenekc310e932007-08-21 22:06:14 +000052/// CFG construction is done via a recursive walk of an AST.
53/// We actually parse the AST in reverse order so that the successor
54/// of a basic block is constructed prior to its predecessor. This
55/// allows us to nicely capture implicit fall-throughs without extra
56/// basic blocks.
57///
58class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000059 CFG* cfg;
60 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000061 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000062 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000063 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000064 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000065
Ted Kremenek19bb3562007-08-28 19:26:49 +000066 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000067 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
68 LabelMapTy LabelMap;
69
Ted Kremenek19bb3562007-08-28 19:26:49 +000070 // A list of blocks that end with a "goto" that must be backpatched to
71 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000072 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000073 BackpatchBlocksTy BackpatchBlocks;
74
Ted Kremenek19bb3562007-08-28 19:26:49 +000075 // A list of labels whose address has been taken (for indirect gotos).
76 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
77 LabelSetTy AddressTakenLabels;
78
Ted Kremenekfddd5182007-08-21 21:42:03 +000079public:
Ted Kremenek026473c2007-08-23 16:51:22 +000080 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000081 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek94382522007-09-05 20:02:05 +000082 SwitchTerminatedBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000083 // Create an empty CFG.
84 cfg = new CFG();
85 }
86
87 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000088
Ted Kremenekd4fdee32007-08-23 21:42:29 +000089 // buildCFG - Used by external clients to construct the CFG.
90 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000091
Ted Kremenekd4fdee32007-08-23 21:42:29 +000092 // Visitors to walk an AST and construct the CFG. Called by
93 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000094
Ted Kremenekd4fdee32007-08-23 21:42:29 +000095 CFGBlock* VisitStmt(Stmt* Statement);
96 CFGBlock* VisitNullStmt(NullStmt* Statement);
97 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
98 CFGBlock* VisitIfStmt(IfStmt* I);
99 CFGBlock* VisitReturnStmt(ReturnStmt* R);
100 CFGBlock* VisitLabelStmt(LabelStmt* L);
101 CFGBlock* VisitGotoStmt(GotoStmt* G);
102 CFGBlock* VisitForStmt(ForStmt* F);
103 CFGBlock* VisitWhileStmt(WhileStmt* W);
104 CFGBlock* VisitDoStmt(DoStmt* D);
105 CFGBlock* VisitContinueStmt(ContinueStmt* C);
106 CFGBlock* VisitBreakStmt(BreakStmt* B);
107 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
108 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000109 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000110
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000111private:
112 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000113 CFGBlock* addStmt(Stmt* S);
114 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
115 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000116 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000117 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000118 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000119 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000120
Ted Kremenekfddd5182007-08-21 21:42:03 +0000121};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000122
123/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
124/// represent an arbitrary statement. Examples include a single expression
125/// or a function body (compound statement). The ownership of the returned
126/// CFG is transferred to the caller. If CFG construction fails, this method
127/// returns NULL.
128CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000129 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000130 if (!Statement) return NULL;
131
132 // Create an empty block that will serve as the exit block for the CFG.
133 // Since this is the first block added to the CFG, it will be implicitly
134 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000135 Succ = createBlock();
136 assert (Succ == &cfg->getExit());
137 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000138
139 // Visit the statements and create the CFG.
140 if (CFGBlock* B = Visit(Statement)) {
141 // Finalize the last constructed block. This usually involves
142 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000143 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000144
145 // Backpatch the gotos whose label -> block mappings we didn't know
146 // when we encountered them.
147 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
148 E = BackpatchBlocks.end(); I != E; ++I ) {
149
150 CFGBlock* B = *I;
151 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
152 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
153
154 // If there is no target for the goto, then we are looking at an
155 // incomplete AST. Handle this by not registering a successor.
156 if (LI == LabelMap.end()) continue;
157
158 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000159 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000160
Ted Kremenek19bb3562007-08-28 19:26:49 +0000161 // Add successors to the Indirect Goto Dispatch block (if we have one).
162 if (CFGBlock* B = cfg->getIndirectGotoBlock())
163 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
164 E = AddressTakenLabels.end(); I != E; ++I ) {
165
166 // Lookup the target block.
167 LabelMapTy::iterator LI = LabelMap.find(*I);
168
169 // If there is no target block that contains label, then we are looking
170 // at an incomplete AST. Handle this by not registering a successor.
171 if (LI == LabelMap.end()) continue;
172
173 B->addSuccessor(LI->second);
174 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000175
Ted Kremenek94b33162007-09-17 16:18:02 +0000176 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000177 }
178
179 // Create an empty entry block that has no predecessors.
180 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000181
Ted Kremenek322f58d2007-09-26 21:23:31 +0000182 // NULL out cfg so that repeated calls to the builder will fail and that
183 // the ownership of the constructed CFG is passed to the caller.
184 CFG* t = cfg;
185 cfg = NULL;
186 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000187}
188
189/// createBlock - Used to lazily create blocks that are connected
190/// to the current (global) succcessor.
191CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000192 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000193 if (add_successor && Succ) B->addSuccessor(Succ);
194 return B;
195}
196
197/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000198/// we must reverse the statements because they have been inserted
199/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000200void CFGBuilder::FinishBlock(CFGBlock* B) {
201 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000202 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203}
204
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000205/// addStmt - Used to add statements/expressions to the current CFGBlock
206/// "Block". This method calls WalkAST on the passed statement to see if it
207/// contains any short-circuit expressions. If so, it recursively creates
208/// the necessary blocks for such expressions. It returns the "topmost" block
209/// of the created blocks, or the original value of "Block" when this method
210/// was called if no additional blocks are created.
211CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000212 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000213 return WalkAST(S,true);
214}
215
216/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000217/// add extra blocks for ternary operators, &&, and ||. We also
218/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000219CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
220 switch (S->getStmtClass()) {
221 case Stmt::ConditionalOperatorClass: {
222 ConditionalOperator* C = cast<ConditionalOperator>(S);
223
224 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
225 ConfluenceBlock->appendStmt(C);
226 FinishBlock(ConfluenceBlock);
227
228 Succ = ConfluenceBlock;
229 Block = NULL;
230 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000231 FinishBlock(LHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000232
233 Succ = ConfluenceBlock;
234 Block = NULL;
235 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000236 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000237
238 Block = createBlock(false);
239 Block->addSuccessor(LHSBlock);
240 Block->addSuccessor(RHSBlock);
241 Block->setTerminator(C);
242 return addStmt(C->getCond());
243 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000244
245 case Stmt::ChooseExprClass: {
246 ChooseExpr* C = cast<ChooseExpr>(S);
247
248 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
249 ConfluenceBlock->appendStmt(C);
250 FinishBlock(ConfluenceBlock);
251
252 Succ = ConfluenceBlock;
253 Block = NULL;
254 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000255 FinishBlock(LHSBlock);
256
Ted Kremenek49a436d2007-08-31 17:03:41 +0000257 Succ = ConfluenceBlock;
258 Block = NULL;
259 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000260 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000261
262 Block = createBlock(false);
263 Block->addSuccessor(LHSBlock);
264 Block->addSuccessor(RHSBlock);
265 Block->setTerminator(C);
266 return addStmt(C->getCond());
267 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000268
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000269 case Stmt::DeclStmtClass:
270 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
271 Block->appendStmt(S);
272 return WalkAST_VisitVarDecl(V);
273 }
274 else return Block;
Ted Kremenek15c27a82007-08-28 18:30:10 +0000275
Ted Kremenek19bb3562007-08-28 19:26:49 +0000276 case Stmt::AddrLabelExprClass: {
277 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
278 AddressTakenLabels.insert(A->getLabel());
279
280 if (AlwaysAddStmt) Block->appendStmt(S);
281 return Block;
282 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000283
284 case Stmt::CallExprClass:
285 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000286
Ted Kremenek15c27a82007-08-28 18:30:10 +0000287 case Stmt::StmtExprClass:
288 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000289
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000290 case Stmt::BinaryOperatorClass: {
291 BinaryOperator* B = cast<BinaryOperator>(S);
292
293 if (B->isLogicalOp()) { // && or ||
294 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
295 ConfluenceBlock->appendStmt(B);
296 FinishBlock(ConfluenceBlock);
297
298 // create the block evaluating the LHS
299 CFGBlock* LHSBlock = createBlock(false);
300 LHSBlock->addSuccessor(ConfluenceBlock);
301 LHSBlock->setTerminator(B);
302
303 // create the block evaluating the RHS
304 Succ = ConfluenceBlock;
305 Block = NULL;
306 CFGBlock* RHSBlock = Visit(B->getRHS());
307 LHSBlock->addSuccessor(RHSBlock);
308
309 // Generate the blocks for evaluating the LHS.
310 Block = LHSBlock;
311 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000312 }
313 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
314 Block->appendStmt(B);
315 addStmt(B->getRHS());
316 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000317 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000318
319 // Fall through to the default case.
320 }
321
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000322 default:
323 if (AlwaysAddStmt) Block->appendStmt(S);
324 return WalkAST_VisitChildren(S);
325 };
326}
327
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000328/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
329/// DeclStmts. Because the initialization code for declarations can
330/// contain arbitrary expressions, we must linearize declarations
331/// to handle arbitrary control-flow induced by those expressions.
332CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
333 // We actually must parse the LAST declaration in a chain of
334 // declarations first, because we are building the CFG in reverse
335 // order.
336 if (Decl* D = V->getNextDeclarator())
337 if (VarDecl* Next = cast<VarDecl>(D))
338 Block = WalkAST_VisitVarDecl(Next);
339
340 if (Expr* E = V->getInit())
341 return addStmt(E);
342
343 assert (Block);
344 return Block;
345}
346
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000347/// WalkAST_VisitChildren - Utility method to call WalkAST on the
348/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000349CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000350 CFGBlock* B = Block;
351 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
352 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000353 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000354
355 return B;
356}
357
Ted Kremenek15c27a82007-08-28 18:30:10 +0000358/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
359/// expressions (a GCC extension).
360CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
361 Block->appendStmt(S);
362 return VisitCompoundStmt(S->getSubStmt());
363}
364
Ted Kremenekf50ec102007-09-11 21:29:43 +0000365/// WalkAST_VisitCallExpr - Utility method to handle function calls that
366/// are nested in expressions. The idea is that each function call should
367/// appear as a distinct statement in the CFGBlock.
368CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
369 Block->appendStmt(C);
370 return WalkAST_VisitChildren(C);
371}
372
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000373/// VisitStmt - Handle statements with no branching control flow.
374CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
375 // We cannot assume that we are in the middle of a basic block, since
376 // the CFG might only be constructed for this single statement. If
377 // we have no current basic block, just create one lazily.
378 if (!Block) Block = createBlock();
379
380 // Simply add the statement to the current block. We actually
381 // insert statements in reverse order; this order is reversed later
382 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000383 addStmt(Statement);
384
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000385 return Block;
386}
387
388CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
389 return Block;
390}
391
392CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
393 // The value returned from this function is the last created CFGBlock
394 // that represents the "entry" point for the translated AST node.
Chris Lattner271f1a62007-09-27 15:15:46 +0000395 CFGBlock* LastBlock = 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000396
397 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
398 E = C->body_rend(); I != E; ++I )
399 // Add the statement to the current block.
400 if (!(LastBlock=Visit(*I)))
401 return NULL;
402
403 return LastBlock;
404}
405
406CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
407 // We may see an if statement in the middle of a basic block, or
408 // it may be the first statement we are processing. In either case,
409 // we create a new basic block. First, we create the blocks for
410 // the then...else statements, and then we create the block containing
411 // the if statement. If we were in the middle of a block, we
412 // stop processing that block and reverse its statements. That block
413 // is then the implicit successor for the "then" and "else" clauses.
414
415 // The block we were proccessing is now finished. Make it the
416 // successor block.
417 if (Block) {
418 Succ = Block;
419 FinishBlock(Block);
420 }
421
422 // Process the false branch. NULL out Block so that the recursive
423 // call to Visit will create a new basic block.
424 // Null out Block so that all successor
425 CFGBlock* ElseBlock = Succ;
426
427 if (Stmt* Else = I->getElse()) {
428 SaveAndRestore<CFGBlock*> sv(Succ);
429
430 // NULL out Block so that the recursive call to Visit will
431 // create a new basic block.
432 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000433 ElseBlock = Visit(Else);
434
435 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
436 ElseBlock = sv.get();
437 else if (Block)
438 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000439 }
440
441 // Process the true branch. NULL out Block so that the recursive
442 // call to Visit will create a new basic block.
443 // Null out Block so that all successor
444 CFGBlock* ThenBlock;
445 {
446 Stmt* Then = I->getThen();
447 assert (Then);
448 SaveAndRestore<CFGBlock*> sv(Succ);
449 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000450 ThenBlock = Visit(Then);
451
452 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
453 ThenBlock = sv.get();
454 else if (Block)
455 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000456 }
457
458 // Now create a new block containing the if statement.
459 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000460
461 // Set the terminator of the new block to the If statement.
462 Block->setTerminator(I);
463
464 // Now add the successors.
465 Block->addSuccessor(ThenBlock);
466 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000467
468 // Add the condition as the last statement in the new block. This
469 // may create new blocks as the condition may contain control-flow. Any
470 // newly created blocks will be pointed to be "Block".
471 return addStmt(I->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000472}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000473
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000474
475CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
476 // If we were in the middle of a block we stop processing that block
477 // and reverse its statements.
478 //
479 // NOTE: If a "return" appears in the middle of a block, this means
480 // that the code afterwards is DEAD (unreachable). We still
481 // keep a basic block for that code; a simple "mark-and-sweep"
482 // from the entry block will be able to report such dead
483 // blocks.
484 if (Block) FinishBlock(Block);
485
486 // Create the new block.
487 Block = createBlock(false);
488
489 // The Exit block is the only successor.
490 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000491
492 // Add the return statement to the block. This may create new blocks
493 // if R contains control-flow (short-circuit operations).
494 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000495}
496
497CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
498 // Get the block of the labeled statement. Add it to our map.
499 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000500
501 if (!LabelBlock) // This can happen when the body is empty, i.e.
502 LabelBlock=createBlock(); // scopes that only contains NullStmts.
503
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000504 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
505 LabelMap[ L ] = LabelBlock;
506
507 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000508 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000509 // label (and we have already processed the substatement) there is no
510 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000511 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000512 FinishBlock(LabelBlock);
513
514 // We set Block to NULL to allow lazy creation of a new block
515 // (if necessary);
516 Block = NULL;
517
518 // This block is now the implicit successor of other blocks.
519 Succ = LabelBlock;
520
521 return LabelBlock;
522}
523
524CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
525 // Goto is a control-flow statement. Thus we stop processing the
526 // current block and create a new one.
527 if (Block) FinishBlock(Block);
528 Block = createBlock(false);
529 Block->setTerminator(G);
530
531 // If we already know the mapping to the label block add the
532 // successor now.
533 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
534
535 if (I == LabelMap.end())
536 // We will need to backpatch this block later.
537 BackpatchBlocks.push_back(Block);
538 else
539 Block->addSuccessor(I->second);
540
541 return Block;
542}
543
544CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
545 // "for" is a control-flow statement. Thus we stop processing the
546 // current block.
547
548 CFGBlock* LoopSuccessor = NULL;
549
550 if (Block) {
551 FinishBlock(Block);
552 LoopSuccessor = Block;
553 }
554 else LoopSuccessor = Succ;
555
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000556 // Because of short-circuit evaluation, the condition of the loop
557 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
558 // blocks that evaluate the condition.
559 CFGBlock* ExitConditionBlock = createBlock(false);
560 CFGBlock* EntryConditionBlock = ExitConditionBlock;
561
562 // Set the terminator for the "exit" condition block.
563 ExitConditionBlock->setTerminator(F);
564
565 // Now add the actual condition to the condition block. Because the
566 // condition itself may contain control-flow, new blocks may be created.
567 if (Stmt* C = F->getCond()) {
568 Block = ExitConditionBlock;
569 EntryConditionBlock = addStmt(C);
570 if (Block) FinishBlock(EntryConditionBlock);
571 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000572
573 // The condition block is the implicit successor for the loop body as
574 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000575 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000576
577 // Now create the loop body.
578 {
579 assert (F->getBody());
580
581 // Save the current values for Block, Succ, and continue and break targets
582 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
583 save_continue(ContinueTargetBlock),
584 save_break(BreakTargetBlock);
585
586 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000587 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000588
589 // All breaks should go to the code following the loop.
590 BreakTargetBlock = LoopSuccessor;
591
Ted Kremenekaf603f72007-08-30 18:39:40 +0000592 // Create a new block to contain the (bottom) of the loop body.
593 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000594
595 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000596 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000597
598 // Now populate the body block, and in the process create new blocks
599 // as we walk the body of the loop.
600 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000601
602 if (!BodyBlock)
603 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
604 else if (Block)
605 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000606
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000607 // This new body block is a successor to our "exit" condition block.
608 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000609 }
610
611 // Link up the condition block with the code that follows the loop.
612 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000613 ExitConditionBlock->addSuccessor(LoopSuccessor);
614
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000615 // If the loop contains initialization, create a new block for those
616 // statements. This block can also contain statements that precede
617 // the loop.
618 if (Stmt* I = F->getInit()) {
619 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000620 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000621 }
622 else {
623 // There is no loop initialization. We are thus basically a while
624 // loop. NULL out Block to force lazy block construction.
625 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000626 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000627 }
628}
629
630CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
631 // "while" is a control-flow statement. Thus we stop processing the
632 // current block.
633
634 CFGBlock* LoopSuccessor = NULL;
635
636 if (Block) {
637 FinishBlock(Block);
638 LoopSuccessor = Block;
639 }
640 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000641
642 // Because of short-circuit evaluation, the condition of the loop
643 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
644 // blocks that evaluate the condition.
645 CFGBlock* ExitConditionBlock = createBlock(false);
646 CFGBlock* EntryConditionBlock = ExitConditionBlock;
647
648 // Set the terminator for the "exit" condition block.
649 ExitConditionBlock->setTerminator(W);
650
651 // Now add the actual condition to the condition block. Because the
652 // condition itself may contain control-flow, new blocks may be created.
653 // Thus we update "Succ" after adding the condition.
654 if (Stmt* C = W->getCond()) {
655 Block = ExitConditionBlock;
656 EntryConditionBlock = addStmt(C);
657 if (Block) FinishBlock(EntryConditionBlock);
658 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000659
660 // The condition block is the implicit successor for the loop body as
661 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000662 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000663
664 // Process the loop body.
665 {
666 assert (W->getBody());
667
668 // Save the current values for Block, Succ, and continue and break targets
669 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
670 save_continue(ContinueTargetBlock),
671 save_break(BreakTargetBlock);
672
673 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000674 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000675
676 // All breaks should go to the code following the loop.
677 BreakTargetBlock = LoopSuccessor;
678
679 // NULL out Block to force lazy instantiation of blocks for the body.
680 Block = NULL;
681
682 // Create the body. The returned block is the entry to the loop body.
683 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000684
685 if (!BodyBlock)
686 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
687 else if (Block)
688 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000689
690 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000691 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000692 }
693
694 // Link up the condition block with the code that follows the loop.
695 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000696 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000697
698 // There can be no more statements in the condition block
699 // since we loop back to this block. NULL out Block to force
700 // lazy creation of another block.
701 Block = NULL;
702
703 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000704 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000705}
706
707CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
708 // "do...while" is a control-flow statement. Thus we stop processing the
709 // current block.
710
711 CFGBlock* LoopSuccessor = NULL;
712
713 if (Block) {
714 FinishBlock(Block);
715 LoopSuccessor = Block;
716 }
717 else LoopSuccessor = Succ;
718
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000719 // Because of short-circuit evaluation, the condition of the loop
720 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
721 // blocks that evaluate the condition.
722 CFGBlock* ExitConditionBlock = createBlock(false);
723 CFGBlock* EntryConditionBlock = ExitConditionBlock;
724
725 // Set the terminator for the "exit" condition block.
726 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000727
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000728 // Now add the actual condition to the condition block. Because the
729 // condition itself may contain control-flow, new blocks may be created.
730 if (Stmt* C = D->getCond()) {
731 Block = ExitConditionBlock;
732 EntryConditionBlock = addStmt(C);
733 if (Block) FinishBlock(EntryConditionBlock);
734 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000735
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000736 // The condition block is the implicit successor for the loop body as
737 // well as any code above the loop.
738 Succ = EntryConditionBlock;
739
740
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000741 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000742 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000743 {
744 assert (D->getBody());
745
746 // Save the current values for Block, Succ, and continue and break targets
747 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
748 save_continue(ContinueTargetBlock),
749 save_break(BreakTargetBlock);
750
751 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000752 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000753
754 // All breaks should go to the code following the loop.
755 BreakTargetBlock = LoopSuccessor;
756
757 // NULL out Block to force lazy instantiation of blocks for the body.
758 Block = NULL;
759
760 // Create the body. The returned block is the entry to the loop body.
761 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000762
Ted Kremenekaf603f72007-08-30 18:39:40 +0000763 if (!BodyBlock)
764 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
765 else if (Block)
766 FinishBlock(BodyBlock);
767
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000768 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000769 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000770 }
771
772 // Link up the condition block with the code that follows the loop.
773 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000774 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000775
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000776 // There can be no more statements in the body block(s)
777 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000778 // lazy creation of another block.
779 Block = NULL;
780
781 // Return the loop body, which is the dominating block for the loop.
782 return BodyBlock;
783}
784
785CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
786 // "continue" is a control-flow statement. Thus we stop processing the
787 // current block.
788 if (Block) FinishBlock(Block);
789
790 // Now create a new block that ends with the continue statement.
791 Block = createBlock(false);
792 Block->setTerminator(C);
793
794 // If there is no target for the continue, then we are looking at an
795 // incomplete AST. Handle this by not registering a successor.
796 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
797
798 return Block;
799}
800
801CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
802 // "break" is a control-flow statement. Thus we stop processing the
803 // current block.
804 if (Block) FinishBlock(Block);
805
806 // Now create a new block that ends with the continue statement.
807 Block = createBlock(false);
808 Block->setTerminator(B);
809
810 // If there is no target for the break, then we are looking at an
811 // incomplete AST. Handle this by not registering a successor.
812 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
813
814 return Block;
815}
816
817CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
818 // "switch" is a control-flow statement. Thus we stop processing the
819 // current block.
820 CFGBlock* SwitchSuccessor = NULL;
821
822 if (Block) {
823 FinishBlock(Block);
824 SwitchSuccessor = Block;
825 }
826 else SwitchSuccessor = Succ;
827
828 // Save the current "switch" context.
829 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
830 save_break(BreakTargetBlock);
831
832 // Create a new block that will contain the switch statement.
833 SwitchTerminatedBlock = createBlock(false);
834
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000835 // Now process the switch body. The code after the switch is the implicit
836 // successor.
837 Succ = SwitchSuccessor;
838 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000839
840 // When visiting the body, the case statements should automatically get
841 // linked up to the switch. We also don't keep a pointer to the body,
842 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000843 assert (S->getBody() && "switch must contain a non-NULL body");
844 Block = NULL;
845 CFGBlock *BodyBlock = Visit(S->getBody());
846 if (Block) FinishBlock(BodyBlock);
847
848 // Add the terminator and condition in the switch block.
849 SwitchTerminatedBlock->setTerminator(S);
850 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000851 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000852 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000853}
854
855CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
856 // A SwitchCase is either a "default" or "case" statement. We handle
857 // both in the same way. They are essentially labels, so they are the
858 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000859
860 if (S->getSubStmt()) Visit(S->getSubStmt());
861 CFGBlock* CaseBlock = Block;
862 if (!CaseBlock) CaseBlock = createBlock();
863
Ted Kremenek9cffe732007-08-29 23:20:49 +0000864 // Cases/Default statements partition block, so this is the top of
865 // the basic block we were processing (the case/default is the label).
866 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000867 FinishBlock(CaseBlock);
868
869 // Add this block to the list of successors for the block with the
870 // switch statement.
871 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
872
873 // We set Block to NULL to allow lazy creation of a new block (if necessary)
874 Block = NULL;
875
876 // This block is now the implicit successor of other blocks.
877 Succ = CaseBlock;
878
879 return CaseBlock;
880}
881
Ted Kremenek19bb3562007-08-28 19:26:49 +0000882CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
883 // Lazily create the indirect-goto dispatch block if there isn't one
884 // already.
885 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
886
887 if (!IBlock) {
888 IBlock = createBlock(false);
889 cfg->setIndirectGotoBlock(IBlock);
890 }
891
892 // IndirectGoto is a control-flow statement. Thus we stop processing the
893 // current block and create a new one.
894 if (Block) FinishBlock(Block);
895 Block = createBlock(false);
896 Block->setTerminator(I);
897 Block->addSuccessor(IBlock);
898 return addStmt(I->getTarget());
899}
900
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000901
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000902} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000903
904/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
905/// block has no successors or predecessors. If this is the first block
906/// created in the CFG, it is automatically set to be the Entry and Exit
907/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000908CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000909 bool first_block = begin() == end();
910
911 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000912 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000913
914 // If this is the first block, set it as the Entry and Exit.
915 if (first_block) Entry = Exit = &front();
916
917 // Return the block.
918 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000919}
920
Ted Kremenek026473c2007-08-23 16:51:22 +0000921/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
922/// CFG is returned to the caller.
923CFG* CFG::buildCFG(Stmt* Statement) {
924 CFGBuilder Builder;
925 return Builder.buildCFG(Statement);
926}
927
928/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000929void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
930
Ted Kremenek63f58872007-10-01 19:33:33 +0000931//===----------------------------------------------------------------------===//
932// CFG: Queries for BlkExprs.
933//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +0000934
Ted Kremenek63f58872007-10-01 19:33:33 +0000935namespace {
936 typedef llvm::DenseMap<const Expr*,unsigned> BlkExprMapTy;
937}
938
939static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
940 BlkExprMapTy* M = new BlkExprMapTy();
941
942 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
943 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
944 if (const Expr* E = dyn_cast<Expr>(*BI))
945 (*M)[E] = M->size();
946
947 return M;
948}
949
950bool CFG::isBlkExpr(const Stmt* S) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000951 assert (S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000952 if (const Expr* E = dyn_cast<Expr>(S)) return getBlkExprNum(E);
953 else return true; // Statements are by default "block-level expressions."
954}
955
956CFG::BlkExprNumTy CFG::getBlkExprNum(const Expr* E) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000957 assert(E != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000958 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
959
960 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
961 BlkExprMapTy::iterator I = M->find(E);
962
963 if (I == M->end()) return CFG::BlkExprNumTy();
964 else return CFG::BlkExprNumTy(I->second);
965}
966
967unsigned CFG::getNumBlkExprs() {
968 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
969 return M->size();
970 else {
971 // We assume callers interested in the number of BlkExprs will want
972 // the map constructed if it doesn't already exist.
973 BlkExprMap = (void*) PopulateBlkExprMap(*this);
974 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
975 }
976}
977
978CFG::~CFG() {
979 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
980}
981
Ted Kremenek7dba8602007-08-29 21:56:09 +0000982//===----------------------------------------------------------------------===//
983// CFG pretty printing
984//===----------------------------------------------------------------------===//
985
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000986namespace {
987
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000988class StmtPrinterHelper : public PrinterHelper {
989
Ted Kremenek42a509f2007-08-31 21:30:12 +0000990 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
991 StmtMapTy StmtMap;
992 signed CurrentBlock;
993 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000994
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000995public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000996
Ted Kremenek42a509f2007-08-31 21:30:12 +0000997 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
998 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
999 unsigned j = 1;
1000 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1001 BI != BEnd; ++BI, ++j )
1002 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1003 }
1004 }
1005
1006 virtual ~StmtPrinterHelper() {}
1007
1008 void setBlockID(signed i) { CurrentBlock = i; }
1009 void setStmtID(unsigned i) { CurrentStmt = i; }
1010
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001011 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1012
1013 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001014
1015 if (I == StmtMap.end())
1016 return false;
1017
1018 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1019 && I->second.second == CurrentStmt)
1020 return false;
1021
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001022 OS << "[B" << I->second.first << "." << I->second.second << "]";
1023 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001024 }
1025};
1026
1027class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek805e9a82007-08-31 21:49:40 +00001028 void >
1029{
Ted Kremenek42a509f2007-08-31 21:30:12 +00001030 std::ostream& OS;
1031 StmtPrinterHelper* Helper;
1032public:
1033 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1034 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001035
1036 void VisitIfStmt(IfStmt* I) {
1037 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001038 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001039 OS << "\n";
1040 }
1041
1042 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001043 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001044
1045 void VisitForStmt(ForStmt* F) {
1046 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001047 if (F->getInit()) OS << "...";
1048 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001049 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001050 OS << "; ";
1051 if (F->getInc()) OS << "...";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001052 OS << ")\n";
1053 }
1054
1055 void VisitWhileStmt(WhileStmt* W) {
1056 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001057 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001058 OS << "\n";
1059 }
1060
1061 void VisitDoStmt(DoStmt* D) {
1062 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001063 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001064 OS << '\n';
1065 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001066
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001067 void VisitSwitchStmt(SwitchStmt* S) {
1068 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001069 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001070 OS << '\n';
1071 }
1072
Ted Kremenek805e9a82007-08-31 21:49:40 +00001073 void VisitConditionalOperator(ConditionalOperator* C) {
1074 C->getCond()->printPretty(OS,Helper);
1075 OS << " ? ... : ...\n";
1076 }
1077
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001078 void VisitChooseExpr(ChooseExpr* C) {
1079 OS << "__builtin_choose_expr( ";
1080 C->getCond()->printPretty(OS,Helper);
1081 OS << " )\n";
1082 }
1083
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001084 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1085 OS << "goto *";
1086 I->getTarget()->printPretty(OS,Helper);
1087 OS << '\n';
1088 }
1089
Ted Kremenek805e9a82007-08-31 21:49:40 +00001090 void VisitBinaryOperator(BinaryOperator* B) {
1091 if (!B->isLogicalOp()) {
1092 VisitExpr(B);
1093 return;
1094 }
1095
1096 B->getLHS()->printPretty(OS,Helper);
1097
1098 switch (B->getOpcode()) {
1099 case BinaryOperator::LOr:
1100 OS << " || ...\n";
1101 return;
1102 case BinaryOperator::LAnd:
1103 OS << " && ...\n";
1104 return;
1105 default:
1106 assert(false && "Invalid logical operator.");
1107 }
1108 }
1109
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001110 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001111 E->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001112 OS << '\n';
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001113 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001114};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001115
1116
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001117void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1118 if (Helper) {
1119 // special printing for statement-expressions.
1120 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1121 CompoundStmt* Sub = SE->getSubStmt();
1122
1123 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001124 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001125 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001126 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001127 return;
1128 }
1129 }
1130
1131 // special printing for comma expressions.
1132 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1133 if (B->getOpcode() == BinaryOperator::Comma) {
1134 OS << "... , ";
1135 Helper->handledStmt(B->getRHS(),OS);
1136 OS << '\n';
1137 return;
1138 }
1139 }
1140 }
1141
1142 S->printPretty(OS, Helper);
1143
1144 // Expressions need a newline.
1145 if (isa<Expr>(S)) OS << '\n';
1146}
1147
Ted Kremenek42a509f2007-08-31 21:30:12 +00001148void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1149 StmtPrinterHelper* Helper, bool print_edges) {
1150
1151 if (Helper) Helper->setBlockID(B.getBlockID());
1152
Ted Kremenek7dba8602007-08-29 21:56:09 +00001153 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001154 OS << "\n [ B" << B.getBlockID();
1155
1156 if (&B == &cfg->getEntry())
1157 OS << " (ENTRY) ]\n";
1158 else if (&B == &cfg->getExit())
1159 OS << " (EXIT) ]\n";
1160 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001161 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001162 else
1163 OS << " ]\n";
1164
Ted Kremenek9cffe732007-08-29 23:20:49 +00001165 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001166 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1167
1168 if (print_edges)
1169 OS << " ";
1170
Ted Kremenek9cffe732007-08-29 23:20:49 +00001171 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1172 OS << L->getName();
1173 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1174 OS << "case ";
1175 C->getLHS()->printPretty(OS);
1176 if (C->getRHS()) {
1177 OS << " ... ";
1178 C->getRHS()->printPretty(OS);
1179 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001180 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001181 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001182 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001183 else
1184 assert(false && "Invalid label statement in CFGBlock.");
1185
Ted Kremenek9cffe732007-08-29 23:20:49 +00001186 OS << ":\n";
1187 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001188
Ted Kremenekfddd5182007-08-21 21:42:03 +00001189 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001190 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001191
1192 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1193 I != E ; ++I, ++j ) {
1194
Ted Kremenek9cffe732007-08-29 23:20:49 +00001195 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001196 if (print_edges)
1197 OS << " ";
1198
1199 OS << std::setw(3) << j << ": ";
1200
1201 if (Helper)
1202 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001203
1204 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001205 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001206
Ted Kremenek9cffe732007-08-29 23:20:49 +00001207 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001208 if (B.getTerminator()) {
1209 if (print_edges)
1210 OS << " ";
1211
Ted Kremenek9cffe732007-08-29 23:20:49 +00001212 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001213
1214 if (Helper) Helper->setBlockID(-1);
1215
1216 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1217 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenekfddd5182007-08-21 21:42:03 +00001218 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001219
Ted Kremenek9cffe732007-08-29 23:20:49 +00001220 if (print_edges) {
1221 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001222 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001223 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001224
Ted Kremenek42a509f2007-08-31 21:30:12 +00001225 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1226 I != E; ++I, ++i) {
1227
1228 if (i == 8 || (i-8) == 0)
1229 OS << "\n ";
1230
Ted Kremenek9cffe732007-08-29 23:20:49 +00001231 OS << " B" << (*I)->getBlockID();
1232 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001233
1234 OS << '\n';
1235
1236 // Print the successors of this block.
1237 OS << " Successors (" << B.succ_size() << "):";
1238 i = 0;
1239
1240 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1241 I != E; ++I, ++i) {
1242
1243 if (i == 8 || (i-8) % 10 == 0)
1244 OS << "\n ";
1245
1246 OS << " B" << (*I)->getBlockID();
1247 }
1248
Ted Kremenek9cffe732007-08-29 23:20:49 +00001249 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001250 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001251}
1252
1253} // end anonymous namespace
1254
1255/// dump - A simple pretty printer of a CFG that outputs to stderr.
1256void CFG::dump() const { print(std::cerr); }
1257
1258/// print - A simple pretty printer of a CFG that outputs to an ostream.
1259void CFG::print(std::ostream& OS) const {
1260
1261 StmtPrinterHelper Helper(this);
1262
1263 // Print the entry block.
1264 print_block(OS, this, getEntry(), &Helper, true);
1265
1266 // Iterate through the CFGBlocks and print them one by one.
1267 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1268 // Skip the entry block, because we already printed it.
1269 if (&(*I) == &getEntry() || &(*I) == &getExit())
1270 continue;
1271
1272 print_block(OS, this, *I, &Helper, true);
1273 }
1274
1275 // Print the exit block.
1276 print_block(OS, this, getExit(), &Helper, true);
1277}
1278
1279/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1280void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1281
1282/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1283/// Generally this will only be called from CFG::print.
1284void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1285 StmtPrinterHelper Helper(cfg);
1286 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001287}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001288
1289//===----------------------------------------------------------------------===//
1290// CFG Graphviz Visualization
1291//===----------------------------------------------------------------------===//
1292
Ted Kremenek42a509f2007-08-31 21:30:12 +00001293
1294#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001295static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001296#endif
1297
1298void CFG::viewCFG() const {
1299#ifndef NDEBUG
1300 StmtPrinterHelper H(this);
1301 GraphHelper = &H;
1302 llvm::ViewGraph(this,"CFG");
1303 GraphHelper = NULL;
1304#else
1305 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001306 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001307#endif
1308}
1309
Ted Kremenek7dba8602007-08-29 21:56:09 +00001310namespace llvm {
1311template<>
1312struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1313 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1314
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001315#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001316 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001317 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001318 std::string OutStr = Out.str();
1319
1320 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1321
1322 // Process string output to make it nicer...
1323 for (unsigned i = 0; i != OutStr.length(); ++i)
1324 if (OutStr[i] == '\n') { // Left justify
1325 OutStr[i] = '\\';
1326 OutStr.insert(OutStr.begin()+i+1, 'l');
1327 }
1328
1329 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001330#else
1331 return "";
1332#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001333 }
1334};
1335} // end namespace llvm