blob: aa5bbe437dafb500ef29ae0667039c38fec59c3f [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenekfddd5182007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
16#include "clang/AST/Expr.h"
Ted Kremenekc310e932007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek274f4332008-04-28 18:00:46 +000024#include <llvm/Support/Allocator.h>
Ted Kremenekfddd5182007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000027#include <sstream>
Ted Kremenek83c01da2008-01-11 00:40:29 +000028
Ted Kremenekfddd5182007-08-21 21:42:03 +000029using namespace clang;
30
31namespace {
32
Ted Kremenekbefef2f2007-08-23 21:26:19 +000033// SaveAndRestore - A utility class that uses RIIA to save and restore
34// the value of a variable.
35template<typename T>
Ted Kremenek6fa9b882008-01-08 18:15:10 +000036struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000037 SaveAndRestore(T& x) : X(x), old_value(x) {}
38 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000039 T get() { return old_value; }
40
Ted Kremenekbefef2f2007-08-23 21:26:19 +000041 T& X;
42 T old_value;
43};
Ted Kremenekfddd5182007-08-21 21:42:03 +000044
45/// CFGBuilder - This class is implements CFG construction from an AST.
46/// The builder is stateful: an instance of the builder should be used to only
47/// construct a single CFG.
48///
49/// Example usage:
50///
51/// CFGBuilder builder;
52/// CFG* cfg = builder.BuildAST(stmt1);
53///
Ted Kremenekc310e932007-08-21 22:06:14 +000054/// CFG construction is done via a recursive walk of an AST.
55/// We actually parse the AST in reverse order so that the successor
56/// of a basic block is constructed prior to its predecessor. This
57/// allows us to nicely capture implicit fall-throughs without extra
58/// basic blocks.
59///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000060class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000061 CFG* cfg;
62 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000063 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000064 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000065 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000066 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000067 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000068
Ted Kremenek19bb3562007-08-28 19:26:49 +000069 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000070 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
71 LabelMapTy LabelMap;
72
Ted Kremenek19bb3562007-08-28 19:26:49 +000073 // A list of blocks that end with a "goto" that must be backpatched to
74 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000075 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000076 BackpatchBlocksTy BackpatchBlocks;
77
Ted Kremenek19bb3562007-08-28 19:26:49 +000078 // A list of labels whose address has been taken (for indirect gotos).
79 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
80 LabelSetTy AddressTakenLabels;
81
Ted Kremenekfddd5182007-08-21 21:42:03 +000082public:
Ted Kremenek026473c2007-08-23 16:51:22 +000083 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000084 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000085 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000086 // Create an empty CFG.
87 cfg = new CFG();
88 }
89
90 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000091
Ted Kremenekd4fdee32007-08-23 21:42:29 +000092 // buildCFG - Used by external clients to construct the CFG.
93 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000094
Ted Kremenekd4fdee32007-08-23 21:42:29 +000095 // Visitors to walk an AST and construct the CFG. Called by
96 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000097
Ted Kremenekd4fdee32007-08-23 21:42:29 +000098 CFGBlock* VisitStmt(Stmt* Statement);
99 CFGBlock* VisitNullStmt(NullStmt* Statement);
100 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
101 CFGBlock* VisitIfStmt(IfStmt* I);
102 CFGBlock* VisitReturnStmt(ReturnStmt* R);
103 CFGBlock* VisitLabelStmt(LabelStmt* L);
104 CFGBlock* VisitGotoStmt(GotoStmt* G);
105 CFGBlock* VisitForStmt(ForStmt* F);
106 CFGBlock* VisitWhileStmt(WhileStmt* W);
107 CFGBlock* VisitDoStmt(DoStmt* D);
108 CFGBlock* VisitContinueStmt(ContinueStmt* C);
109 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000110 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
111 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek295222c2008-02-13 21:46:34 +0000112 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000113 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000114
Ted Kremenek4102af92008-03-13 03:04:22 +0000115 // FIXME: Add support for ObjC-specific control-flow structures.
116
Ted Kremenek274f4332008-04-28 18:00:46 +0000117 // NYS == Not Yet Supported
118 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000119 badCFG = true;
120 return Block;
121 }
122
Ted Kremenek274f4332008-04-28 18:00:46 +0000123 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
124 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
125 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
126 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
127 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
128
129 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
130 return NYS();
Ted Kremenek4102af92008-03-13 03:04:22 +0000131 }
132
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000133private:
134 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000135 CFGBlock* addStmt(Stmt* Terminator);
136 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
137 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000138 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000139 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000140 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000141
Ted Kremenek4102af92008-03-13 03:04:22 +0000142 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000143};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000144
145/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
146/// represent an arbitrary statement. Examples include a single expression
147/// or a function body (compound statement). The ownership of the returned
148/// CFG is transferred to the caller. If CFG construction fails, this method
149/// returns NULL.
150CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000151 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000152 if (!Statement) return NULL;
153
Ted Kremenek4102af92008-03-13 03:04:22 +0000154 badCFG = false;
155
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000156 // Create an empty block that will serve as the exit block for the CFG.
157 // Since this is the first block added to the CFG, it will be implicitly
158 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000159 Succ = createBlock();
160 assert (Succ == &cfg->getExit());
161 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000162
163 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000164 CFGBlock* B = Visit(Statement);
165 if (!B) B = Succ;
166
167 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000168 // Finalize the last constructed block. This usually involves
169 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000170 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000171
172 // Backpatch the gotos whose label -> block mappings we didn't know
173 // when we encountered them.
174 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
175 E = BackpatchBlocks.end(); I != E; ++I ) {
176
177 CFGBlock* B = *I;
178 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
179 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
180
181 // If there is no target for the goto, then we are looking at an
182 // incomplete AST. Handle this by not registering a successor.
183 if (LI == LabelMap.end()) continue;
184
185 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000186 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000187
Ted Kremenek19bb3562007-08-28 19:26:49 +0000188 // Add successors to the Indirect Goto Dispatch block (if we have one).
189 if (CFGBlock* B = cfg->getIndirectGotoBlock())
190 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
191 E = AddressTakenLabels.end(); I != E; ++I ) {
192
193 // Lookup the target block.
194 LabelMapTy::iterator LI = LabelMap.find(*I);
195
196 // If there is no target block that contains label, then we are looking
197 // at an incomplete AST. Handle this by not registering a successor.
198 if (LI == LabelMap.end()) continue;
199
200 B->addSuccessor(LI->second);
201 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000202
Ted Kremenek94b33162007-09-17 16:18:02 +0000203 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000204 }
205
206 // Create an empty entry block that has no predecessors.
207 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000208
Ted Kremenek4102af92008-03-13 03:04:22 +0000209 if (badCFG) {
210 delete cfg;
211 cfg = NULL;
212 return NULL;
213 }
214
Ted Kremenek322f58d2007-09-26 21:23:31 +0000215 // NULL out cfg so that repeated calls to the builder will fail and that
216 // the ownership of the constructed CFG is passed to the caller.
217 CFG* t = cfg;
218 cfg = NULL;
219 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000220}
221
222/// createBlock - Used to lazily create blocks that are connected
223/// to the current (global) succcessor.
224CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000225 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000226 if (add_successor && Succ) B->addSuccessor(Succ);
227 return B;
228}
229
230/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000231/// we must reverse the statements because they have been inserted
232/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000233void CFGBuilder::FinishBlock(CFGBlock* B) {
234 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000235 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000236}
237
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000238/// addStmt - Used to add statements/expressions to the current CFGBlock
239/// "Block". This method calls WalkAST on the passed statement to see if it
240/// contains any short-circuit expressions. If so, it recursively creates
241/// the necessary blocks for such expressions. It returns the "topmost" block
242/// of the created blocks, or the original value of "Block" when this method
243/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000244CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000245 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000246 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000247}
248
249/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000250/// add extra blocks for ternary operators, &&, and ||. We also
251/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000252CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
253 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000254 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000255 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000256
257 // Create the confluence block that will "merge" the results
258 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000259 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
260 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000261 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000262
263 // Create a block for the LHS expression if there is an LHS expression.
264 // A GCC extension allows LHS to be NULL, causing the condition to
265 // be the value that is returned instead.
266 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000267 Succ = ConfluenceBlock;
268 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000269 CFGBlock* LHSBlock = NULL;
270 if (C->getLHS()) {
271 LHSBlock = Visit(C->getLHS());
272 FinishBlock(LHSBlock);
273 Block = NULL;
274 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000275
Ted Kremenekecc04c92007-11-26 18:20:26 +0000276 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000277 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000278 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000279 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000280
Ted Kremenekecc04c92007-11-26 18:20:26 +0000281 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000282 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000283
284 if (LHSBlock)
285 Block->addSuccessor(LHSBlock);
286 else {
287 // If we have no LHS expression, add the ConfluenceBlock as a direct
288 // successor for the block containing the condition. Moreover,
289 // we need to reverse the order of the predecessors in the
290 // ConfluenceBlock because the RHSBlock will have been added to
291 // the succcessors already, and we want the first predecessor to the
292 // the block containing the expression for the case when the ternary
293 // expression evaluates to true.
294 Block->addSuccessor(ConfluenceBlock);
295 assert (ConfluenceBlock->pred_size() == 2);
296 std::reverse(ConfluenceBlock->pred_begin(),
297 ConfluenceBlock->pred_end());
298 }
299
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000300 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000301
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000302 Block->setTerminator(C);
303 return addStmt(C->getCond());
304 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000305
306 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000307 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000308
309 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
310 ConfluenceBlock->appendStmt(C);
311 FinishBlock(ConfluenceBlock);
312
313 Succ = ConfluenceBlock;
314 Block = NULL;
315 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000316 FinishBlock(LHSBlock);
317
Ted Kremenek49a436d2007-08-31 17:03:41 +0000318 Succ = ConfluenceBlock;
319 Block = NULL;
320 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000321 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000322
323 Block = createBlock(false);
324 Block->addSuccessor(LHSBlock);
325 Block->addSuccessor(RHSBlock);
326 Block->setTerminator(C);
327 return addStmt(C->getCond());
328 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000329
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000330 case Stmt::DeclStmtClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000331 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
332 Block->appendStmt(Terminator);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000333
334 StmtIterator I(D);
335 return WalkAST_VisitDeclSubExprs(I);
336 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000337
Ted Kremenek19bb3562007-08-28 19:26:49 +0000338 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000339 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000340 AddressTakenLabels.insert(A->getLabel());
341
Ted Kremenek411cdee2008-04-16 21:10:48 +0000342 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000343 return Block;
344 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000345
Ted Kremenek15c27a82007-08-28 18:30:10 +0000346 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000347 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000348
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000349 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000350 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000351
352 // sizeof(expressions). For such expressions,
353 // the subexpression is not really evaluated, so
354 // we don't care about control-flow within the sizeof.
355 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000356 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000357 return Block;
358 }
359
360 break;
361 }
362
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000363 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000364 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000365
366 if (B->isLogicalOp()) { // && or ||
367 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
368 ConfluenceBlock->appendStmt(B);
369 FinishBlock(ConfluenceBlock);
370
371 // create the block evaluating the LHS
372 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000373 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000374
375 // create the block evaluating the RHS
376 Succ = ConfluenceBlock;
377 Block = NULL;
378 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000379
380 // Now link the LHSBlock with RHSBlock.
381 if (B->getOpcode() == BinaryOperator::LOr) {
382 LHSBlock->addSuccessor(ConfluenceBlock);
383 LHSBlock->addSuccessor(RHSBlock);
384 }
385 else {
386 assert (B->getOpcode() == BinaryOperator::LAnd);
387 LHSBlock->addSuccessor(RHSBlock);
388 LHSBlock->addSuccessor(ConfluenceBlock);
389 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000390
391 // Generate the blocks for evaluating the LHS.
392 Block = LHSBlock;
393 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000394 }
395 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
396 Block->appendStmt(B);
397 addStmt(B->getRHS());
398 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000399 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000400
401 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000402 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000403
404 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000406
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000407 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000408 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000409 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000410
Ted Kremenek411cdee2008-04-16 21:10:48 +0000411 if (AlwaysAddStmt) Block->appendStmt(Terminator);
412 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000413}
414
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000415/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
416/// DeclStmts. Because the initialization code (and sometimes the
417/// the type declarations) for DeclStmts can contain arbitrary expressions,
418/// we must linearize declarations to handle arbitrary control-flow induced by
419/// those expressions.
420CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000421 if (I == StmtIterator())
422 return Block;
423
Ted Kremenek411cdee2008-04-16 21:10:48 +0000424 Stmt* Terminator = *I;
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000425 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000426 WalkAST_VisitDeclSubExprs(I);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000427
428 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000429
Ted Kremenek411cdee2008-04-16 21:10:48 +0000430 switch (Terminator->getStmtClass()) {
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000431 case Stmt::IntegerLiteralClass:
432 case Stmt::CharacterLiteralClass:
433 case Stmt::StringLiteralClass:
434 break;
435
436 // All other cases.
437
438 default:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000439 Block = addStmt(Terminator);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000440 }
441
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000442 return Block;
443}
444
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000445/// WalkAST_VisitChildren - Utility method to call WalkAST on the
446/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000447CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000448 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000449 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000450 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000451 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000452
453 return B;
454}
455
Ted Kremenek15c27a82007-08-28 18:30:10 +0000456/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
457/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000458CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
459 Block->appendStmt(Terminator);
460 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000461}
462
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000463/// VisitStmt - Handle statements with no branching control flow.
464CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
465 // We cannot assume that we are in the middle of a basic block, since
466 // the CFG might only be constructed for this single statement. If
467 // we have no current basic block, just create one lazily.
468 if (!Block) Block = createBlock();
469
470 // Simply add the statement to the current block. We actually
471 // insert statements in reverse order; this order is reversed later
472 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000473 addStmt(Statement);
474
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000475 return Block;
476}
477
478CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
479 return Block;
480}
481
482CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000483
484 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000485
Ted Kremenekd34066c2008-02-26 00:22:58 +0000486 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
487 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000488 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000489 }
490
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000491 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000492}
493
494CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
495 // We may see an if statement in the middle of a basic block, or
496 // it may be the first statement we are processing. In either case,
497 // we create a new basic block. First, we create the blocks for
498 // the then...else statements, and then we create the block containing
499 // the if statement. If we were in the middle of a block, we
500 // stop processing that block and reverse its statements. That block
501 // is then the implicit successor for the "then" and "else" clauses.
502
503 // The block we were proccessing is now finished. Make it the
504 // successor block.
505 if (Block) {
506 Succ = Block;
507 FinishBlock(Block);
508 }
509
510 // Process the false branch. NULL out Block so that the recursive
511 // call to Visit will create a new basic block.
512 // Null out Block so that all successor
513 CFGBlock* ElseBlock = Succ;
514
515 if (Stmt* Else = I->getElse()) {
516 SaveAndRestore<CFGBlock*> sv(Succ);
517
518 // NULL out Block so that the recursive call to Visit will
519 // create a new basic block.
520 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000521 ElseBlock = Visit(Else);
522
523 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
524 ElseBlock = sv.get();
525 else if (Block)
526 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000527 }
528
529 // Process the true branch. NULL out Block so that the recursive
530 // call to Visit will create a new basic block.
531 // Null out Block so that all successor
532 CFGBlock* ThenBlock;
533 {
534 Stmt* Then = I->getThen();
535 assert (Then);
536 SaveAndRestore<CFGBlock*> sv(Succ);
537 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000538 ThenBlock = Visit(Then);
539
540 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
541 ThenBlock = sv.get();
542 else if (Block)
543 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000544 }
545
546 // Now create a new block containing the if statement.
547 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000548
549 // Set the terminator of the new block to the If statement.
550 Block->setTerminator(I);
551
552 // Now add the successors.
553 Block->addSuccessor(ThenBlock);
554 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000555
556 // Add the condition as the last statement in the new block. This
557 // may create new blocks as the condition may contain control-flow. Any
558 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000559 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000560}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000561
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000562
563CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
564 // If we were in the middle of a block we stop processing that block
565 // and reverse its statements.
566 //
567 // NOTE: If a "return" appears in the middle of a block, this means
568 // that the code afterwards is DEAD (unreachable). We still
569 // keep a basic block for that code; a simple "mark-and-sweep"
570 // from the entry block will be able to report such dead
571 // blocks.
572 if (Block) FinishBlock(Block);
573
574 // Create the new block.
575 Block = createBlock(false);
576
577 // The Exit block is the only successor.
578 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000579
580 // Add the return statement to the block. This may create new blocks
581 // if R contains control-flow (short-circuit operations).
582 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000583}
584
585CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
586 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000587 Visit(L->getSubStmt());
588 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000589
590 if (!LabelBlock) // This can happen when the body is empty, i.e.
591 LabelBlock=createBlock(); // scopes that only contains NullStmts.
592
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000593 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
594 LabelMap[ L ] = LabelBlock;
595
596 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000597 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000598 // label (and we have already processed the substatement) there is no
599 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000600 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000601 FinishBlock(LabelBlock);
602
603 // We set Block to NULL to allow lazy creation of a new block
604 // (if necessary);
605 Block = NULL;
606
607 // This block is now the implicit successor of other blocks.
608 Succ = LabelBlock;
609
610 return LabelBlock;
611}
612
613CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
614 // Goto is a control-flow statement. Thus we stop processing the
615 // current block and create a new one.
616 if (Block) FinishBlock(Block);
617 Block = createBlock(false);
618 Block->setTerminator(G);
619
620 // If we already know the mapping to the label block add the
621 // successor now.
622 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
623
624 if (I == LabelMap.end())
625 // We will need to backpatch this block later.
626 BackpatchBlocks.push_back(Block);
627 else
628 Block->addSuccessor(I->second);
629
630 return Block;
631}
632
633CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
634 // "for" is a control-flow statement. Thus we stop processing the
635 // current block.
636
637 CFGBlock* LoopSuccessor = NULL;
638
639 if (Block) {
640 FinishBlock(Block);
641 LoopSuccessor = Block;
642 }
643 else LoopSuccessor = Succ;
644
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000645 // Because of short-circuit evaluation, the condition of the loop
646 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
647 // blocks that evaluate the condition.
648 CFGBlock* ExitConditionBlock = createBlock(false);
649 CFGBlock* EntryConditionBlock = ExitConditionBlock;
650
651 // Set the terminator for the "exit" condition block.
652 ExitConditionBlock->setTerminator(F);
653
654 // Now add the actual condition to the condition block. Because the
655 // condition itself may contain control-flow, new blocks may be created.
656 if (Stmt* C = F->getCond()) {
657 Block = ExitConditionBlock;
658 EntryConditionBlock = addStmt(C);
659 if (Block) FinishBlock(EntryConditionBlock);
660 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000661
662 // The condition block is the implicit successor for the loop body as
663 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000664 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000665
666 // Now create the loop body.
667 {
668 assert (F->getBody());
669
670 // Save the current values for Block, Succ, and continue and break targets
671 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
672 save_continue(ContinueTargetBlock),
673 save_break(BreakTargetBlock);
674
675 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000676 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000677
678 // All breaks should go to the code following the loop.
679 BreakTargetBlock = LoopSuccessor;
680
Ted Kremenekaf603f72007-08-30 18:39:40 +0000681 // Create a new block to contain the (bottom) of the loop body.
682 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000683
684 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000685 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000686
687 // Now populate the body block, and in the process create new blocks
688 // as we walk the body of the loop.
689 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000690
691 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000692 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000693 else if (Block)
694 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000695
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000696 // This new body block is a successor to our "exit" condition block.
697 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000698 }
699
700 // Link up the condition block with the code that follows the loop.
701 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000702 ExitConditionBlock->addSuccessor(LoopSuccessor);
703
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000704 // If the loop contains initialization, create a new block for those
705 // statements. This block can also contain statements that precede
706 // the loop.
707 if (Stmt* I = F->getInit()) {
708 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000709 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000710 }
711 else {
712 // There is no loop initialization. We are thus basically a while
713 // loop. NULL out Block to force lazy block construction.
714 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000715 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000716 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000717 }
718}
719
720CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
721 // "while" is a control-flow statement. Thus we stop processing the
722 // current block.
723
724 CFGBlock* LoopSuccessor = NULL;
725
726 if (Block) {
727 FinishBlock(Block);
728 LoopSuccessor = Block;
729 }
730 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000731
732 // Because of short-circuit evaluation, the condition of the loop
733 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
734 // blocks that evaluate the condition.
735 CFGBlock* ExitConditionBlock = createBlock(false);
736 CFGBlock* EntryConditionBlock = ExitConditionBlock;
737
738 // Set the terminator for the "exit" condition block.
739 ExitConditionBlock->setTerminator(W);
740
741 // Now add the actual condition to the condition block. Because the
742 // condition itself may contain control-flow, new blocks may be created.
743 // Thus we update "Succ" after adding the condition.
744 if (Stmt* C = W->getCond()) {
745 Block = ExitConditionBlock;
746 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000747 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000748 if (Block) FinishBlock(EntryConditionBlock);
749 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000750
751 // The condition block is the implicit successor for the loop body as
752 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000753 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000754
755 // Process the loop body.
756 {
757 assert (W->getBody());
758
759 // Save the current values for Block, Succ, and continue and break targets
760 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
761 save_continue(ContinueTargetBlock),
762 save_break(BreakTargetBlock);
763
764 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000765 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000766
767 // All breaks should go to the code following the loop.
768 BreakTargetBlock = LoopSuccessor;
769
770 // NULL out Block to force lazy instantiation of blocks for the body.
771 Block = NULL;
772
773 // Create the body. The returned block is the entry to the loop body.
774 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000775
776 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000777 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000778 else if (Block)
779 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000780
781 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000782 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000783 }
784
785 // Link up the condition block with the code that follows the loop.
786 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000787 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000788
789 // There can be no more statements in the condition block
790 // since we loop back to this block. NULL out Block to force
791 // lazy creation of another block.
792 Block = NULL;
793
794 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000795 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000796 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000797}
798
799CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
800 // "do...while" is a control-flow statement. Thus we stop processing the
801 // current block.
802
803 CFGBlock* LoopSuccessor = NULL;
804
805 if (Block) {
806 FinishBlock(Block);
807 LoopSuccessor = Block;
808 }
809 else LoopSuccessor = Succ;
810
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000811 // Because of short-circuit evaluation, the condition of the loop
812 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
813 // blocks that evaluate the condition.
814 CFGBlock* ExitConditionBlock = createBlock(false);
815 CFGBlock* EntryConditionBlock = ExitConditionBlock;
816
817 // Set the terminator for the "exit" condition block.
818 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000819
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000820 // Now add the actual condition to the condition block. Because the
821 // condition itself may contain control-flow, new blocks may be created.
822 if (Stmt* C = D->getCond()) {
823 Block = ExitConditionBlock;
824 EntryConditionBlock = addStmt(C);
825 if (Block) FinishBlock(EntryConditionBlock);
826 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000827
Ted Kremenek54827132008-02-27 07:20:00 +0000828 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000829 Succ = EntryConditionBlock;
830
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000831 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000832 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000833 {
834 assert (D->getBody());
835
836 // Save the current values for Block, Succ, and continue and break targets
837 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
838 save_continue(ContinueTargetBlock),
839 save_break(BreakTargetBlock);
840
841 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000842 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000843
844 // All breaks should go to the code following the loop.
845 BreakTargetBlock = LoopSuccessor;
846
847 // NULL out Block to force lazy instantiation of blocks for the body.
848 Block = NULL;
849
850 // Create the body. The returned block is the entry to the loop body.
851 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000852
Ted Kremenekaf603f72007-08-30 18:39:40 +0000853 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000854 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000855 else if (Block)
856 FinishBlock(BodyBlock);
857
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000858 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000859 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000860 }
861
862 // Link up the condition block with the code that follows the loop.
863 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000864 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000865
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000866 // There can be no more statements in the body block(s)
867 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000868 // lazy creation of another block.
869 Block = NULL;
870
871 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000872 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000873 return BodyBlock;
874}
875
876CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
877 // "continue" is a control-flow statement. Thus we stop processing the
878 // current block.
879 if (Block) FinishBlock(Block);
880
881 // Now create a new block that ends with the continue statement.
882 Block = createBlock(false);
883 Block->setTerminator(C);
884
885 // If there is no target for the continue, then we are looking at an
886 // incomplete AST. Handle this by not registering a successor.
887 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
888
889 return Block;
890}
891
892CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
893 // "break" is a control-flow statement. Thus we stop processing the
894 // current block.
895 if (Block) FinishBlock(Block);
896
897 // Now create a new block that ends with the continue statement.
898 Block = createBlock(false);
899 Block->setTerminator(B);
900
901 // If there is no target for the break, then we are looking at an
902 // incomplete AST. Handle this by not registering a successor.
903 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
904
905 return Block;
906}
907
Ted Kremenek411cdee2008-04-16 21:10:48 +0000908CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000909 // "switch" is a control-flow statement. Thus we stop processing the
910 // current block.
911 CFGBlock* SwitchSuccessor = NULL;
912
913 if (Block) {
914 FinishBlock(Block);
915 SwitchSuccessor = Block;
916 }
917 else SwitchSuccessor = Succ;
918
919 // Save the current "switch" context.
920 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000921 save_break(BreakTargetBlock),
922 save_default(DefaultCaseBlock);
923
924 // Set the "default" case to be the block after the switch statement.
925 // If the switch statement contains a "default:", this value will
926 // be overwritten with the block for that code.
927 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000928
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000929 // Create a new block that will contain the switch statement.
930 SwitchTerminatedBlock = createBlock(false);
931
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000932 // Now process the switch body. The code after the switch is the implicit
933 // successor.
934 Succ = SwitchSuccessor;
935 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000936
937 // When visiting the body, the case statements should automatically get
938 // linked up to the switch. We also don't keep a pointer to the body,
939 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000940 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000941 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000942 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000943 if (Block) FinishBlock(BodyBlock);
944
Ted Kremenek295222c2008-02-13 21:46:34 +0000945 // If we have no "default:" case, the default transition is to the
946 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000947 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000948
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000949 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000950 SwitchTerminatedBlock->setTerminator(Terminator);
951 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000952 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000953
Ted Kremenek411cdee2008-04-16 21:10:48 +0000954 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000955}
956
Ted Kremenek411cdee2008-04-16 21:10:48 +0000957CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000958 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000959 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000960
Ted Kremenek411cdee2008-04-16 21:10:48 +0000961 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000962 CFGBlock* CaseBlock = Block;
963 if (!CaseBlock) CaseBlock = createBlock();
964
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000965 // Cases statements partition blocks, so this is the top of
966 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000967 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000968 FinishBlock(CaseBlock);
969
970 // Add this block to the list of successors for the block with the
971 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000972 assert (SwitchTerminatedBlock);
973 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000974
975 // We set Block to NULL to allow lazy creation of a new block (if necessary)
976 Block = NULL;
977
978 // This block is now the implicit successor of other blocks.
979 Succ = CaseBlock;
980
Ted Kremenek2677ea82008-03-15 07:45:02 +0000981 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000982}
Ted Kremenek295222c2008-02-13 21:46:34 +0000983
Ted Kremenek411cdee2008-04-16 21:10:48 +0000984CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
985 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000986 DefaultCaseBlock = Block;
987 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
988
989 // Default statements partition blocks, so this is the top of
990 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000991 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000992 FinishBlock(DefaultCaseBlock);
993
994 // Unlike case statements, we don't add the default block to the
995 // successors for the switch statement immediately. This is done
996 // when we finish processing the switch statement. This allows for
997 // the default case (including a fall-through to the code after the
998 // switch statement) to always be the last successor of a switch-terminated
999 // block.
1000
1001 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1002 Block = NULL;
1003
1004 // This block is now the implicit successor of other blocks.
1005 Succ = DefaultCaseBlock;
1006
1007 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001008}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001009
Ted Kremenek19bb3562007-08-28 19:26:49 +00001010CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1011 // Lazily create the indirect-goto dispatch block if there isn't one
1012 // already.
1013 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1014
1015 if (!IBlock) {
1016 IBlock = createBlock(false);
1017 cfg->setIndirectGotoBlock(IBlock);
1018 }
1019
1020 // IndirectGoto is a control-flow statement. Thus we stop processing the
1021 // current block and create a new one.
1022 if (Block) FinishBlock(Block);
1023 Block = createBlock(false);
1024 Block->setTerminator(I);
1025 Block->addSuccessor(IBlock);
1026 return addStmt(I->getTarget());
1027}
1028
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001029
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001030} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001031
1032/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1033/// block has no successors or predecessors. If this is the first block
1034/// created in the CFG, it is automatically set to be the Entry and Exit
1035/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001036CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001037 bool first_block = begin() == end();
1038
1039 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001040 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001041
1042 // If this is the first block, set it as the Entry and Exit.
1043 if (first_block) Entry = Exit = &front();
1044
1045 // Return the block.
1046 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001047}
1048
Ted Kremenek026473c2007-08-23 16:51:22 +00001049/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1050/// CFG is returned to the caller.
1051CFG* CFG::buildCFG(Stmt* Statement) {
1052 CFGBuilder Builder;
1053 return Builder.buildCFG(Statement);
1054}
1055
1056/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001057void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1058
Ted Kremenek63f58872007-10-01 19:33:33 +00001059//===----------------------------------------------------------------------===//
1060// CFG: Queries for BlkExprs.
1061//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001062
Ted Kremenek63f58872007-10-01 19:33:33 +00001063namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001064 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001065}
1066
Ted Kremenek411cdee2008-04-16 21:10:48 +00001067static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1068 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001069 return;
1070
Ted Kremenek411cdee2008-04-16 21:10:48 +00001071 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001072 if (!*I) continue;
1073
1074 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1075 if (B->isAssignmentOp()) Set.insert(B);
1076
1077 FindSubExprAssignments(*I, Set);
1078 }
1079}
1080
Ted Kremenek63f58872007-10-01 19:33:33 +00001081static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1082 BlkExprMapTy* M = new BlkExprMapTy();
1083
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001084 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001085 // only assignments that we want to *possibly* register as a block-level
1086 // expression. Basically, if an assignment occurs both in a subexpression
1087 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001088 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1089
Ted Kremenek63f58872007-10-01 19:33:33 +00001090 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1091 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001092 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001093
Ted Kremenek411cdee2008-04-16 21:10:48 +00001094 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1095
1096 // Iterate over the statements again on identify the Expr* and Stmt* at
1097 // the block-level that are block-level expressions.
1098
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001099 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001100 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001101
Ted Kremenek411cdee2008-04-16 21:10:48 +00001102 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001103 // Assignment expressions that are not nested within another
1104 // expression are really "statements" whose value is never
1105 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001106 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001107 continue;
1108 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001109 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001110 // Special handling for statement expressions. The last statement
1111 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001112 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001113 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001114 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001115 (*M)[C->body_back()] = x;
1116 }
1117 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001118
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001119 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001120 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001121 }
1122
Ted Kremenek411cdee2008-04-16 21:10:48 +00001123 // Look at terminators. The condition is a block-level expression.
1124
1125 Expr* Exp = I->getTerminatorCondition();
1126
1127 if (Exp && M->find(Exp) == M->end()) {
1128 unsigned x = M->size();
1129 (*M)[Exp] = x;
1130 }
1131 }
1132
Ted Kremenek63f58872007-10-01 19:33:33 +00001133 return M;
1134}
1135
Ted Kremenek86946742008-01-17 20:48:37 +00001136CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1137 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001138 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1139
1140 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001141 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001142
1143 if (I == M->end()) return CFG::BlkExprNumTy();
1144 else return CFG::BlkExprNumTy(I->second);
1145}
1146
1147unsigned CFG::getNumBlkExprs() {
1148 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1149 return M->size();
1150 else {
1151 // We assume callers interested in the number of BlkExprs will want
1152 // the map constructed if it doesn't already exist.
1153 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1154 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1155 }
1156}
1157
Ted Kremenek274f4332008-04-28 18:00:46 +00001158//===----------------------------------------------------------------------===//
1159// Internal Block-Edge Set; used for modeling persistent <CFGBlock*,CFGBlock*>
1160// pairs for use with ProgramPoint.
1161//===----------------------------------------------------------------------===//
1162
1163typedef std::pair<CFGBlock*,CFGBlock*> BPairTy;
1164
1165namespace llvm {
1166 template<> struct FoldingSetTrait<BPairTy*> {
1167 static void Profile(const BPairTy* X, FoldingSetNodeID& profile) {
1168 profile.AddPointer(X->first);
1169 profile.AddPointer(X->second);
1170 }
1171 };
1172}
1173
1174typedef llvm::FoldingSetNodeWrapper<BPairTy*> PersistPairTy;
1175typedef llvm::FoldingSet<PersistPairTy> BlkEdgeSetTy;
Ted Kremenek83c01da2008-01-11 00:40:29 +00001176
1177const std::pair<CFGBlock*,CFGBlock*>*
1178CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1179
Ted Kremenek274f4332008-04-28 18:00:46 +00001180 llvm::BumpPtrAllocator*& Alloc =
1181 reinterpret_cast<llvm::BumpPtrAllocator*&>(Allocator);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001182
Ted Kremenek274f4332008-04-28 18:00:46 +00001183 if (!Alloc)
1184 Alloc = new llvm::BumpPtrAllocator();
1185
1186 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1187
1188 if (!p)
1189 p = new BlkEdgeSetTy();
1190
1191 // Profile the edges.
1192 llvm::FoldingSetNodeID profile;
1193 void* InsertPos;
1194
1195 profile.AddPointer(B1);
1196 profile.AddPointer(B2);
1197
1198 PersistPairTy* V = p->FindNodeOrInsertPos(profile, InsertPos);
1199
1200 if (!V) {
1201 assert (llvm::AlignOf<BPairTy>::Alignment_LessEqual_8Bytes);
1202
1203 // Allocate the pair, forcing an 8-byte alignment.
1204 BPairTy* pair = (BPairTy*) Alloc->Allocate(sizeof(*pair), 8);
1205
1206 new (pair) BPairTy(const_cast<CFGBlock*>(B1),
1207 const_cast<CFGBlock*>(B2));
1208
1209 // Allocate the meta data to store the pair in the FoldingSet.
1210 PersistPairTy* ppair = (PersistPairTy*) Alloc->Allocate<PersistPairTy>();
1211 new (ppair) PersistPairTy(pair);
1212
1213 p->InsertNode(ppair, InsertPos);
1214
1215 return pair;
1216 }
1217
1218 return V->getValue();
Ted Kremenek83c01da2008-01-11 00:40:29 +00001219}
1220
Ted Kremenek274f4332008-04-28 18:00:46 +00001221//===----------------------------------------------------------------------===//
1222// Cleanup: CFG dstor.
1223//===----------------------------------------------------------------------===//
1224
Ted Kremenek63f58872007-10-01 19:33:33 +00001225CFG::~CFG() {
1226 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001227 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek274f4332008-04-28 18:00:46 +00001228 delete reinterpret_cast<llvm::BumpPtrAllocator*> (Allocator);
Ted Kremenek63f58872007-10-01 19:33:33 +00001229}
1230
Ted Kremenek7dba8602007-08-29 21:56:09 +00001231//===----------------------------------------------------------------------===//
1232// CFG pretty printing
1233//===----------------------------------------------------------------------===//
1234
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001235namespace {
1236
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001237class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001238
Ted Kremenek42a509f2007-08-31 21:30:12 +00001239 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1240 StmtMapTy StmtMap;
1241 signed CurrentBlock;
1242 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001243
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001244public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001245
Ted Kremenek42a509f2007-08-31 21:30:12 +00001246 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1247 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1248 unsigned j = 1;
1249 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1250 BI != BEnd; ++BI, ++j )
1251 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1252 }
1253 }
1254
1255 virtual ~StmtPrinterHelper() {}
1256
1257 void setBlockID(signed i) { CurrentBlock = i; }
1258 void setStmtID(unsigned i) { CurrentStmt = i; }
1259
Ted Kremenek411cdee2008-04-16 21:10:48 +00001260 virtual bool handledStmt(Stmt* Terminator, std::ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001261
Ted Kremenek411cdee2008-04-16 21:10:48 +00001262 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001263
1264 if (I == StmtMap.end())
1265 return false;
1266
1267 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1268 && I->second.second == CurrentStmt)
1269 return false;
1270
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001271 OS << "[B" << I->second.first << "." << I->second.second << "]";
1272 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001273 }
1274};
1275
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001276class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1277 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1278
Ted Kremenek42a509f2007-08-31 21:30:12 +00001279 std::ostream& OS;
1280 StmtPrinterHelper* Helper;
1281public:
1282 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1283 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001284
1285 void VisitIfStmt(IfStmt* I) {
1286 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001287 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001288 }
1289
1290 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001291 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001292
1293 void VisitForStmt(ForStmt* F) {
1294 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001295 if (F->getInit()) OS << "...";
1296 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001297 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001298 OS << "; ";
1299 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001300 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001301 }
1302
1303 void VisitWhileStmt(WhileStmt* W) {
1304 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001305 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001306 }
1307
1308 void VisitDoStmt(DoStmt* D) {
1309 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001310 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001311 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001312
Ted Kremenek411cdee2008-04-16 21:10:48 +00001313 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001314 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001315 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001316 }
1317
Ted Kremenek805e9a82007-08-31 21:49:40 +00001318 void VisitConditionalOperator(ConditionalOperator* C) {
1319 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001320 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001321 }
1322
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001323 void VisitChooseExpr(ChooseExpr* C) {
1324 OS << "__builtin_choose_expr( ";
1325 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001326 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001327 }
1328
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001329 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1330 OS << "goto *";
1331 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001332 }
1333
Ted Kremenek805e9a82007-08-31 21:49:40 +00001334 void VisitBinaryOperator(BinaryOperator* B) {
1335 if (!B->isLogicalOp()) {
1336 VisitExpr(B);
1337 return;
1338 }
1339
1340 B->getLHS()->printPretty(OS,Helper);
1341
1342 switch (B->getOpcode()) {
1343 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001344 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001345 return;
1346 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001347 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001348 return;
1349 default:
1350 assert(false && "Invalid logical operator.");
1351 }
1352 }
1353
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001354 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001355 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001356 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001357};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001358
1359
Ted Kremenek411cdee2008-04-16 21:10:48 +00001360void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001361 if (Helper) {
1362 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001363 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001364 CompoundStmt* Sub = SE->getSubStmt();
1365
1366 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001367 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001368 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001369 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001370 return;
1371 }
1372 }
1373
1374 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001375 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001376 if (B->getOpcode() == BinaryOperator::Comma) {
1377 OS << "... , ";
1378 Helper->handledStmt(B->getRHS(),OS);
1379 OS << '\n';
1380 return;
1381 }
1382 }
1383 }
1384
Ted Kremenek411cdee2008-04-16 21:10:48 +00001385 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001386
1387 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001388 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001389}
1390
Ted Kremenek42a509f2007-08-31 21:30:12 +00001391void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1392 StmtPrinterHelper* Helper, bool print_edges) {
1393
1394 if (Helper) Helper->setBlockID(B.getBlockID());
1395
Ted Kremenek7dba8602007-08-29 21:56:09 +00001396 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001397 OS << "\n [ B" << B.getBlockID();
1398
1399 if (&B == &cfg->getEntry())
1400 OS << " (ENTRY) ]\n";
1401 else if (&B == &cfg->getExit())
1402 OS << " (EXIT) ]\n";
1403 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001404 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001405 else
1406 OS << " ]\n";
1407
Ted Kremenek9cffe732007-08-29 23:20:49 +00001408 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001409 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001410
1411 if (print_edges)
1412 OS << " ";
1413
Ted Kremenek411cdee2008-04-16 21:10:48 +00001414 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001415 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001416 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001417 OS << "case ";
1418 C->getLHS()->printPretty(OS);
1419 if (C->getRHS()) {
1420 OS << " ... ";
1421 C->getRHS()->printPretty(OS);
1422 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001423 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001424 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001425 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426 else
1427 assert(false && "Invalid label statement in CFGBlock.");
1428
Ted Kremenek9cffe732007-08-29 23:20:49 +00001429 OS << ":\n";
1430 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001431
Ted Kremenekfddd5182007-08-21 21:42:03 +00001432 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001433 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001434
1435 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1436 I != E ; ++I, ++j ) {
1437
Ted Kremenek9cffe732007-08-29 23:20:49 +00001438 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001439 if (print_edges)
1440 OS << " ";
1441
1442 OS << std::setw(3) << j << ": ";
1443
1444 if (Helper)
1445 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001446
1447 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001448 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001449
Ted Kremenek9cffe732007-08-29 23:20:49 +00001450 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001451 if (B.getTerminator()) {
1452 if (print_edges)
1453 OS << " ";
1454
Ted Kremenek9cffe732007-08-29 23:20:49 +00001455 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001456
1457 if (Helper) Helper->setBlockID(-1);
1458
1459 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1460 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001461 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001462 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001463
Ted Kremenek9cffe732007-08-29 23:20:49 +00001464 if (print_edges) {
1465 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001466 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001467 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001468
Ted Kremenek42a509f2007-08-31 21:30:12 +00001469 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1470 I != E; ++I, ++i) {
1471
1472 if (i == 8 || (i-8) == 0)
1473 OS << "\n ";
1474
Ted Kremenek9cffe732007-08-29 23:20:49 +00001475 OS << " B" << (*I)->getBlockID();
1476 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001477
1478 OS << '\n';
1479
1480 // Print the successors of this block.
1481 OS << " Successors (" << B.succ_size() << "):";
1482 i = 0;
1483
1484 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1485 I != E; ++I, ++i) {
1486
1487 if (i == 8 || (i-8) % 10 == 0)
1488 OS << "\n ";
1489
1490 OS << " B" << (*I)->getBlockID();
1491 }
1492
Ted Kremenek9cffe732007-08-29 23:20:49 +00001493 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001494 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001495}
1496
1497} // end anonymous namespace
1498
1499/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001500void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001501
1502/// print - A simple pretty printer of a CFG that outputs to an ostream.
1503void CFG::print(std::ostream& OS) const {
1504
1505 StmtPrinterHelper Helper(this);
1506
1507 // Print the entry block.
1508 print_block(OS, this, getEntry(), &Helper, true);
1509
1510 // Iterate through the CFGBlocks and print them one by one.
1511 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1512 // Skip the entry block, because we already printed it.
1513 if (&(*I) == &getEntry() || &(*I) == &getExit())
1514 continue;
1515
1516 print_block(OS, this, *I, &Helper, true);
1517 }
1518
1519 // Print the exit block.
1520 print_block(OS, this, getExit(), &Helper, true);
1521}
1522
1523/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001524void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001525
1526/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1527/// Generally this will only be called from CFG::print.
1528void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1529 StmtPrinterHelper Helper(cfg);
1530 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001531}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001532
Ted Kremeneka2925852008-01-30 23:02:42 +00001533/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1534void CFGBlock::printTerminator(std::ostream& OS) const {
1535 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1536 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1537}
1538
Ted Kremenek411cdee2008-04-16 21:10:48 +00001539Expr* CFGBlock::getTerminatorCondition() {
1540
1541 if (!Terminator)
1542 return NULL;
1543
1544 Expr* E = NULL;
1545
1546 switch (Terminator->getStmtClass()) {
1547 default:
1548 break;
1549
1550 case Stmt::ForStmtClass:
1551 E = cast<ForStmt>(Terminator)->getCond();
1552 break;
1553
1554 case Stmt::WhileStmtClass:
1555 E = cast<WhileStmt>(Terminator)->getCond();
1556 break;
1557
1558 case Stmt::DoStmtClass:
1559 E = cast<DoStmt>(Terminator)->getCond();
1560 break;
1561
1562 case Stmt::IfStmtClass:
1563 E = cast<IfStmt>(Terminator)->getCond();
1564 break;
1565
1566 case Stmt::ChooseExprClass:
1567 E = cast<ChooseExpr>(Terminator)->getCond();
1568 break;
1569
1570 case Stmt::IndirectGotoStmtClass:
1571 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1572 break;
1573
1574 case Stmt::SwitchStmtClass:
1575 E = cast<SwitchStmt>(Terminator)->getCond();
1576 break;
1577
1578 case Stmt::ConditionalOperatorClass:
1579 E = cast<ConditionalOperator>(Terminator)->getCond();
1580 break;
1581
1582 case Stmt::BinaryOperatorClass: // '&&' and '||'
1583 E = cast<BinaryOperator>(Terminator)->getLHS();
1584 break;
1585 }
1586
1587 return E ? E->IgnoreParens() : NULL;
1588}
1589
Ted Kremeneka2925852008-01-30 23:02:42 +00001590
Ted Kremenek7dba8602007-08-29 21:56:09 +00001591//===----------------------------------------------------------------------===//
1592// CFG Graphviz Visualization
1593//===----------------------------------------------------------------------===//
1594
Ted Kremenek42a509f2007-08-31 21:30:12 +00001595
1596#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001597static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001598#endif
1599
1600void CFG::viewCFG() const {
1601#ifndef NDEBUG
1602 StmtPrinterHelper H(this);
1603 GraphHelper = &H;
1604 llvm::ViewGraph(this,"CFG");
1605 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001606#endif
1607}
1608
Ted Kremenek7dba8602007-08-29 21:56:09 +00001609namespace llvm {
1610template<>
1611struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1612 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1613
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001614#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001615 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001616 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001617 std::string OutStr = Out.str();
1618
1619 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1620
1621 // Process string output to make it nicer...
1622 for (unsigned i = 0; i != OutStr.length(); ++i)
1623 if (OutStr[i] == '\n') { // Left justify
1624 OutStr[i] = '\\';
1625 OutStr.insert(OutStr.begin()+i+1, 'l');
1626 }
1627
1628 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001629#else
1630 return "";
1631#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001632 }
1633};
1634} // end namespace llvm