blob: c0b1b96967c4b0d22bc06e42db3e44a50c74979a [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"
Ted Kremenekc310e932007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenek274f4332008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremeneka95d3752008-09-13 05:16:45 +000024#include <llvm/Support/Format.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
Ted Kremenekc7eb9032008-08-06 23:20:50 +000045static SourceLocation GetEndLoc(ScopedDecl* D) {
46 if (VarDecl* VD = dyn_cast<VarDecl>(D))
47 if (Expr* Ex = VD->getInit())
48 return Ex->getSourceRange().getEnd();
49
50 return D->getLocation();
51}
52
53class VISIBILITY_HIDDEN UnaryDeclStmt : public DeclStmt {
54 Stmt* Ex;
55public:
56 UnaryDeclStmt(ScopedDecl* D)
57 : DeclStmt(D, D->getLocation(), GetEndLoc(D)), Ex(0) {
58 if (VarDecl* VD = dyn_cast<VarDecl>(D))
59 Ex = VD->getInit();
60 }
61
62 virtual ~UnaryDeclStmt() {}
63 virtual void Destroy(ASTContext& Ctx) { assert(false && "Do not call"); }
64
65 virtual child_iterator child_begin() {
66 return Ex ? &Ex : 0;
67 }
68 virtual child_iterator child_end() {
69 return Ex ? &Ex + 1 : 0;
70 }
71 virtual decl_iterator decl_begin() {
72 return getDecl();
73 }
74 virtual decl_iterator decl_end() {
75 ScopedDecl* D = getDecl();
76 return D ? D->getNextDeclarator() : 0;
77 }
78};
79
Ted Kremeneka34ea072008-08-04 22:51:42 +000080/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenekfddd5182007-08-21 21:42:03 +000081/// The builder is stateful: an instance of the builder should be used to only
82/// construct a single CFG.
83///
84/// Example usage:
85///
86/// CFGBuilder builder;
87/// CFG* cfg = builder.BuildAST(stmt1);
88///
Ted Kremenekc310e932007-08-21 22:06:14 +000089/// CFG construction is done via a recursive walk of an AST.
90/// We actually parse the AST in reverse order so that the successor
91/// of a basic block is constructed prior to its predecessor. This
92/// allows us to nicely capture implicit fall-throughs without extra
93/// basic blocks.
94///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000095class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000096 CFG* cfg;
97 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000098 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000099 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +0000100 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +0000101 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000102 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000103
Ted Kremenek19bb3562007-08-28 19:26:49 +0000104 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +0000105 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
106 LabelMapTy LabelMap;
107
Ted Kremenek19bb3562007-08-28 19:26:49 +0000108 // A list of blocks that end with a "goto" that must be backpatched to
109 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +0000110 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +0000111 BackpatchBlocksTy BackpatchBlocks;
112
Ted Kremenek19bb3562007-08-28 19:26:49 +0000113 // A list of labels whose address has been taken (for indirect gotos).
114 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
115 LabelSetTy AddressTakenLabels;
116
Ted Kremenekfddd5182007-08-21 21:42:03 +0000117public:
Ted Kremenek026473c2007-08-23 16:51:22 +0000118 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +0000119 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000120 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +0000121 // Create an empty CFG.
122 cfg = new CFG();
123 }
124
125 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +0000126
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000127 // buildCFG - Used by external clients to construct the CFG.
128 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +0000129
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000130 // Visitors to walk an AST and construct the CFG. Called by
131 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000132
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000133 CFGBlock* VisitStmt(Stmt* Statement);
134 CFGBlock* VisitNullStmt(NullStmt* Statement);
135 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
136 CFGBlock* VisitIfStmt(IfStmt* I);
137 CFGBlock* VisitReturnStmt(ReturnStmt* R);
138 CFGBlock* VisitLabelStmt(LabelStmt* L);
139 CFGBlock* VisitGotoStmt(GotoStmt* G);
140 CFGBlock* VisitForStmt(ForStmt* F);
141 CFGBlock* VisitWhileStmt(WhileStmt* W);
142 CFGBlock* VisitDoStmt(DoStmt* D);
143 CFGBlock* VisitContinueStmt(ContinueStmt* C);
144 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000145 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
146 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek295222c2008-02-13 21:46:34 +0000147 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000148 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000149
Ted Kremenek4102af92008-03-13 03:04:22 +0000150 // FIXME: Add support for ObjC-specific control-flow structures.
151
Ted Kremenek274f4332008-04-28 18:00:46 +0000152 // NYS == Not Yet Supported
153 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000154 badCFG = true;
155 return Block;
156 }
157
Ted Kremenek274f4332008-04-28 18:00:46 +0000158 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
159 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
160 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
161 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
162 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
163
164 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
165 return NYS();
Ted Kremenek4102af92008-03-13 03:04:22 +0000166 }
167
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000168private:
169 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000170 CFGBlock* addStmt(Stmt* Terminator);
171 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
172 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000173 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000174 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000175 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000176
Ted Kremenek4102af92008-03-13 03:04:22 +0000177 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000178};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000179
180/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
181/// represent an arbitrary statement. Examples include a single expression
182/// or a function body (compound statement). The ownership of the returned
183/// CFG is transferred to the caller. If CFG construction fails, this method
184/// returns NULL.
185CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000186 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000187 if (!Statement) return NULL;
188
Ted Kremenek4102af92008-03-13 03:04:22 +0000189 badCFG = false;
190
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000191 // Create an empty block that will serve as the exit block for the CFG.
192 // Since this is the first block added to the CFG, it will be implicitly
193 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000194 Succ = createBlock();
195 assert (Succ == &cfg->getExit());
196 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000197
198 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000199 CFGBlock* B = Visit(Statement);
200 if (!B) B = Succ;
201
202 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203 // Finalize the last constructed block. This usually involves
204 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000205 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000206
207 // Backpatch the gotos whose label -> block mappings we didn't know
208 // when we encountered them.
209 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
210 E = BackpatchBlocks.end(); I != E; ++I ) {
211
212 CFGBlock* B = *I;
213 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
214 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
215
216 // If there is no target for the goto, then we are looking at an
217 // incomplete AST. Handle this by not registering a successor.
218 if (LI == LabelMap.end()) continue;
219
220 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000221 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000222
Ted Kremenek19bb3562007-08-28 19:26:49 +0000223 // Add successors to the Indirect Goto Dispatch block (if we have one).
224 if (CFGBlock* B = cfg->getIndirectGotoBlock())
225 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
226 E = AddressTakenLabels.end(); I != E; ++I ) {
227
228 // Lookup the target block.
229 LabelMapTy::iterator LI = LabelMap.find(*I);
230
231 // If there is no target block that contains label, then we are looking
232 // at an incomplete AST. Handle this by not registering a successor.
233 if (LI == LabelMap.end()) continue;
234
235 B->addSuccessor(LI->second);
236 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000237
Ted Kremenek94b33162007-09-17 16:18:02 +0000238 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000239 }
240
241 // Create an empty entry block that has no predecessors.
242 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000243
Ted Kremenek4102af92008-03-13 03:04:22 +0000244 if (badCFG) {
245 delete cfg;
246 cfg = NULL;
247 return NULL;
248 }
249
Ted Kremenek322f58d2007-09-26 21:23:31 +0000250 // NULL out cfg so that repeated calls to the builder will fail and that
251 // the ownership of the constructed CFG is passed to the caller.
252 CFG* t = cfg;
253 cfg = NULL;
254 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000255}
256
257/// createBlock - Used to lazily create blocks that are connected
258/// to the current (global) succcessor.
259CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000260 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000261 if (add_successor && Succ) B->addSuccessor(Succ);
262 return B;
263}
264
265/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000266/// we must reverse the statements because they have been inserted
267/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000268void CFGBuilder::FinishBlock(CFGBlock* B) {
269 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000270 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000271}
272
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000273/// addStmt - Used to add statements/expressions to the current CFGBlock
274/// "Block". This method calls WalkAST on the passed statement to see if it
275/// contains any short-circuit expressions. If so, it recursively creates
276/// the necessary blocks for such expressions. It returns the "topmost" block
277/// of the created blocks, or the original value of "Block" when this method
278/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000279CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000280 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000281 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000282}
283
284/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000285/// add extra blocks for ternary operators, &&, and ||. We also
286/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000287CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
288 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000289 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000290 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000291
292 // Create the confluence block that will "merge" the results
293 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000294 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
295 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000296 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000297
298 // Create a block for the LHS expression if there is an LHS expression.
299 // A GCC extension allows LHS to be NULL, causing the condition to
300 // be the value that is returned instead.
301 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000302 Succ = ConfluenceBlock;
303 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000304 CFGBlock* LHSBlock = NULL;
305 if (C->getLHS()) {
306 LHSBlock = Visit(C->getLHS());
307 FinishBlock(LHSBlock);
308 Block = NULL;
309 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000310
Ted Kremenekecc04c92007-11-26 18:20:26 +0000311 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000312 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000313 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000314 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000315
Ted Kremenekecc04c92007-11-26 18:20:26 +0000316 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000317 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000318
319 if (LHSBlock)
320 Block->addSuccessor(LHSBlock);
321 else {
322 // If we have no LHS expression, add the ConfluenceBlock as a direct
323 // successor for the block containing the condition. Moreover,
324 // we need to reverse the order of the predecessors in the
325 // ConfluenceBlock because the RHSBlock will have been added to
326 // the succcessors already, and we want the first predecessor to the
327 // the block containing the expression for the case when the ternary
328 // expression evaluates to true.
329 Block->addSuccessor(ConfluenceBlock);
330 assert (ConfluenceBlock->pred_size() == 2);
331 std::reverse(ConfluenceBlock->pred_begin(),
332 ConfluenceBlock->pred_end());
333 }
334
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000335 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000336
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000337 Block->setTerminator(C);
338 return addStmt(C->getCond());
339 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000340
341 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000342 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000343
344 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
345 ConfluenceBlock->appendStmt(C);
346 FinishBlock(ConfluenceBlock);
347
348 Succ = ConfluenceBlock;
349 Block = NULL;
350 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000351 FinishBlock(LHSBlock);
352
Ted Kremenek49a436d2007-08-31 17:03:41 +0000353 Succ = ConfluenceBlock;
354 Block = NULL;
355 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000356 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000357
358 Block = createBlock(false);
359 Block->addSuccessor(LHSBlock);
360 Block->addSuccessor(RHSBlock);
361 Block->setTerminator(C);
362 return addStmt(C->getCond());
363 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000364
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000365 case Stmt::DeclStmtClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000366 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000367
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000368 if (!D->getNextDeclarator()) {
369 Block->appendStmt(Terminator);
370 return WalkAST_VisitDeclSubExpr(D);
371 }
372 else {
373 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
374 BufTy Buf;
375 CFGBlock* B = 0;
376 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
377 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
378 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
379 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
380 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
381
382 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
383 // get automatically freed with the CFG.
384 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
385 // Append the fake DeclStmt to block.
386 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
387 B = WalkAST_VisitDeclSubExpr(*I);
388 }
389 return B;
390 }
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000391 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000392
Ted Kremenek19bb3562007-08-28 19:26:49 +0000393 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000394 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000395 AddressTakenLabels.insert(A->getLabel());
396
Ted Kremenek411cdee2008-04-16 21:10:48 +0000397 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000398 return Block;
399 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000400
Ted Kremenek15c27a82007-08-28 18:30:10 +0000401 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000402 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000403
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000404 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000406
407 // sizeof(expressions). For such expressions,
408 // the subexpression is not really evaluated, so
409 // we don't care about control-flow within the sizeof.
410 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000411 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000412 return Block;
413 }
414
415 break;
416 }
417
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000418 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000419 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000420
421 if (B->isLogicalOp()) { // && or ||
422 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
423 ConfluenceBlock->appendStmt(B);
424 FinishBlock(ConfluenceBlock);
425
426 // create the block evaluating the LHS
427 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000428 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000429
430 // create the block evaluating the RHS
431 Succ = ConfluenceBlock;
432 Block = NULL;
433 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000434
435 // Now link the LHSBlock with RHSBlock.
436 if (B->getOpcode() == BinaryOperator::LOr) {
437 LHSBlock->addSuccessor(ConfluenceBlock);
438 LHSBlock->addSuccessor(RHSBlock);
439 }
440 else {
441 assert (B->getOpcode() == BinaryOperator::LAnd);
442 LHSBlock->addSuccessor(RHSBlock);
443 LHSBlock->addSuccessor(ConfluenceBlock);
444 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000445
446 // Generate the blocks for evaluating the LHS.
447 Block = LHSBlock;
448 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000449 }
450 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
451 Block->appendStmt(B);
452 addStmt(B->getRHS());
453 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000454 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000455
456 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000457 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000458
459 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000460 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000461
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000462 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000463 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000464 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000465
Ted Kremenek411cdee2008-04-16 21:10:48 +0000466 if (AlwaysAddStmt) Block->appendStmt(Terminator);
467 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000468}
469
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000470static VariableArrayType* FindVA(Type* t) {
471 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
472 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
473 if (vat->getSizeExpr())
474 return vat;
475
476 t = vt->getElementType().getTypePtr();
477 }
478
479 return 0;
480}
481
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000482/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
483/// for initializers in Decls.
484CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
485 VarDecl* VD = dyn_cast<VarDecl>(D);
486
487 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000488 return Block;
489
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000490 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000491
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000492 if (Init) {
493 // Optimization: Don't create separate block-level statements for literals.
494 switch (Init->getStmtClass()) {
495 case Stmt::IntegerLiteralClass:
496 case Stmt::CharacterLiteralClass:
497 case Stmt::StringLiteralClass:
498 break;
499 default:
500 Block = addStmt(Init);
501 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000502 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000503
504 // If the type of VD is a VLA, then we must process its size expressions.
505 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
506 VA = FindVA(VA->getElementType().getTypePtr()))
507 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000508
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000509 return Block;
510}
511
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000512/// WalkAST_VisitChildren - Utility method to call WalkAST on the
513/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000514CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000515 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000516 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000517 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000518 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000519
520 return B;
521}
522
Ted Kremenek15c27a82007-08-28 18:30:10 +0000523/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
524/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000525CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
526 Block->appendStmt(Terminator);
527 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000528}
529
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000530/// VisitStmt - Handle statements with no branching control flow.
531CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
532 // We cannot assume that we are in the middle of a basic block, since
533 // the CFG might only be constructed for this single statement. If
534 // we have no current basic block, just create one lazily.
535 if (!Block) Block = createBlock();
536
537 // Simply add the statement to the current block. We actually
538 // insert statements in reverse order; this order is reversed later
539 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000540 addStmt(Statement);
541
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000542 return Block;
543}
544
545CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
546 return Block;
547}
548
549CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000550
551 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000552
Ted Kremenekd34066c2008-02-26 00:22:58 +0000553 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
554 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000555 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000556 }
557
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000558 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000559}
560
561CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
562 // We may see an if statement in the middle of a basic block, or
563 // it may be the first statement we are processing. In either case,
564 // we create a new basic block. First, we create the blocks for
565 // the then...else statements, and then we create the block containing
566 // the if statement. If we were in the middle of a block, we
567 // stop processing that block and reverse its statements. That block
568 // is then the implicit successor for the "then" and "else" clauses.
569
570 // The block we were proccessing is now finished. Make it the
571 // successor block.
572 if (Block) {
573 Succ = Block;
574 FinishBlock(Block);
575 }
576
577 // Process the false branch. NULL out Block so that the recursive
578 // call to Visit will create a new basic block.
579 // Null out Block so that all successor
580 CFGBlock* ElseBlock = Succ;
581
582 if (Stmt* Else = I->getElse()) {
583 SaveAndRestore<CFGBlock*> sv(Succ);
584
585 // NULL out Block so that the recursive call to Visit will
586 // create a new basic block.
587 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000588 ElseBlock = Visit(Else);
589
590 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
591 ElseBlock = sv.get();
592 else if (Block)
593 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000594 }
595
596 // Process the true branch. NULL out Block so that the recursive
597 // call to Visit will create a new basic block.
598 // Null out Block so that all successor
599 CFGBlock* ThenBlock;
600 {
601 Stmt* Then = I->getThen();
602 assert (Then);
603 SaveAndRestore<CFGBlock*> sv(Succ);
604 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000605 ThenBlock = Visit(Then);
606
607 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
608 ThenBlock = sv.get();
609 else if (Block)
610 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000611 }
612
613 // Now create a new block containing the if statement.
614 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000615
616 // Set the terminator of the new block to the If statement.
617 Block->setTerminator(I);
618
619 // Now add the successors.
620 Block->addSuccessor(ThenBlock);
621 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000622
623 // Add the condition as the last statement in the new block. This
624 // may create new blocks as the condition may contain control-flow. Any
625 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000626 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000627}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000628
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000629
630CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
631 // If we were in the middle of a block we stop processing that block
632 // and reverse its statements.
633 //
634 // NOTE: If a "return" appears in the middle of a block, this means
635 // that the code afterwards is DEAD (unreachable). We still
636 // keep a basic block for that code; a simple "mark-and-sweep"
637 // from the entry block will be able to report such dead
638 // blocks.
639 if (Block) FinishBlock(Block);
640
641 // Create the new block.
642 Block = createBlock(false);
643
644 // The Exit block is the only successor.
645 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000646
647 // Add the return statement to the block. This may create new blocks
648 // if R contains control-flow (short-circuit operations).
649 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000650}
651
652CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
653 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000654 Visit(L->getSubStmt());
655 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000656
657 if (!LabelBlock) // This can happen when the body is empty, i.e.
658 LabelBlock=createBlock(); // scopes that only contains NullStmts.
659
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000660 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
661 LabelMap[ L ] = LabelBlock;
662
663 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000664 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000665 // label (and we have already processed the substatement) there is no
666 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000667 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000668 FinishBlock(LabelBlock);
669
670 // We set Block to NULL to allow lazy creation of a new block
671 // (if necessary);
672 Block = NULL;
673
674 // This block is now the implicit successor of other blocks.
675 Succ = LabelBlock;
676
677 return LabelBlock;
678}
679
680CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
681 // Goto is a control-flow statement. Thus we stop processing the
682 // current block and create a new one.
683 if (Block) FinishBlock(Block);
684 Block = createBlock(false);
685 Block->setTerminator(G);
686
687 // If we already know the mapping to the label block add the
688 // successor now.
689 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
690
691 if (I == LabelMap.end())
692 // We will need to backpatch this block later.
693 BackpatchBlocks.push_back(Block);
694 else
695 Block->addSuccessor(I->second);
696
697 return Block;
698}
699
700CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
701 // "for" is a control-flow statement. Thus we stop processing the
702 // current block.
703
704 CFGBlock* LoopSuccessor = NULL;
705
706 if (Block) {
707 FinishBlock(Block);
708 LoopSuccessor = Block;
709 }
710 else LoopSuccessor = Succ;
711
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000712 // Because of short-circuit evaluation, the condition of the loop
713 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
714 // blocks that evaluate the condition.
715 CFGBlock* ExitConditionBlock = createBlock(false);
716 CFGBlock* EntryConditionBlock = ExitConditionBlock;
717
718 // Set the terminator for the "exit" condition block.
719 ExitConditionBlock->setTerminator(F);
720
721 // Now add the actual condition to the condition block. Because the
722 // condition itself may contain control-flow, new blocks may be created.
723 if (Stmt* C = F->getCond()) {
724 Block = ExitConditionBlock;
725 EntryConditionBlock = addStmt(C);
726 if (Block) FinishBlock(EntryConditionBlock);
727 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000728
729 // The condition block is the implicit successor for the loop body as
730 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000731 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000732
733 // Now create the loop body.
734 {
735 assert (F->getBody());
736
737 // Save the current values for Block, Succ, and continue and break targets
738 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
739 save_continue(ContinueTargetBlock),
740 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000741
Ted Kremenekaf603f72007-08-30 18:39:40 +0000742 // Create a new block to contain the (bottom) of the loop body.
743 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000744
Ted Kremeneke9334502008-09-04 21:48:47 +0000745 if (Stmt* I = F->getInc()) {
746 // Generate increment code in its own basic block. This is the target
747 // of continue statements.
748 Succ = addStmt(I);
749 Block = 0;
750 ContinueTargetBlock = Succ;
751 }
752 else {
753 // No increment code. Continues should go the the entry condition block.
754 ContinueTargetBlock = EntryConditionBlock;
755 }
756
757 // All breaks should go to the code following the loop.
758 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000759
760 // Now populate the body block, and in the process create new blocks
761 // as we walk the body of the loop.
762 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000763
764 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000765 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000766 else if (Block)
767 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000768
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000769 // This new body block is a successor to our "exit" condition block.
770 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000771 }
772
773 // Link up the condition block with the code that follows the loop.
774 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000775 ExitConditionBlock->addSuccessor(LoopSuccessor);
776
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000777 // If the loop contains initialization, create a new block for those
778 // statements. This block can also contain statements that precede
779 // the loop.
780 if (Stmt* I = F->getInit()) {
781 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000782 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000783 }
784 else {
785 // There is no loop initialization. We are thus basically a while
786 // loop. NULL out Block to force lazy block construction.
787 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000788 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000789 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000790 }
791}
792
793CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
794 // "while" is a control-flow statement. Thus we stop processing the
795 // current block.
796
797 CFGBlock* LoopSuccessor = NULL;
798
799 if (Block) {
800 FinishBlock(Block);
801 LoopSuccessor = Block;
802 }
803 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000804
805 // Because of short-circuit evaluation, the condition of the loop
806 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
807 // blocks that evaluate the condition.
808 CFGBlock* ExitConditionBlock = createBlock(false);
809 CFGBlock* EntryConditionBlock = ExitConditionBlock;
810
811 // Set the terminator for the "exit" condition block.
812 ExitConditionBlock->setTerminator(W);
813
814 // Now add the actual condition to the condition block. Because the
815 // condition itself may contain control-flow, new blocks may be created.
816 // Thus we update "Succ" after adding the condition.
817 if (Stmt* C = W->getCond()) {
818 Block = ExitConditionBlock;
819 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000820 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000821 if (Block) FinishBlock(EntryConditionBlock);
822 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000823
824 // The condition block is the implicit successor for the loop body as
825 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000826 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000827
828 // Process the loop body.
829 {
830 assert (W->getBody());
831
832 // Save the current values for Block, Succ, and continue and break targets
833 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
834 save_continue(ContinueTargetBlock),
835 save_break(BreakTargetBlock);
836
837 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000838 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000839
840 // All breaks should go to the code following the loop.
841 BreakTargetBlock = LoopSuccessor;
842
843 // NULL out Block to force lazy instantiation of blocks for the body.
844 Block = NULL;
845
846 // Create the body. The returned block is the entry to the loop body.
847 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000848
849 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000850 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000851 else if (Block)
852 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000853
854 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000855 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000856 }
857
858 // Link up the condition block with the code that follows the loop.
859 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000860 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000861
862 // There can be no more statements in the condition block
863 // since we loop back to this block. NULL out Block to force
864 // lazy creation of another block.
865 Block = NULL;
866
867 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000868 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000869 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000870}
871
872CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
873 // "do...while" is a control-flow statement. Thus we stop processing the
874 // current block.
875
876 CFGBlock* LoopSuccessor = NULL;
877
878 if (Block) {
879 FinishBlock(Block);
880 LoopSuccessor = Block;
881 }
882 else LoopSuccessor = Succ;
883
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000884 // Because of short-circuit evaluation, the condition of the loop
885 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
886 // blocks that evaluate the condition.
887 CFGBlock* ExitConditionBlock = createBlock(false);
888 CFGBlock* EntryConditionBlock = ExitConditionBlock;
889
890 // Set the terminator for the "exit" condition block.
891 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000892
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000893 // Now add the actual condition to the condition block. Because the
894 // condition itself may contain control-flow, new blocks may be created.
895 if (Stmt* C = D->getCond()) {
896 Block = ExitConditionBlock;
897 EntryConditionBlock = addStmt(C);
898 if (Block) FinishBlock(EntryConditionBlock);
899 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000900
Ted Kremenek54827132008-02-27 07:20:00 +0000901 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000902 Succ = EntryConditionBlock;
903
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000904 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000905 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000906 {
907 assert (D->getBody());
908
909 // Save the current values for Block, Succ, and continue and break targets
910 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
911 save_continue(ContinueTargetBlock),
912 save_break(BreakTargetBlock);
913
914 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000915 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000916
917 // All breaks should go to the code following the loop.
918 BreakTargetBlock = LoopSuccessor;
919
920 // NULL out Block to force lazy instantiation of blocks for the body.
921 Block = NULL;
922
923 // Create the body. The returned block is the entry to the loop body.
924 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000925
Ted Kremenekaf603f72007-08-30 18:39:40 +0000926 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000927 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000928 else if (Block)
929 FinishBlock(BodyBlock);
930
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000931 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000932 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000933 }
934
935 // Link up the condition block with the code that follows the loop.
936 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000937 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000938
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000939 // There can be no more statements in the body block(s)
940 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000941 // lazy creation of another block.
942 Block = NULL;
943
944 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000945 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000946 return BodyBlock;
947}
948
949CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
950 // "continue" is a control-flow statement. Thus we stop processing the
951 // current block.
952 if (Block) FinishBlock(Block);
953
954 // Now create a new block that ends with the continue statement.
955 Block = createBlock(false);
956 Block->setTerminator(C);
957
958 // If there is no target for the continue, then we are looking at an
959 // incomplete AST. Handle this by not registering a successor.
960 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
961
962 return Block;
963}
964
965CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
966 // "break" is a control-flow statement. Thus we stop processing the
967 // current block.
968 if (Block) FinishBlock(Block);
969
970 // Now create a new block that ends with the continue statement.
971 Block = createBlock(false);
972 Block->setTerminator(B);
973
974 // If there is no target for the break, then we are looking at an
975 // incomplete AST. Handle this by not registering a successor.
976 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
977
978 return Block;
979}
980
Ted Kremenek411cdee2008-04-16 21:10:48 +0000981CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000982 // "switch" is a control-flow statement. Thus we stop processing the
983 // current block.
984 CFGBlock* SwitchSuccessor = NULL;
985
986 if (Block) {
987 FinishBlock(Block);
988 SwitchSuccessor = Block;
989 }
990 else SwitchSuccessor = Succ;
991
992 // Save the current "switch" context.
993 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000994 save_break(BreakTargetBlock),
995 save_default(DefaultCaseBlock);
996
997 // Set the "default" case to be the block after the switch statement.
998 // If the switch statement contains a "default:", this value will
999 // be overwritten with the block for that code.
1000 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001001
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001002 // Create a new block that will contain the switch statement.
1003 SwitchTerminatedBlock = createBlock(false);
1004
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001005 // Now process the switch body. The code after the switch is the implicit
1006 // successor.
1007 Succ = SwitchSuccessor;
1008 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001009
1010 // When visiting the body, the case statements should automatically get
1011 // linked up to the switch. We also don't keep a pointer to the body,
1012 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001013 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001014 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001015 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001016 if (Block) FinishBlock(BodyBlock);
1017
Ted Kremenek295222c2008-02-13 21:46:34 +00001018 // If we have no "default:" case, the default transition is to the
1019 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001020 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001021
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001022 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001023 SwitchTerminatedBlock->setTerminator(Terminator);
1024 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001025 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001026
Ted Kremenek411cdee2008-04-16 21:10:48 +00001027 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001028}
1029
Ted Kremenek411cdee2008-04-16 21:10:48 +00001030CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001031 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001032 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001033
Ted Kremenek411cdee2008-04-16 21:10:48 +00001034 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001035 CFGBlock* CaseBlock = Block;
1036 if (!CaseBlock) CaseBlock = createBlock();
1037
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001038 // Cases statements partition blocks, so this is the top of
1039 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001040 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001041 FinishBlock(CaseBlock);
1042
1043 // Add this block to the list of successors for the block with the
1044 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001045 assert (SwitchTerminatedBlock);
1046 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001047
1048 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1049 Block = NULL;
1050
1051 // This block is now the implicit successor of other blocks.
1052 Succ = CaseBlock;
1053
Ted Kremenek2677ea82008-03-15 07:45:02 +00001054 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001055}
Ted Kremenek295222c2008-02-13 21:46:34 +00001056
Ted Kremenek411cdee2008-04-16 21:10:48 +00001057CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1058 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001059 DefaultCaseBlock = Block;
1060 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1061
1062 // Default statements partition blocks, so this is the top of
1063 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001064 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001065 FinishBlock(DefaultCaseBlock);
1066
1067 // Unlike case statements, we don't add the default block to the
1068 // successors for the switch statement immediately. This is done
1069 // when we finish processing the switch statement. This allows for
1070 // the default case (including a fall-through to the code after the
1071 // switch statement) to always be the last successor of a switch-terminated
1072 // block.
1073
1074 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1075 Block = NULL;
1076
1077 // This block is now the implicit successor of other blocks.
1078 Succ = DefaultCaseBlock;
1079
1080 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001081}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001082
Ted Kremenek19bb3562007-08-28 19:26:49 +00001083CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1084 // Lazily create the indirect-goto dispatch block if there isn't one
1085 // already.
1086 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1087
1088 if (!IBlock) {
1089 IBlock = createBlock(false);
1090 cfg->setIndirectGotoBlock(IBlock);
1091 }
1092
1093 // IndirectGoto is a control-flow statement. Thus we stop processing the
1094 // current block and create a new one.
1095 if (Block) FinishBlock(Block);
1096 Block = createBlock(false);
1097 Block->setTerminator(I);
1098 Block->addSuccessor(IBlock);
1099 return addStmt(I->getTarget());
1100}
1101
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001102
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001103} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001104
1105/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1106/// block has no successors or predecessors. If this is the first block
1107/// created in the CFG, it is automatically set to be the Entry and Exit
1108/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001109CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001110 bool first_block = begin() == end();
1111
1112 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001113 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001114
1115 // If this is the first block, set it as the Entry and Exit.
1116 if (first_block) Entry = Exit = &front();
1117
1118 // Return the block.
1119 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001120}
1121
Ted Kremenek026473c2007-08-23 16:51:22 +00001122/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1123/// CFG is returned to the caller.
1124CFG* CFG::buildCFG(Stmt* Statement) {
1125 CFGBuilder Builder;
1126 return Builder.buildCFG(Statement);
1127}
1128
1129/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001130void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1131
Ted Kremenek63f58872007-10-01 19:33:33 +00001132//===----------------------------------------------------------------------===//
1133// CFG: Queries for BlkExprs.
1134//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001135
Ted Kremenek63f58872007-10-01 19:33:33 +00001136namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001137 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001138}
1139
Ted Kremenek411cdee2008-04-16 21:10:48 +00001140static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1141 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001142 return;
1143
Ted Kremenek411cdee2008-04-16 21:10:48 +00001144 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001145 if (!*I) continue;
1146
1147 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1148 if (B->isAssignmentOp()) Set.insert(B);
1149
1150 FindSubExprAssignments(*I, Set);
1151 }
1152}
1153
Ted Kremenek63f58872007-10-01 19:33:33 +00001154static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1155 BlkExprMapTy* M = new BlkExprMapTy();
1156
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001157 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001158 // only assignments that we want to *possibly* register as a block-level
1159 // expression. Basically, if an assignment occurs both in a subexpression
1160 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001161 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1162
Ted Kremenek63f58872007-10-01 19:33:33 +00001163 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1164 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001165 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001166
Ted Kremenek411cdee2008-04-16 21:10:48 +00001167 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1168
1169 // Iterate over the statements again on identify the Expr* and Stmt* at
1170 // the block-level that are block-level expressions.
1171
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001172 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001173 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001174
Ted Kremenek411cdee2008-04-16 21:10:48 +00001175 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001176 // Assignment expressions that are not nested within another
1177 // expression are really "statements" whose value is never
1178 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001179 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001180 continue;
1181 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001182 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001183 // Special handling for statement expressions. The last statement
1184 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001185 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001186 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001187 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001188 (*M)[C->body_back()] = x;
1189 }
1190 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001191
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001192 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001193 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001194 }
1195
Ted Kremenek411cdee2008-04-16 21:10:48 +00001196 // Look at terminators. The condition is a block-level expression.
1197
1198 Expr* Exp = I->getTerminatorCondition();
1199
1200 if (Exp && M->find(Exp) == M->end()) {
1201 unsigned x = M->size();
1202 (*M)[Exp] = x;
1203 }
1204 }
1205
Ted Kremenek63f58872007-10-01 19:33:33 +00001206 return M;
1207}
1208
Ted Kremenek86946742008-01-17 20:48:37 +00001209CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1210 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001211 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1212
1213 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001214 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001215
1216 if (I == M->end()) return CFG::BlkExprNumTy();
1217 else return CFG::BlkExprNumTy(I->second);
1218}
1219
1220unsigned CFG::getNumBlkExprs() {
1221 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1222 return M->size();
1223 else {
1224 // We assume callers interested in the number of BlkExprs will want
1225 // the map constructed if it doesn't already exist.
1226 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1227 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1228 }
1229}
1230
Ted Kremenek274f4332008-04-28 18:00:46 +00001231//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001232// Cleanup: CFG dstor.
1233//===----------------------------------------------------------------------===//
1234
Ted Kremenek63f58872007-10-01 19:33:33 +00001235CFG::~CFG() {
1236 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1237}
1238
Ted Kremenek7dba8602007-08-29 21:56:09 +00001239//===----------------------------------------------------------------------===//
1240// CFG pretty printing
1241//===----------------------------------------------------------------------===//
1242
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001243namespace {
1244
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001245class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001246
Ted Kremenek42a509f2007-08-31 21:30:12 +00001247 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1248 StmtMapTy StmtMap;
1249 signed CurrentBlock;
1250 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001251
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001252public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001253
Ted Kremenek42a509f2007-08-31 21:30:12 +00001254 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1255 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1256 unsigned j = 1;
1257 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1258 BI != BEnd; ++BI, ++j )
1259 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1260 }
1261 }
1262
1263 virtual ~StmtPrinterHelper() {}
1264
1265 void setBlockID(signed i) { CurrentBlock = i; }
1266 void setStmtID(unsigned i) { CurrentStmt = i; }
1267
Ted Kremeneka95d3752008-09-13 05:16:45 +00001268 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001269
Ted Kremenek411cdee2008-04-16 21:10:48 +00001270 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001271
1272 if (I == StmtMap.end())
1273 return false;
1274
1275 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1276 && I->second.second == CurrentStmt)
1277 return false;
1278
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001279 OS << "[B" << I->second.first << "." << I->second.second << "]";
1280 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001281 }
1282};
1283
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001284class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1285 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1286
Ted Kremeneka95d3752008-09-13 05:16:45 +00001287 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001288 StmtPrinterHelper* Helper;
1289public:
Ted Kremeneka95d3752008-09-13 05:16:45 +00001290 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper)
Ted Kremenek42a509f2007-08-31 21:30:12 +00001291 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001292
1293 void VisitIfStmt(IfStmt* I) {
1294 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001295 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001296 }
1297
1298 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001299 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001300
1301 void VisitForStmt(ForStmt* F) {
1302 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001303 if (F->getInit()) OS << "...";
1304 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001305 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001306 OS << "; ";
1307 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001308 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001309 }
1310
1311 void VisitWhileStmt(WhileStmt* W) {
1312 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001313 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001314 }
1315
1316 void VisitDoStmt(DoStmt* D) {
1317 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001318 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001319 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001320
Ted Kremenek411cdee2008-04-16 21:10:48 +00001321 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001322 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001323 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001324 }
1325
Ted Kremenek805e9a82007-08-31 21:49:40 +00001326 void VisitConditionalOperator(ConditionalOperator* C) {
1327 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001328 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001329 }
1330
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001331 void VisitChooseExpr(ChooseExpr* C) {
1332 OS << "__builtin_choose_expr( ";
1333 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001334 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001335 }
1336
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001337 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1338 OS << "goto *";
1339 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001340 }
1341
Ted Kremenek805e9a82007-08-31 21:49:40 +00001342 void VisitBinaryOperator(BinaryOperator* B) {
1343 if (!B->isLogicalOp()) {
1344 VisitExpr(B);
1345 return;
1346 }
1347
1348 B->getLHS()->printPretty(OS,Helper);
1349
1350 switch (B->getOpcode()) {
1351 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001352 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001353 return;
1354 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001355 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001356 return;
1357 default:
1358 assert(false && "Invalid logical operator.");
1359 }
1360 }
1361
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001362 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001363 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001364 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001365};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001366
1367
Ted Kremeneka95d3752008-09-13 05:16:45 +00001368void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001369 if (Helper) {
1370 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001371 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001372 CompoundStmt* Sub = SE->getSubStmt();
1373
1374 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001375 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001376 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001377 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001378 return;
1379 }
1380 }
1381
1382 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001383 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001384 if (B->getOpcode() == BinaryOperator::Comma) {
1385 OS << "... , ";
1386 Helper->handledStmt(B->getRHS(),OS);
1387 OS << '\n';
1388 return;
1389 }
1390 }
1391 }
1392
Ted Kremenek411cdee2008-04-16 21:10:48 +00001393 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001394
1395 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001396 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001397}
1398
Ted Kremeneka95d3752008-09-13 05:16:45 +00001399void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001400 StmtPrinterHelper* Helper, bool print_edges) {
1401
1402 if (Helper) Helper->setBlockID(B.getBlockID());
1403
Ted Kremenek7dba8602007-08-29 21:56:09 +00001404 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001405 OS << "\n [ B" << B.getBlockID();
1406
1407 if (&B == &cfg->getEntry())
1408 OS << " (ENTRY) ]\n";
1409 else if (&B == &cfg->getExit())
1410 OS << " (EXIT) ]\n";
1411 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001412 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001413 else
1414 OS << " ]\n";
1415
Ted Kremenek9cffe732007-08-29 23:20:49 +00001416 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001417 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001418
1419 if (print_edges)
1420 OS << " ";
1421
Ted Kremenek411cdee2008-04-16 21:10:48 +00001422 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001423 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001424 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001425 OS << "case ";
1426 C->getLHS()->printPretty(OS);
1427 if (C->getRHS()) {
1428 OS << " ... ";
1429 C->getRHS()->printPretty(OS);
1430 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001431 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001432 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001433 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001434 else
1435 assert(false && "Invalid label statement in CFGBlock.");
1436
Ted Kremenek9cffe732007-08-29 23:20:49 +00001437 OS << ":\n";
1438 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001439
Ted Kremenekfddd5182007-08-21 21:42:03 +00001440 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001441 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001442
1443 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1444 I != E ; ++I, ++j ) {
1445
Ted Kremenek9cffe732007-08-29 23:20:49 +00001446 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001447 if (print_edges)
1448 OS << " ";
1449
Ted Kremeneka95d3752008-09-13 05:16:45 +00001450 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001451
1452 if (Helper)
1453 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001454
1455 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001456 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001457
Ted Kremenek9cffe732007-08-29 23:20:49 +00001458 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001459 if (B.getTerminator()) {
1460 if (print_edges)
1461 OS << " ";
1462
Ted Kremenek9cffe732007-08-29 23:20:49 +00001463 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001464
1465 if (Helper) Helper->setBlockID(-1);
1466
1467 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1468 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001469 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001470 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001471
Ted Kremenek9cffe732007-08-29 23:20:49 +00001472 if (print_edges) {
1473 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001474 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001475 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001476
Ted Kremenek42a509f2007-08-31 21:30:12 +00001477 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1478 I != E; ++I, ++i) {
1479
1480 if (i == 8 || (i-8) == 0)
1481 OS << "\n ";
1482
Ted Kremenek9cffe732007-08-29 23:20:49 +00001483 OS << " B" << (*I)->getBlockID();
1484 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001485
1486 OS << '\n';
1487
1488 // Print the successors of this block.
1489 OS << " Successors (" << B.succ_size() << "):";
1490 i = 0;
1491
1492 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1493 I != E; ++I, ++i) {
1494
1495 if (i == 8 || (i-8) % 10 == 0)
1496 OS << "\n ";
1497
1498 OS << " B" << (*I)->getBlockID();
1499 }
1500
Ted Kremenek9cffe732007-08-29 23:20:49 +00001501 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001502 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001503}
1504
1505} // end anonymous namespace
1506
1507/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001508void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001509
1510/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001511void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001512
1513 StmtPrinterHelper Helper(this);
1514
1515 // Print the entry block.
1516 print_block(OS, this, getEntry(), &Helper, true);
1517
1518 // Iterate through the CFGBlocks and print them one by one.
1519 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1520 // Skip the entry block, because we already printed it.
1521 if (&(*I) == &getEntry() || &(*I) == &getExit())
1522 continue;
1523
1524 print_block(OS, this, *I, &Helper, true);
1525 }
1526
1527 // Print the exit block.
1528 print_block(OS, this, getExit(), &Helper, true);
1529}
1530
1531/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001532void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001533
1534/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1535/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001536void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001537 StmtPrinterHelper Helper(cfg);
1538 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001539}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001540
Ted Kremeneka2925852008-01-30 23:02:42 +00001541/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001542void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001543 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1544 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1545}
1546
Ted Kremenek411cdee2008-04-16 21:10:48 +00001547Expr* CFGBlock::getTerminatorCondition() {
1548
1549 if (!Terminator)
1550 return NULL;
1551
1552 Expr* E = NULL;
1553
1554 switch (Terminator->getStmtClass()) {
1555 default:
1556 break;
1557
1558 case Stmt::ForStmtClass:
1559 E = cast<ForStmt>(Terminator)->getCond();
1560 break;
1561
1562 case Stmt::WhileStmtClass:
1563 E = cast<WhileStmt>(Terminator)->getCond();
1564 break;
1565
1566 case Stmt::DoStmtClass:
1567 E = cast<DoStmt>(Terminator)->getCond();
1568 break;
1569
1570 case Stmt::IfStmtClass:
1571 E = cast<IfStmt>(Terminator)->getCond();
1572 break;
1573
1574 case Stmt::ChooseExprClass:
1575 E = cast<ChooseExpr>(Terminator)->getCond();
1576 break;
1577
1578 case Stmt::IndirectGotoStmtClass:
1579 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1580 break;
1581
1582 case Stmt::SwitchStmtClass:
1583 E = cast<SwitchStmt>(Terminator)->getCond();
1584 break;
1585
1586 case Stmt::ConditionalOperatorClass:
1587 E = cast<ConditionalOperator>(Terminator)->getCond();
1588 break;
1589
1590 case Stmt::BinaryOperatorClass: // '&&' and '||'
1591 E = cast<BinaryOperator>(Terminator)->getLHS();
1592 break;
1593 }
1594
1595 return E ? E->IgnoreParens() : NULL;
1596}
1597
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001598bool CFGBlock::hasBinaryBranchTerminator() const {
1599
1600 if (!Terminator)
1601 return false;
1602
1603 Expr* E = NULL;
1604
1605 switch (Terminator->getStmtClass()) {
1606 default:
1607 return false;
1608
1609 case Stmt::ForStmtClass:
1610 case Stmt::WhileStmtClass:
1611 case Stmt::DoStmtClass:
1612 case Stmt::IfStmtClass:
1613 case Stmt::ChooseExprClass:
1614 case Stmt::ConditionalOperatorClass:
1615 case Stmt::BinaryOperatorClass:
1616 return true;
1617 }
1618
1619 return E ? E->IgnoreParens() : NULL;
1620}
1621
Ted Kremeneka2925852008-01-30 23:02:42 +00001622
Ted Kremenek7dba8602007-08-29 21:56:09 +00001623//===----------------------------------------------------------------------===//
1624// CFG Graphviz Visualization
1625//===----------------------------------------------------------------------===//
1626
Ted Kremenek42a509f2007-08-31 21:30:12 +00001627
1628#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001629static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001630#endif
1631
1632void CFG::viewCFG() const {
1633#ifndef NDEBUG
1634 StmtPrinterHelper H(this);
1635 GraphHelper = &H;
1636 llvm::ViewGraph(this,"CFG");
1637 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001638#endif
1639}
1640
Ted Kremenek7dba8602007-08-29 21:56:09 +00001641namespace llvm {
1642template<>
1643struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1644 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1645
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001646#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001647 std::string OutSStr;
1648 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001649 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001650 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001651
1652 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1653
1654 // Process string output to make it nicer...
1655 for (unsigned i = 0; i != OutStr.length(); ++i)
1656 if (OutStr[i] == '\n') { // Left justify
1657 OutStr[i] = '\\';
1658 OutStr.insert(OutStr.begin()+i+1, 'l');
1659 }
1660
1661 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001662#else
1663 return "";
1664#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001665 }
1666};
1667} // end namespace llvm