blob: 7746fa64694c6f7f3010330fee20ba7ecc006fbb [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 Kremenek97f75312007-08-21 21:42:03 +000077
Ted Kremenek73543912007-08-23 21:42:29 +000078 // buildCFG - Used by external clients to construct the CFG.
79 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000080
Ted Kremenek73543912007-08-23 21:42:29 +000081 // Visitors to walk an AST and construct the CFG. Called by
82 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000083
Ted Kremenek73543912007-08-23 21:42:29 +000084 CFGBlock* VisitStmt(Stmt* Statement);
85 CFGBlock* VisitNullStmt(NullStmt* Statement);
86 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
87 CFGBlock* VisitIfStmt(IfStmt* I);
88 CFGBlock* VisitReturnStmt(ReturnStmt* R);
89 CFGBlock* VisitLabelStmt(LabelStmt* L);
90 CFGBlock* VisitGotoStmt(GotoStmt* G);
91 CFGBlock* VisitForStmt(ForStmt* F);
92 CFGBlock* VisitWhileStmt(WhileStmt* W);
93 CFGBlock* VisitDoStmt(DoStmt* D);
94 CFGBlock* VisitContinueStmt(ContinueStmt* C);
95 CFGBlock* VisitBreakStmt(BreakStmt* B);
96 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
97 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek97f75312007-08-21 21:42:03 +000098
Ted Kremenek73543912007-08-23 21:42:29 +000099private:
100 CFGBlock* createBlock(bool add_successor = true);
101 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000102
Ted Kremenek97f75312007-08-21 21:42:03 +0000103};
Ted Kremenek73543912007-08-23 21:42:29 +0000104
105/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
106/// represent an arbitrary statement. Examples include a single expression
107/// or a function body (compound statement). The ownership of the returned
108/// CFG is transferred to the caller. If CFG construction fails, this method
109/// returns NULL.
110CFG* CFGBuilder::buildCFG(Stmt* Statement) {
111 if (!Statement) return NULL;
112
113 // Create an empty block that will serve as the exit block for the CFG.
114 // Since this is the first block added to the CFG, it will be implicitly
115 // registered as the exit block.
116 Block = createBlock();
117 assert (Block == &cfg->getExit());
118
119 // Visit the statements and create the CFG.
120 if (CFGBlock* B = Visit(Statement)) {
121 // Finalize the last constructed block. This usually involves
122 // reversing the order of the statements in the block.
123 FinishBlock(B);
124 cfg->setEntry(B);
125
126 // Backpatch the gotos whose label -> block mappings we didn't know
127 // when we encountered them.
128 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
129 E = BackpatchBlocks.end(); I != E; ++I ) {
130
131 CFGBlock* B = *I;
132 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
133 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
134
135 // If there is no target for the goto, then we are looking at an
136 // incomplete AST. Handle this by not registering a successor.
137 if (LI == LabelMap.end()) continue;
138
139 B->addSuccessor(LI->second);
140 }
141
142 // NULL out cfg so that repeated calls
143 CFG* t = cfg;
144 cfg = NULL;
145 return t;
146 }
147 else return NULL;
148}
149
150/// createBlock - Used to lazily create blocks that are connected
151/// to the current (global) succcessor.
152CFGBlock* CFGBuilder::createBlock(bool add_successor) {
153 CFGBlock* B = cfg->createBlock(NumBlocks++);
154 if (add_successor && Succ) B->addSuccessor(Succ);
155 return B;
156}
157
158/// FinishBlock - When the last statement has been added to the block,
159/// usually we must reverse the statements because they have been inserted
160/// in reverse order. When processing labels, however, there are cases
161/// in the recursion where we may have already reversed the statements
162/// in a block. This method safely tidies up a block: if the block
163/// has a label at the front, it has already been reversed. Otherwise,
164/// we reverse it.
165void CFGBuilder::FinishBlock(CFGBlock* B) {
166 assert (B);
167 CFGBlock::iterator I = B->begin();
168 if (I != B->end()) {
169 Stmt* S = *I;
170
171 if (isa<LabelStmt>(S) || isa<SwitchCase>(S))
172 return;
173
174 B->reverseStmts();
175 }
176}
177
178/// VisitStmt - Handle statements with no branching control flow.
179CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
180 // We cannot assume that we are in the middle of a basic block, since
181 // the CFG might only be constructed for this single statement. If
182 // we have no current basic block, just create one lazily.
183 if (!Block) Block = createBlock();
184
185 // Simply add the statement to the current block. We actually
186 // insert statements in reverse order; this order is reversed later
187 // when processing the containing element in the AST.
188 Block->appendStmt(Statement);
189
190 return Block;
191}
192
193CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
194 return Block;
195}
196
197CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
198 // The value returned from this function is the last created CFGBlock
199 // that represents the "entry" point for the translated AST node.
200 CFGBlock* LastBlock;
201
202 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
203 E = C->body_rend(); I != E; ++I )
204 // Add the statement to the current block.
205 if (!(LastBlock=Visit(*I)))
206 return NULL;
207
208 return LastBlock;
209}
210
211CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
212 // We may see an if statement in the middle of a basic block, or
213 // it may be the first statement we are processing. In either case,
214 // we create a new basic block. First, we create the blocks for
215 // the then...else statements, and then we create the block containing
216 // the if statement. If we were in the middle of a block, we
217 // stop processing that block and reverse its statements. That block
218 // is then the implicit successor for the "then" and "else" clauses.
219
220 // The block we were proccessing is now finished. Make it the
221 // successor block.
222 if (Block) {
223 Succ = Block;
224 FinishBlock(Block);
225 }
226
227 // Process the false branch. NULL out Block so that the recursive
228 // call to Visit will create a new basic block.
229 // Null out Block so that all successor
230 CFGBlock* ElseBlock = Succ;
231
232 if (Stmt* Else = I->getElse()) {
233 SaveAndRestore<CFGBlock*> sv(Succ);
234
235 // NULL out Block so that the recursive call to Visit will
236 // create a new basic block.
237 Block = NULL;
238 ElseBlock = Visit(Else);
239 if (!ElseBlock) return NULL;
240 FinishBlock(ElseBlock);
241 }
242
243 // Process the true branch. NULL out Block so that the recursive
244 // call to Visit will create a new basic block.
245 // Null out Block so that all successor
246 CFGBlock* ThenBlock;
247 {
248 Stmt* Then = I->getThen();
249 assert (Then);
250 SaveAndRestore<CFGBlock*> sv(Succ);
251 Block = NULL;
252 ThenBlock = Visit(Then);
253 if (!ThenBlock) return NULL;
254 FinishBlock(ThenBlock);
255 }
256
257 // Now create a new block containing the if statement.
258 Block = createBlock(false);
259
260 // Add the condition as the last statement in the new block.
261 Block->appendStmt(I->getCond());
262
263 // Set the terminator of the new block to the If statement.
264 Block->setTerminator(I);
265
266 // Now add the successors.
267 Block->addSuccessor(ThenBlock);
268 Block->addSuccessor(ElseBlock);
269
270 return Block;
271}
272
273CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
274 // If we were in the middle of a block we stop processing that block
275 // and reverse its statements.
276 //
277 // NOTE: If a "return" appears in the middle of a block, this means
278 // that the code afterwards is DEAD (unreachable). We still
279 // keep a basic block for that code; a simple "mark-and-sweep"
280 // from the entry block will be able to report such dead
281 // blocks.
282 if (Block) FinishBlock(Block);
283
284 // Create the new block.
285 Block = createBlock(false);
286
287 // The Exit block is the only successor.
288 Block->addSuccessor(&cfg->getExit());
289
290 // Add the return statement to the block.
291 Block->appendStmt(R);
292
293 // Also add the return statement as the terminator.
294 Block->setTerminator(R);
295
296 return Block;
297}
298
299CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
300 // Get the block of the labeled statement. Add it to our map.
301 CFGBlock* LabelBlock = Visit(L->getSubStmt());
302 assert (LabelBlock);
303
304 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
305 LabelMap[ L ] = LabelBlock;
306
307 // Labels partition blocks, so this is the end of the basic block
308 // we were processing (the label is the first statement).
309 LabelBlock->appendStmt(L);
310 FinishBlock(LabelBlock);
311
312 // We set Block to NULL to allow lazy creation of a new block
313 // (if necessary);
314 Block = NULL;
315
316 // This block is now the implicit successor of other blocks.
317 Succ = LabelBlock;
318
319 return LabelBlock;
320}
321
322CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
323 // Goto is a control-flow statement. Thus we stop processing the
324 // current block and create a new one.
325 if (Block) FinishBlock(Block);
326 Block = createBlock(false);
327 Block->setTerminator(G);
328
329 // If we already know the mapping to the label block add the
330 // successor now.
331 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
332
333 if (I == LabelMap.end())
334 // We will need to backpatch this block later.
335 BackpatchBlocks.push_back(Block);
336 else
337 Block->addSuccessor(I->second);
338
339 return Block;
340}
341
342CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
343 // "for" is a control-flow statement. Thus we stop processing the
344 // current block.
345
346 CFGBlock* LoopSuccessor = NULL;
347
348 if (Block) {
349 FinishBlock(Block);
350 LoopSuccessor = Block;
351 }
352 else LoopSuccessor = Succ;
353
354 // Create the condition block.
355 CFGBlock* ConditionBlock = createBlock(false);
356 ConditionBlock->setTerminator(F);
357 if (Stmt* C = F->getCond()) ConditionBlock->appendStmt(C);
358
359 // The condition block is the implicit successor for the loop body as
360 // well as any code above the loop.
361 Succ = ConditionBlock;
362
363 // Now create the loop body.
364 {
365 assert (F->getBody());
366
367 // Save the current values for Block, Succ, and continue and break targets
368 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
369 save_continue(ContinueTargetBlock),
370 save_break(BreakTargetBlock);
371
372 // All continues within this loop should go to the condition block
373 ContinueTargetBlock = ConditionBlock;
374
375 // All breaks should go to the code following the loop.
376 BreakTargetBlock = LoopSuccessor;
377
378 // Create a new block to contain the (bottom) of the loop body.
379 Block = createBlock();
380
381 // If we have increment code, insert it at the end of the body block.
382 if (Stmt* I = F->getInc()) Block->appendStmt(I);
383
384 // Now populate the body block, and in the process create new blocks
385 // as we walk the body of the loop.
386 CFGBlock* BodyBlock = Visit(F->getBody());
387 assert (BodyBlock);
388 FinishBlock(BodyBlock);
389
390 // This new body block is a successor to our condition block.
391 ConditionBlock->addSuccessor(BodyBlock);
392 }
393
394 // Link up the condition block with the code that follows the loop.
395 // (the false branch).
396 ConditionBlock->addSuccessor(LoopSuccessor);
397
398 // If the loop contains initialization, create a new block for those
399 // statements. This block can also contain statements that precede
400 // the loop.
401 if (Stmt* I = F->getInit()) {
402 Block = createBlock();
403 Block->appendStmt(I);
404 return Block;
405 }
406 else {
407 // There is no loop initialization. We are thus basically a while
408 // loop. NULL out Block to force lazy block construction.
409 Block = NULL;
410 return ConditionBlock;
411 }
412}
413
414CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
415 // "while" is a control-flow statement. Thus we stop processing the
416 // current block.
417
418 CFGBlock* LoopSuccessor = NULL;
419
420 if (Block) {
421 FinishBlock(Block);
422 LoopSuccessor = Block;
423 }
424 else LoopSuccessor = Succ;
425
426 // Create the condition block.
427 CFGBlock* ConditionBlock = createBlock(false);
428 ConditionBlock->setTerminator(W);
429 if (Stmt* C = W->getCond()) ConditionBlock->appendStmt(C);
430
431 // The condition block is the implicit successor for the loop body as
432 // well as any code above the loop.
433 Succ = ConditionBlock;
434
435 // Process the loop body.
436 {
437 assert (W->getBody());
438
439 // Save the current values for Block, Succ, and continue and break targets
440 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
441 save_continue(ContinueTargetBlock),
442 save_break(BreakTargetBlock);
443
444 // All continues within this loop should go to the condition block
445 ContinueTargetBlock = ConditionBlock;
446
447 // All breaks should go to the code following the loop.
448 BreakTargetBlock = LoopSuccessor;
449
450 // NULL out Block to force lazy instantiation of blocks for the body.
451 Block = NULL;
452
453 // Create the body. The returned block is the entry to the loop body.
454 CFGBlock* BodyBlock = Visit(W->getBody());
455 assert (BodyBlock);
456 FinishBlock(BodyBlock);
457
458 // Add the loop body entry as a successor to the condition.
459 ConditionBlock->addSuccessor(BodyBlock);
460 }
461
462 // Link up the condition block with the code that follows the loop.
463 // (the false branch).
464 ConditionBlock->addSuccessor(LoopSuccessor);
465
466 // There can be no more statements in the condition block
467 // since we loop back to this block. NULL out Block to force
468 // lazy creation of another block.
469 Block = NULL;
470
471 // Return the condition block, which is the dominating block for the loop.
472 return ConditionBlock;
473}
474
475CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
476 // "do...while" is a control-flow statement. Thus we stop processing the
477 // current block.
478
479 CFGBlock* LoopSuccessor = NULL;
480
481 if (Block) {
482 FinishBlock(Block);
483 LoopSuccessor = Block;
484 }
485 else LoopSuccessor = Succ;
486
487 // Create the condition block.
488 CFGBlock* ConditionBlock = createBlock(false);
489 ConditionBlock->setTerminator(D);
490 if (Stmt* C = D->getCond()) ConditionBlock->appendStmt(C);
491
492 // The condition block is the implicit successor for the loop body.
493 Succ = ConditionBlock;
494
495 CFGBlock* BodyBlock = NULL;
496 // Process the loop body.
497 {
498 assert (D->getBody());
499
500 // Save the current values for Block, Succ, and continue and break targets
501 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
502 save_continue(ContinueTargetBlock),
503 save_break(BreakTargetBlock);
504
505 // All continues within this loop should go to the condition block
506 ContinueTargetBlock = ConditionBlock;
507
508 // All breaks should go to the code following the loop.
509 BreakTargetBlock = LoopSuccessor;
510
511 // NULL out Block to force lazy instantiation of blocks for the body.
512 Block = NULL;
513
514 // Create the body. The returned block is the entry to the loop body.
515 BodyBlock = Visit(D->getBody());
516 assert (BodyBlock);
517 FinishBlock(BodyBlock);
518
519 // Add the loop body entry as a successor to the condition.
520 ConditionBlock->addSuccessor(BodyBlock);
521 }
522
523 // Link up the condition block with the code that follows the loop.
524 // (the false branch).
525 ConditionBlock->addSuccessor(LoopSuccessor);
526
527 // There can be no more statements in the condition block
528 // since we loop back to this block. NULL out Block to force
529 // lazy creation of another block.
530 Block = NULL;
531
532 // Return the loop body, which is the dominating block for the loop.
533 return BodyBlock;
534}
535
536CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
537 // "continue" is a control-flow statement. Thus we stop processing the
538 // current block.
539 if (Block) FinishBlock(Block);
540
541 // Now create a new block that ends with the continue statement.
542 Block = createBlock(false);
543 Block->setTerminator(C);
544
545 // If there is no target for the continue, then we are looking at an
546 // incomplete AST. Handle this by not registering a successor.
547 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
548
549 return Block;
550}
551
552CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
553 // "break" is a control-flow statement. Thus we stop processing the
554 // current block.
555 if (Block) FinishBlock(Block);
556
557 // Now create a new block that ends with the continue statement.
558 Block = createBlock(false);
559 Block->setTerminator(B);
560
561 // If there is no target for the break, then we are looking at an
562 // incomplete AST. Handle this by not registering a successor.
563 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
564
565 return Block;
566}
567
568CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
569 // "switch" is a control-flow statement. Thus we stop processing the
570 // current block.
571 CFGBlock* SwitchSuccessor = NULL;
572
573 if (Block) {
574 FinishBlock(Block);
575 SwitchSuccessor = Block;
576 }
577 else SwitchSuccessor = Succ;
578
579 // Save the current "switch" context.
580 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
581 save_break(BreakTargetBlock);
582
583 // Create a new block that will contain the switch statement.
584 SwitchTerminatedBlock = createBlock(false);
585
586 // Add the terminator and condition in the switch block.
587 assert (S->getCond() && "switch condition must be non-NULL");
588 SwitchTerminatedBlock->appendStmt(S->getCond());
589 SwitchTerminatedBlock->setTerminator(S);
590
591
592 // Now process the switch body. The code after the switch is the implicit
593 // successor.
594 Succ = SwitchSuccessor;
595 BreakTargetBlock = SwitchSuccessor;
596
597 assert (S->getBody() && "switch must contain a non-NULL body");
598 Block = NULL;
599
600 // When visiting the body, the case statements should automatically get
601 // linked up to the switch. We also don't keep a pointer to the body,
602 // since all control-flow from the switch goes to case/default statements.
603 Visit(S->getBody());
604
605 Block = SwitchTerminatedBlock;
606 return SwitchTerminatedBlock;
607}
608
609CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
610 // A SwitchCase is either a "default" or "case" statement. We handle
611 // both in the same way. They are essentially labels, so they are the
612 // first statement in a block.
613 CFGBlock* CaseBlock = Visit(S->getSubStmt());
614 assert (CaseBlock);
615
616 // Cases/Default statements parition block, so this is the top of
617 // the basic block we were processing (the case/default is the first stmt).
618 CaseBlock->appendStmt(S);
619 FinishBlock(CaseBlock);
620
621 // Add this block to the list of successors for the block with the
622 // switch statement.
623 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
624
625 // We set Block to NULL to allow lazy creation of a new block (if necessary)
626 Block = NULL;
627
628 // This block is now the implicit successor of other blocks.
629 Succ = CaseBlock;
630
631 return CaseBlock;
632}
633
634
Ted Kremenekd6e50602007-08-23 21:26:19 +0000635} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000636
637/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
638/// block has no successors or predecessors. If this is the first block
639/// created in the CFG, it is automatically set to be the Entry and Exit
640/// of the CFG.
641CFGBlock* CFG::createBlock(unsigned blockID) {
642 bool first_block = begin() == end();
643
644 // Create the block.
645 Blocks.push_front(CFGBlock(blockID));
646
647 // If this is the first block, set it as the Entry and Exit.
648 if (first_block) Entry = Exit = &front();
649
650 // Return the block.
651 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000652}
653
Ted Kremenek4db5b452007-08-23 16:51:22 +0000654/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
655/// CFG is returned to the caller.
656CFG* CFG::buildCFG(Stmt* Statement) {
657 CFGBuilder Builder;
658 return Builder.buildCFG(Statement);
659}
660
661/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000662void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
663
Ted Kremenek4db5b452007-08-23 16:51:22 +0000664/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000665void CFG::dump() { print(std::cerr); }
666
Ted Kremenek4db5b452007-08-23 16:51:22 +0000667/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek97f75312007-08-21 21:42:03 +0000668void CFG::print(std::ostream& OS) {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000669 // Print the Entry block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000670 if (begin() != end()) {
671 CFGBlock& Entry = getEntry();
672 OS << "\n [ B" << Entry.getBlockID() << " (ENTRY) ]\n";
673 Entry.print(OS);
674 }
675
Ted Kremenek4db5b452007-08-23 16:51:22 +0000676 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenek97f75312007-08-21 21:42:03 +0000677 for (iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000678 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000679 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000680
Ted Kremenek4db5b452007-08-23 16:51:22 +0000681 OS << "\n [ B" << I->getBlockID() << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000682 I->print(OS);
683 }
Ted Kremenek73543912007-08-23 21:42:29 +0000684
Ted Kremenek4db5b452007-08-23 16:51:22 +0000685 // Print the Exit Block.
686 if (begin() != end()) {
687 CFGBlock& Exit = getExit();
688 OS << "\n [ B" << Exit.getBlockID() << " (EXIT) ]\n";
689 Exit.print(OS);
690 }
Ted Kremenek73543912007-08-23 21:42:29 +0000691
Ted Kremenek97f75312007-08-21 21:42:03 +0000692 OS << "\n";
693}
694
Ted Kremenekd8313202007-08-22 18:22:34 +0000695
696namespace {
697
Ted Kremenek73543912007-08-23 21:42:29 +0000698class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
699 void > {
700 std::ostream& OS;
701public:
702 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
703
704 void VisitIfStmt(IfStmt* I) {
705 OS << "if ";
706 I->getCond()->printPretty(std::cerr);
707 OS << "\n";
708 }
709
710 // Default case.
711 void VisitStmt(Stmt* S) { S->printPretty(OS); }
712
713 void VisitForStmt(ForStmt* F) {
714 OS << "for (" ;
715 if (Stmt* I = F->getInit()) I->printPretty(OS);
716 OS << " ; ";
717 if (Stmt* C = F->getCond()) C->printPretty(OS);
718 OS << " ; ";
719 if (Stmt* I = F->getInc()) I->printPretty(OS);
720 OS << ")\n";
721 }
722
723 void VisitWhileStmt(WhileStmt* W) {
724 OS << "while " ;
725 if (Stmt* C = W->getCond()) C->printPretty(OS);
726 OS << "\n";
727 }
728
729 void VisitDoStmt(DoStmt* D) {
730 OS << "do ... while ";
731 if (Stmt* C = D->getCond()) C->printPretty(OS);
732 OS << "\n";
733 }
734};
735} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000736
Ted Kremenek4db5b452007-08-23 16:51:22 +0000737/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000738void CFGBlock::dump() { print(std::cerr); }
739
Ted Kremenek4db5b452007-08-23 16:51:22 +0000740/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
741/// Generally this will only be called from CFG::print.
Ted Kremenek97f75312007-08-21 21:42:03 +0000742void CFGBlock::print(std::ostream& OS) {
743
744 // Iterate through the statements in the block and print them.
745 OS << " ------------------------\n";
746 unsigned j = 1;
747 for (iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekc5de2222007-08-21 23:26:17 +0000748 // Print the statement # in the basic block.
749 OS << " " << std::setw(3) << j << ": ";
750
751 // Print the statement/expression.
752 Stmt* S = *I;
753
754 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
755 OS << L->getName() << ": (LABEL)\n";
756 else
757 (*I)->printPretty(OS);
758
759 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +0000760 if (isa<Expr>(*I)) OS << '\n';
761 }
762 OS << " ------------------------\n";
763
764 // Print the predecessors of this block.
765 OS << " Predecessors (" << pred_size() << "):";
766 unsigned i = 0;
767 for (pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i ) {
768 if (i == 8 || (i-8) == 0) {
769 OS << "\n ";
770 }
771 OS << " B" << (*I)->getBlockID();
772 }
773
774 // Print the terminator of this block.
775 OS << "\n Terminator: ";
Ted Kremenekd8313202007-08-22 18:22:34 +0000776 if (ControlFlowStmt)
777 CFGBlockTerminatorPrint(OS).Visit(ControlFlowStmt);
778 else
779 OS << "<NULL>\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000780
781 // Print the successors of this block.
782 OS << " Successors (" << succ_size() << "):";
783 i = 0;
784 for (succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i ) {
785 if (i == 8 || (i-8) % 10 == 0) {
786 OS << "\n ";
787 }
788 OS << " B" << (*I)->getBlockID();
789 }
790 OS << '\n';
Ted Kremenek4db5b452007-08-23 16:51:22 +0000791}