blob: b11162e6154515a64e601a089b193f29077dddaa [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
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 Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000019#include <iostream>
20#include <iomanip>
21#include <algorithm>
22using namespace clang;
23
24namespace {
25
Ted Kremenekd6e50602007-08-23 21:26:19 +000026// SaveAndRestore - A utility class that uses RIIA to save and restore
27// the value of a variable.
28template<typename T>
29struct SaveAndRestore {
30 SaveAndRestore(T& x) : X(x), old_value(x) {}
31 ~SaveAndRestore() { X = old_value; }
32
33 T& X;
34 T old_value;
35};
Ted Kremenek97f75312007-08-21 21:42:03 +000036
37/// CFGBuilder - This class is implements CFG construction from an AST.
38/// The builder is stateful: an instance of the builder should be used to only
39/// construct a single CFG.
40///
41/// Example usage:
42///
43/// CFGBuilder builder;
44/// CFG* cfg = builder.BuildAST(stmt1);
45///
Ted Kremenek95e854d2007-08-21 22:06:14 +000046/// CFG construction is done via a recursive walk of an AST.
47/// We actually parse the AST in reverse order so that the successor
48/// of a basic block is constructed prior to its predecessor. This
49/// allows us to nicely capture implicit fall-throughs without extra
50/// basic blocks.
51///
52class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000053 CFG* cfg;
54 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000055 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000056 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000057 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000058 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000059 unsigned NumBlocks;
60
Ted Kremenekc5de2222007-08-21 23:26:17 +000061 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
62 LabelMapTy LabelMap;
63
Ted Kremenekf5392b72007-08-22 15:40:58 +000064 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000065 BackpatchBlocksTy BackpatchBlocks;
66
Ted Kremenek97f75312007-08-21 21:42:03 +000067public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000068 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000069 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremeneke809ebf2007-08-23 18:43:24 +000070 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000071 NumBlocks(0) {
72 // Create an empty CFG.
73 cfg = new CFG();
74 }
75
76 ~CFGBuilder() { delete cfg; }
Ted Kremenekd8313202007-08-22 18:22:34 +000077
Ted Kremenekbec06e82007-08-22 21:05:42 +000078 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
Ted Kremenek97f75312007-08-21 21:42:03 +000079 /// represent an arbitrary statement. Examples include a single expression
80 /// or a function body (compound statement). The ownership of the returned
81 /// CFG is transferred to the caller. If CFG construction fails, this method
82 /// returns NULL.
Ted Kremenek4db5b452007-08-23 16:51:22 +000083 CFG* buildCFG(Stmt* Statement) {
Ted Kremenek97f75312007-08-21 21:42:03 +000084 if (!Statement) return NULL;
85
Ted Kremenek4db5b452007-08-23 16:51:22 +000086 // Create an empty block that will serve as the exit block for the CFG.
87 // Since this is the first block added to the CFG, it will be implicitly
88 // registered as the exit block.
Ted Kremenek97f75312007-08-21 21:42:03 +000089 Block = createBlock();
Ted Kremenek4db5b452007-08-23 16:51:22 +000090 assert (Block == &cfg->getExit());
Ted Kremenek97f75312007-08-21 21:42:03 +000091
92 // Visit the statements and create the CFG.
Ted Kremenek95e854d2007-08-21 22:06:14 +000093 if (CFGBlock* B = Visit(Statement)) {
Ted Kremenekd8313202007-08-22 18:22:34 +000094 // Finalize the last constructed block. This usually involves
95 // reversing the order of the statements in the block.
96 FinishBlock(B);
Ted Kremenekbec06e82007-08-22 21:05:42 +000097 cfg->setEntry(B);
Ted Kremenekc5de2222007-08-21 23:26:17 +000098
99 // Backpatch the gotos whose label -> block mappings we didn't know
100 // when we encountered them.
101 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
102 E = BackpatchBlocks.end(); I != E; ++I ) {
103
104 CFGBlock* B = *I;
105 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
106 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
107
Ted Kremenek7372bb22007-08-23 17:29:58 +0000108 // If there is no target for the goto, then we are looking at an
109 // incomplete AST. Handle this by not registering a successor.
110 if (LI == LabelMap.end()) continue;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000111
112 B->addSuccessor(LI->second);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000113 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000114
Ted Kremenek97f75312007-08-21 21:42:03 +0000115 // NULL out cfg so that repeated calls
116 CFG* t = cfg;
117 cfg = NULL;
118 return t;
119 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000120 else return NULL;
Ted Kremenek97f75312007-08-21 21:42:03 +0000121 }
Ted Kremenek95e854d2007-08-21 22:06:14 +0000122
Ted Kremenek97f75312007-08-21 21:42:03 +0000123 // createBlock - Used to lazily create blocks that are connected
124 // to the current (global) succcessor.
125 CFGBlock* createBlock( bool add_successor = true ) {
126 CFGBlock* B = cfg->createBlock(NumBlocks++);
127 if (add_successor && Succ) B->addSuccessor(Succ);
128 return B;
129 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000130
131 // FinishBlock - When the last statement has been added to the block,
132 // usually we must reverse the statements because they have been inserted
133 // in reverse order. When processing labels, however, there are cases
134 // in the recursion where we may have already reversed the statements
135 // in a block. This method safely tidies up a block: if the block
136 // has a label at the front, it has already been reversed. Otherwise,
137 // we reverse it.
138 void FinishBlock(CFGBlock* B) {
139 assert (B);
140 CFGBlock::iterator I = B->begin();
141 if (I != B->end()) {
142 Stmt* S = *I;
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000143
144 if (isa<LabelStmt>(S) || isa<SwitchCase>(S))
145 return;
146
147 B->reverseStmts();
Ted Kremenekd8313202007-08-22 18:22:34 +0000148 }
149 }
Ted Kremenek97f75312007-08-21 21:42:03 +0000150
Ted Kremenek95e854d2007-08-21 22:06:14 +0000151 /// Here we handle statements with no branching control flow.
152 CFGBlock* VisitStmt(Stmt* Statement) {
153 // We cannot assume that we are in the middle of a basic block, since
154 // the CFG might only be constructed for this single statement. If
155 // we have no current basic block, just create one lazily.
156 if (!Block) Block = createBlock();
157
158 // Simply add the statement to the current block. We actually
159 // insert statements in reverse order; this order is reversed later
160 // when processing the containing element in the AST.
161 Block->appendStmt(Statement);
Ted Kremenek97f75312007-08-21 21:42:03 +0000162
163 return Block;
164 }
165
Ted Kremenekd8313202007-08-22 18:22:34 +0000166 CFGBlock* VisitNullStmt(NullStmt* Statement) {
167 return Block;
168 }
169
Ted Kremenek95e854d2007-08-21 22:06:14 +0000170 CFGBlock* VisitCompoundStmt(CompoundStmt* C) {
171 // The value returned from this function is the last created CFGBlock
172 // that represents the "entry" point for the translated AST node.
Ted Kremenekd8313202007-08-22 18:22:34 +0000173 CFGBlock* LastBlock;
174
Ted Kremenek95e854d2007-08-21 22:06:14 +0000175 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
Ted Kremenekd8313202007-08-22 18:22:34 +0000176 E = C->body_rend(); I != E; ++I )
Ted Kremenek95e854d2007-08-21 22:06:14 +0000177 // Add the statement to the current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000178 if (!(LastBlock=Visit(*I)))
179 return NULL;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000180
Ted Kremenekd8313202007-08-22 18:22:34 +0000181 return LastBlock;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000182 }
183
184 CFGBlock* VisitIfStmt(IfStmt* I) {
185
186 // We may see an if statement in the middle of a basic block, or
187 // it may be the first statement we are processing. In either case,
188 // we create a new basic block. First, we create the blocks for
189 // the then...else statements, and then we create the block containing
190 // the if statement. If we were in the middle of a block, we
191 // stop processing that block and reverse its statements. That block
192 // is then the implicit successor for the "then" and "else" clauses.
193
194 // The block we were proccessing is now finished. Make it the
195 // successor block.
196 if (Block) {
197 Succ = Block;
Ted Kremenekd8313202007-08-22 18:22:34 +0000198 FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000199 }
200
201 // Process the false branch. NULL out Block so that the recursive
202 // call to Visit will create a new basic block.
203 // Null out Block so that all successor
204 CFGBlock* ElseBlock = Succ;
205
206 if (Stmt* Else = I->getElse()) {
207 SaveAndRestore<CFGBlock*> sv(Succ);
208
209 // NULL out Block so that the recursive call to Visit will
210 // create a new basic block.
211 Block = NULL;
212 ElseBlock = Visit(Else);
213 if (!ElseBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000214 FinishBlock(ElseBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000215 }
216
217 // Process the true branch. NULL out Block so that the recursive
218 // call to Visit will create a new basic block.
219 // Null out Block so that all successor
220 CFGBlock* ThenBlock;
221 {
222 Stmt* Then = I->getThen();
223 assert (Then);
224 SaveAndRestore<CFGBlock*> sv(Succ);
225 Block = NULL;
226 ThenBlock = Visit(Then);
227 if (!ThenBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000228 FinishBlock(ThenBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000229 }
230
231 // Now create a new block containing the if statement.
232 Block = createBlock(false);
233
234 // Add the condition as the last statement in the new block.
235 Block->appendStmt(I->getCond());
236
237 // Set the terminator of the new block to the If statement.
238 Block->setTerminator(I);
239
240 // Now add the successors.
241 Block->addSuccessor(ThenBlock);
242 Block->addSuccessor(ElseBlock);
243
244 return Block;
245 }
246
247 CFGBlock* VisitReturnStmt(ReturnStmt* R) {
248 // If we were in the middle of a block we stop processing that block
249 // and reverse its statements.
250 //
251 // NOTE: If a "return" appears in the middle of a block, this means
252 // that the code afterwards is DEAD (unreachable). We still
253 // keep a basic block for that code; a simple "mark-and-sweep"
254 // from the entry block will be able to report such dead
255 // blocks.
Ted Kremenekd8313202007-08-22 18:22:34 +0000256 if (Block) FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000257
258 // Create the new block.
259 Block = createBlock(false);
260
261 // The Exit block is the only successor.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000262 Block->addSuccessor(&cfg->getExit());
Ted Kremenek95e854d2007-08-21 22:06:14 +0000263
Ted Kremenek4db5b452007-08-23 16:51:22 +0000264 // Add the return statement to the block.
Ted Kremenek95e854d2007-08-21 22:06:14 +0000265 Block->appendStmt(R);
266
Ted Kremenek4db5b452007-08-23 16:51:22 +0000267 // Also add the return statement as the terminator.
268 Block->setTerminator(R);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000269
270 return Block;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000271 }
272
273 CFGBlock* VisitLabelStmt(LabelStmt* L) {
274 // Get the block of the labeled statement. Add it to our map.
275 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenekd8313202007-08-22 18:22:34 +0000276 assert (LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000277
278 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
279 LabelMap[ L ] = LabelBlock;
280
281 // Labels partition blocks, so this is the end of the basic block
282 // we were processing (the label is the first statement).
Ted Kremenekd8313202007-08-22 18:22:34 +0000283 LabelBlock->appendStmt(L);
284 FinishBlock(LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000285
286 // We set Block to NULL to allow lazy creation of a new block
287 // (if necessary);
288 Block = NULL;
289
290 // This block is now the implicit successor of other blocks.
291 Succ = LabelBlock;
292
293 return LabelBlock;
294 }
295
296 CFGBlock* VisitGotoStmt(GotoStmt* G) {
297 // Goto is a control-flow statement. Thus we stop processing the
298 // current block and create a new one.
Ted Kremenekd8313202007-08-22 18:22:34 +0000299 if (Block) FinishBlock(Block);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000300 Block = createBlock(false);
301 Block->setTerminator(G);
302
303 // If we already know the mapping to the label block add the
304 // successor now.
305 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
306
307 if (I == LabelMap.end())
308 // We will need to backpatch this block later.
309 BackpatchBlocks.push_back(Block);
310 else
311 Block->addSuccessor(I->second);
312
313 return Block;
314 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000315
316 CFGBlock* VisitForStmt(ForStmt* F) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000317 // "for" is a control-flow statement. Thus we stop processing the
Ted Kremenekd8313202007-08-22 18:22:34 +0000318 // current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000319
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000320 CFGBlock* LoopSuccessor = NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000321
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000322 if (Block) {
323 FinishBlock(Block);
324 LoopSuccessor = Block;
325 }
326 else LoopSuccessor = Succ;
327
328 // Create the condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000329 CFGBlock* ConditionBlock = createBlock(false);
Ted Kremenekf511d672007-08-22 21:36:54 +0000330 ConditionBlock->setTerminator(F);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000331 if (Stmt* C = F->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekf511d672007-08-22 21:36:54 +0000332
333 // The condition block is the implicit successor for the loop body as
334 // well as any code above the loop.
335 Succ = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000336
337 // Now create the loop body.
338 {
339 assert (F->getBody());
Ted Kremenekf511d672007-08-22 21:36:54 +0000340
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000341 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000342 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000343 save_continue(ContinueTargetBlock),
344 save_break(BreakTargetBlock);
345
Ted Kremenekf511d672007-08-22 21:36:54 +0000346 // All continues within this loop should go to the condition block
347 ContinueTargetBlock = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000348
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000349 // All breaks should go to the code following the loop.
350 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000351
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000352 // Create a new block to contain the (bottom) of the loop body.
Ted Kremenekd8313202007-08-22 18:22:34 +0000353 Block = createBlock();
354
355 // If we have increment code, insert it at the end of the body block.
356 if (Stmt* I = F->getInc()) Block->appendStmt(I);
357
358 // Now populate the body block, and in the process create new blocks
359 // as we walk the body of the loop.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000360 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekd8313202007-08-22 18:22:34 +0000361 assert (BodyBlock);
362 FinishBlock(BodyBlock);
363
364 // This new body block is a successor to our condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000365 ConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd8313202007-08-22 18:22:34 +0000366 }
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000367
Ted Kremenekd8313202007-08-22 18:22:34 +0000368 // Link up the condition block with the code that follows the loop.
369 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000370 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd8313202007-08-22 18:22:34 +0000371
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000372 // If the loop contains initialization, create a new block for those
373 // statements. This block can also contain statements that precede
374 // the loop.
375 if (Stmt* I = F->getInit()) {
376 Block = createBlock();
377 Block->appendStmt(I);
378 return Block;
379 }
380 else {
381 // There is no loop initialization. We are thus basically a while
382 // loop. NULL out Block to force lazy block construction.
383 Block = NULL;
384 return ConditionBlock;
385 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000386 }
Ted Kremenekbec06e82007-08-22 21:05:42 +0000387
388 CFGBlock* VisitWhileStmt(WhileStmt* W) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000389 // "while" is a control-flow statement. Thus we stop processing the
Ted Kremenekbec06e82007-08-22 21:05:42 +0000390 // current block.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000391
392 CFGBlock* LoopSuccessor = NULL;
393
394 if (Block) {
395 FinishBlock(Block);
396 LoopSuccessor = Block;
397 }
398 else LoopSuccessor = Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +0000399
400 // Create the condition block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000401 CFGBlock* ConditionBlock = createBlock(false);
402 ConditionBlock->setTerminator(W);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000403 if (Stmt* C = W->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000404
Ted Kremenekf511d672007-08-22 21:36:54 +0000405 // The condition block is the implicit successor for the loop body as
406 // well as any code above the loop.
407 Succ = ConditionBlock;
408
Ted Kremenekbec06e82007-08-22 21:05:42 +0000409 // Process the loop body.
410 {
411 assert (W->getBody());
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000412
413 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000414 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenekf308d372007-08-22 21:51:58 +0000415 save_continue(ContinueTargetBlock),
416 save_break(BreakTargetBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000417
Ted Kremenekf511d672007-08-22 21:36:54 +0000418 // All continues within this loop should go to the condition block
419 ContinueTargetBlock = ConditionBlock;
420
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000421 // All breaks should go to the code following the loop.
422 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000423
Ted Kremenekf511d672007-08-22 21:36:54 +0000424 // NULL out Block to force lazy instantiation of blocks for the body.
425 Block = NULL;
426
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000427 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekf511d672007-08-22 21:36:54 +0000428 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekbec06e82007-08-22 21:05:42 +0000429 assert (BodyBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000430 FinishBlock(BodyBlock);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000431
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000432 // Add the loop body entry as a successor to the condition.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000433 ConditionBlock->addSuccessor(BodyBlock);
434 }
435
Ted Kremenekf308d372007-08-22 21:51:58 +0000436 // Link up the condition block with the code that follows the loop.
437 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000438 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000439
440 // There can be no more statements in the condition block
441 // since we loop back to this block. NULL out Block to force
442 // lazy creation of another block.
443 Block = NULL;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000444
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000445 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000446 return ConditionBlock;
447 }
448
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000449 CFGBlock* VisitDoStmt(DoStmt* D) {
450 // "do...while" is a control-flow statement. Thus we stop processing the
451 // current block.
452
453 CFGBlock* LoopSuccessor = NULL;
454
455 if (Block) {
456 FinishBlock(Block);
457 LoopSuccessor = Block;
458 }
459 else LoopSuccessor = Succ;
460
461 // Create the condition block.
462 CFGBlock* ConditionBlock = createBlock(false);
463 ConditionBlock->setTerminator(D);
464 if (Stmt* C = D->getCond()) ConditionBlock->appendStmt(C);
465
466 // The condition block is the implicit successor for the loop body.
467 Succ = ConditionBlock;
468
469 CFGBlock* BodyBlock = NULL;
470 // Process the loop body.
471 {
472 assert (D->getBody());
473
474 // Save the current values for Block, Succ, and continue and break targets
475 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
476 save_continue(ContinueTargetBlock),
477 save_break(BreakTargetBlock);
478
479 // All continues within this loop should go to the condition block
480 ContinueTargetBlock = ConditionBlock;
481
482 // All breaks should go to the code following the loop.
483 BreakTargetBlock = LoopSuccessor;
484
485 // NULL out Block to force lazy instantiation of blocks for the body.
486 Block = NULL;
487
488 // Create the body. The returned block is the entry to the loop body.
489 BodyBlock = Visit(D->getBody());
490 assert (BodyBlock);
491 FinishBlock(BodyBlock);
492
493 // Add the loop body entry as a successor to the condition.
494 ConditionBlock->addSuccessor(BodyBlock);
495 }
496
497 // Link up the condition block with the code that follows the loop.
498 // (the false branch).
499 ConditionBlock->addSuccessor(LoopSuccessor);
500
501 // There can be no more statements in the condition block
502 // since we loop back to this block. NULL out Block to force
503 // lazy creation of another block.
504 Block = NULL;
505
506 // Return the loop body, which is the dominating block for the loop.
507 return BodyBlock;
508 }
509
Ted Kremenekf511d672007-08-22 21:36:54 +0000510 CFGBlock* VisitContinueStmt(ContinueStmt* C) {
Ted Kremenekf308d372007-08-22 21:51:58 +0000511 // "continue" is a control-flow statement. Thus we stop processing the
Ted Kremenekf511d672007-08-22 21:36:54 +0000512 // current block.
513 if (Block) FinishBlock(Block);
514
515 // Now create a new block that ends with the continue statement.
516 Block = createBlock(false);
517 Block->setTerminator(C);
518
Ted Kremenek7372bb22007-08-23 17:29:58 +0000519 // If there is no target for the continue, then we are looking at an
520 // incomplete AST. Handle this by not registering a successor.
521 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
Ted Kremenekf511d672007-08-22 21:36:54 +0000522
Ted Kremenekf511d672007-08-22 21:36:54 +0000523 return Block;
524 }
525
Ted Kremenekf308d372007-08-22 21:51:58 +0000526 CFGBlock* VisitBreakStmt(BreakStmt* B) {
527 // "break" is a control-flow statement. Thus we stop processing the
528 // current block.
529 if (Block) FinishBlock(Block);
530
531 // Now create a new block that ends with the continue statement.
532 Block = createBlock(false);
533 Block->setTerminator(B);
534
Ted Kremenek7372bb22007-08-23 17:29:58 +0000535 // If there is no target for the break, then we are looking at an
536 // incomplete AST. Handle this by not registering a successor.
537 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
538
Ted Kremenekf308d372007-08-22 21:51:58 +0000539 return Block;
540 }
541
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000542 CFGBlock* VisitSwitchStmt(SwitchStmt* S) {
543 // "switch" is a control-flow statement. Thus we stop processing the
544 // current block.
545 CFGBlock* SwitchSuccessor = NULL;
546
547 if (Block) {
548 FinishBlock(Block);
549 SwitchSuccessor = Block;
550 }
551 else SwitchSuccessor = Succ;
552
553 // Save the current "switch" context.
554 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
555 save_break(BreakTargetBlock);
556
557 // Create a new block that will contain the switch statement.
558 SwitchTerminatedBlock = createBlock(false);
559
560 // Add the terminator and condition in the switch block.
561 assert (S->getCond() && "switch condition must be non-NULL");
562 SwitchTerminatedBlock->appendStmt(S->getCond());
563 SwitchTerminatedBlock->setTerminator(S);
564
565
566 // Now process the switch body. The code after the switch is the implicit
567 // successor.
568 Succ = SwitchSuccessor;
569 BreakTargetBlock = SwitchSuccessor;
570
571 assert (S->getBody() && "switch must contain a non-NULL body");
572 Block = NULL;
573
574 // When visiting the body, the case statements should automatically get
575 // linked up to the switch. We also don't keep a pointer to the body,
576 // since all control-flow from the switch goes to case/default statements.
577 Visit(S->getBody());
578
579 Block = SwitchTerminatedBlock;
580 return SwitchTerminatedBlock;
581 }
582
583 CFGBlock* VisitSwitchCase(SwitchCase* S) {
584 // A SwitchCase is either a "default" or "case" statement. We handle
585 // both in the same way. They are essentially labels, so they are the
586 // first statement in a block.
587 CFGBlock* CaseBlock = Visit(S->getSubStmt());
588 assert (CaseBlock);
589
590 // Cases/Default statements parition block, so this is the top of
591 // the basic block we were processing (the case/default is the first stmt).
592 CaseBlock->appendStmt(S);
593 FinishBlock(CaseBlock);
594
595 // Add this block to the list of successors for the block with the
596 // switch statement.
597 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
598
599 // We set Block to NULL to allow lazy creation of a new block (if necessary)
600 Block = NULL;
601
602 // This block is now the implicit successor of other blocks.
603 Succ = CaseBlock;
604
605 return CaseBlock;
606 }
607
Ted Kremenek97f75312007-08-21 21:42:03 +0000608};
Ted Kremenekd6e50602007-08-23 21:26:19 +0000609} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000610
611/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
612/// block has no successors or predecessors. If this is the first block
613/// created in the CFG, it is automatically set to be the Entry and Exit
614/// of the CFG.
615CFGBlock* CFG::createBlock(unsigned blockID) {
616 bool first_block = begin() == end();
617
618 // Create the block.
619 Blocks.push_front(CFGBlock(blockID));
620
621 // If this is the first block, set it as the Entry and Exit.
622 if (first_block) Entry = Exit = &front();
623
624 // Return the block.
625 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000626}
627
Ted Kremenek4db5b452007-08-23 16:51:22 +0000628/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
629/// CFG is returned to the caller.
630CFG* CFG::buildCFG(Stmt* Statement) {
631 CFGBuilder Builder;
632 return Builder.buildCFG(Statement);
633}
634
635/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000636void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
637
Ted Kremenek4db5b452007-08-23 16:51:22 +0000638/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000639void CFG::dump() { print(std::cerr); }
640
Ted Kremenek4db5b452007-08-23 16:51:22 +0000641/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek97f75312007-08-21 21:42:03 +0000642void CFG::print(std::ostream& OS) {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000643
644 // Print the Entry block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000645 if (begin() != end()) {
646 CFGBlock& Entry = getEntry();
647 OS << "\n [ B" << Entry.getBlockID() << " (ENTRY) ]\n";
648 Entry.print(OS);
649 }
650
Ted Kremenek4db5b452007-08-23 16:51:22 +0000651 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenek97f75312007-08-21 21:42:03 +0000652 for (iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000653 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000654 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000655
Ted Kremenek4db5b452007-08-23 16:51:22 +0000656 OS << "\n [ B" << I->getBlockID() << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000657 I->print(OS);
658 }
Ted Kremenek4db5b452007-08-23 16:51:22 +0000659
660 // Print the Exit Block.
661 if (begin() != end()) {
662 CFGBlock& Exit = getExit();
663 OS << "\n [ B" << Exit.getBlockID() << " (EXIT) ]\n";
664 Exit.print(OS);
665 }
666
Ted Kremenek97f75312007-08-21 21:42:03 +0000667 OS << "\n";
668}
669
Ted Kremenekd8313202007-08-22 18:22:34 +0000670
671namespace {
672
673 class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
674 void > {
675 std::ostream& OS;
676 public:
677 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
678
679 void VisitIfStmt(IfStmt* I) {
680 OS << "if ";
681 I->getCond()->printPretty(std::cerr);
682 OS << "\n";
683 }
684
685 // Default case.
686 void VisitStmt(Stmt* S) { S->printPretty(OS); }
687
688 void VisitForStmt(ForStmt* F) {
689 OS << "for (" ;
690 if (Stmt* I = F->getInit()) I->printPretty(OS);
691 OS << " ; ";
692 if (Stmt* C = F->getCond()) C->printPretty(OS);
693 OS << " ; ";
694 if (Stmt* I = F->getInc()) I->printPretty(OS);
695 OS << ")\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000696 }
697
698 void VisitWhileStmt(WhileStmt* W) {
699 OS << "while " ;
700 if (Stmt* C = W->getCond()) C->printPretty(OS);
701 OS << "\n";
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000702 }
703
704 void VisitDoStmt(DoStmt* D) {
705 OS << "do ... while ";
706 if (Stmt* C = D->getCond()) C->printPretty(OS);
707 OS << "\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000708 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000709 };
710}
711
Ted Kremenek4db5b452007-08-23 16:51:22 +0000712/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000713void CFGBlock::dump() { print(std::cerr); }
714
Ted Kremenek4db5b452007-08-23 16:51:22 +0000715/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
716/// Generally this will only be called from CFG::print.
Ted Kremenek97f75312007-08-21 21:42:03 +0000717void CFGBlock::print(std::ostream& OS) {
718
719 // Iterate through the statements in the block and print them.
720 OS << " ------------------------\n";
721 unsigned j = 1;
722 for (iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekc5de2222007-08-21 23:26:17 +0000723 // Print the statement # in the basic block.
724 OS << " " << std::setw(3) << j << ": ";
725
726 // Print the statement/expression.
727 Stmt* S = *I;
728
729 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
730 OS << L->getName() << ": (LABEL)\n";
731 else
732 (*I)->printPretty(OS);
733
734 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +0000735 if (isa<Expr>(*I)) OS << '\n';
736 }
737 OS << " ------------------------\n";
738
739 // Print the predecessors of this block.
740 OS << " Predecessors (" << pred_size() << "):";
741 unsigned i = 0;
742 for (pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i ) {
743 if (i == 8 || (i-8) == 0) {
744 OS << "\n ";
745 }
746 OS << " B" << (*I)->getBlockID();
747 }
748
749 // Print the terminator of this block.
750 OS << "\n Terminator: ";
Ted Kremenekd8313202007-08-22 18:22:34 +0000751 if (ControlFlowStmt)
752 CFGBlockTerminatorPrint(OS).Visit(ControlFlowStmt);
753 else
754 OS << "<NULL>\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000755
756 // Print the successors of this block.
757 OS << " Successors (" << succ_size() << "):";
758 i = 0;
759 for (succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i ) {
760 if (i == 8 || (i-8) % 10 == 0) {
761 OS << "\n ";
762 }
763 OS << " B" << (*I)->getBlockID();
764 }
765 OS << '\n';
Ted Kremenek4db5b452007-08-23 16:51:22 +0000766}