blob: b76fe6b68cd89aef775f4de1009cd576ca458bf8 [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
Douglas Gregor4afa39d2009-01-20 01:17:11 +000045static SourceLocation GetEndLoc(Decl* D) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +000046 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
Ted Kremeneka34ea072008-08-04 22:51:42 +000053/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenekfddd5182007-08-21 21:42:03 +000054/// The builder is stateful: an instance of the builder should be used to only
55/// construct a single CFG.
56///
57/// Example usage:
58///
59/// CFGBuilder builder;
60/// CFG* cfg = builder.BuildAST(stmt1);
61///
Ted Kremenekc310e932007-08-21 22:06:14 +000062/// CFG construction is done via a recursive walk of an AST.
63/// We actually parse the AST in reverse order so that the successor
64/// of a basic block is constructed prior to its predecessor. This
65/// allows us to nicely capture implicit fall-throughs without extra
66/// basic blocks.
67///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000068class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000069 CFG* cfg;
70 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000071 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000072 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000073 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000074 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000075 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000076
Ted Kremenek19bb3562007-08-28 19:26:49 +000077 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000078 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
79 LabelMapTy LabelMap;
80
Ted Kremenek19bb3562007-08-28 19:26:49 +000081 // A list of blocks that end with a "goto" that must be backpatched to
82 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000083 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000084 BackpatchBlocksTy BackpatchBlocks;
85
Ted Kremenek19bb3562007-08-28 19:26:49 +000086 // A list of labels whose address has been taken (for indirect gotos).
87 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
88 LabelSetTy AddressTakenLabels;
89
Ted Kremenekfddd5182007-08-21 21:42:03 +000090public:
Ted Kremenek026473c2007-08-23 16:51:22 +000091 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000092 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000093 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000094 // Create an empty CFG.
95 cfg = new CFG();
96 }
97
98 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000099
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000100 // buildCFG - Used by external clients to construct the CFG.
101 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +0000102
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000103 // Visitors to walk an AST and construct the CFG. Called by
104 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000105
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000106 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000107 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000108 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
109 CFGBlock* VisitContinueStmt(ContinueStmt* C);
Ted Kremenek295222c2008-02-13 21:46:34 +0000110 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000111 CFGBlock* VisitDoStmt(DoStmt* D);
112 CFGBlock* VisitForStmt(ForStmt* F);
113 CFGBlock* VisitGotoStmt(GotoStmt* G);
114 CFGBlock* VisitIfStmt(IfStmt* I);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000115 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000116 CFGBlock* VisitLabelStmt(LabelStmt* L);
117 CFGBlock* VisitNullStmt(NullStmt* Statement);
118 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);
119 CFGBlock* VisitReturnStmt(ReturnStmt* R);
120 CFGBlock* VisitStmt(Stmt* Statement);
121 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
122 CFGBlock* VisitWhileStmt(WhileStmt* W);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000123
Ted Kremenek4102af92008-03-13 03:04:22 +0000124 // FIXME: Add support for ObjC-specific control-flow structures.
125
Ted Kremenek274f4332008-04-28 18:00:46 +0000126 // NYS == Not Yet Supported
127 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000128 badCFG = true;
129 return Block;
130 }
131
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000132 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S);
133 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
134 // FIXME: For now we pretend that @catch and the code it contains
135 // does not exit.
136 return Block;
137 }
138
Ted Kremenek2fda5042008-12-09 20:20:09 +0000139 // FIXME: This is not completely supported. We basically @throw like
140 // a 'return'.
141 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S);
Ted Kremenek274f4332008-04-28 18:00:46 +0000142
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000143 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S);
Ted Kremenek4102af92008-03-13 03:04:22 +0000144
Ted Kremenek00c0a302008-09-26 18:17:07 +0000145 // Blocks.
146 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
147 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
148
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000149private:
150 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000151 CFGBlock* addStmt(Stmt* Terminator);
152 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
153 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000154 CFGBlock* WalkAST_VisitDeclSubExpr(Decl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000155 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000156 bool FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000157
Ted Kremenek4102af92008-03-13 03:04:22 +0000158 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000159};
Ted Kremenek610a09e2008-09-26 22:58:57 +0000160
Douglas Gregor898574e2008-12-05 23:32:09 +0000161// FIXME: Add support for dependent-sized array types in C++?
162// Does it even make sense to build a CFG for an uninstantiated template?
Ted Kremenek610a09e2008-09-26 22:58:57 +0000163static VariableArrayType* FindVA(Type* t) {
164 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
165 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
166 if (vat->getSizeExpr())
167 return vat;
168
169 t = vt->getElementType().getTypePtr();
170 }
171
172 return 0;
173}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000174
175/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
176/// represent an arbitrary statement. Examples include a single expression
177/// or a function body (compound statement). The ownership of the returned
178/// CFG is transferred to the caller. If CFG construction fails, this method
179/// returns NULL.
180CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000181 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000182 if (!Statement) return NULL;
183
Ted Kremenek4102af92008-03-13 03:04:22 +0000184 badCFG = false;
185
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000186 // Create an empty block that will serve as the exit block for the CFG.
187 // Since this is the first block added to the CFG, it will be implicitly
188 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000189 Succ = createBlock();
190 assert (Succ == &cfg->getExit());
191 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000192
193 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000194 CFGBlock* B = Visit(Statement);
195 if (!B) B = Succ;
196
197 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000198 // Finalize the last constructed block. This usually involves
199 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000200 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000201
202 // Backpatch the gotos whose label -> block mappings we didn't know
203 // when we encountered them.
204 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
205 E = BackpatchBlocks.end(); I != E; ++I ) {
206
207 CFGBlock* B = *I;
208 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
209 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
210
211 // If there is no target for the goto, then we are looking at an
212 // incomplete AST. Handle this by not registering a successor.
213 if (LI == LabelMap.end()) continue;
214
215 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000216 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000217
Ted Kremenek19bb3562007-08-28 19:26:49 +0000218 // Add successors to the Indirect Goto Dispatch block (if we have one).
219 if (CFGBlock* B = cfg->getIndirectGotoBlock())
220 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
221 E = AddressTakenLabels.end(); I != E; ++I ) {
222
223 // Lookup the target block.
224 LabelMapTy::iterator LI = LabelMap.find(*I);
225
226 // If there is no target block that contains label, then we are looking
227 // at an incomplete AST. Handle this by not registering a successor.
228 if (LI == LabelMap.end()) continue;
229
230 B->addSuccessor(LI->second);
231 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000232
Ted Kremenek94b33162007-09-17 16:18:02 +0000233 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000234 }
235
236 // Create an empty entry block that has no predecessors.
237 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000238
Ted Kremenek4102af92008-03-13 03:04:22 +0000239 if (badCFG) {
240 delete cfg;
241 cfg = NULL;
242 return NULL;
243 }
244
Ted Kremenek322f58d2007-09-26 21:23:31 +0000245 // NULL out cfg so that repeated calls to the builder will fail and that
246 // the ownership of the constructed CFG is passed to the caller.
247 CFG* t = cfg;
248 cfg = NULL;
249 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000250}
251
252/// createBlock - Used to lazily create blocks that are connected
253/// to the current (global) succcessor.
254CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000255 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000256 if (add_successor && Succ) B->addSuccessor(Succ);
257 return B;
258}
259
260/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000261/// we must reverse the statements because they have been inserted
262/// in reverse order.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000263bool CFGBuilder::FinishBlock(CFGBlock* B) {
264 if (badCFG)
265 return false;
266
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000267 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000268 B->reverseStmts();
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000269 return true;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000270}
271
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000272/// addStmt - Used to add statements/expressions to the current CFGBlock
273/// "Block". This method calls WalkAST on the passed statement to see if it
274/// contains any short-circuit expressions. If so, it recursively creates
275/// the necessary blocks for such expressions. It returns the "topmost" block
276/// of the created blocks, or the original value of "Block" when this method
277/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000278CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000279 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000280 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000281}
282
283/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000284/// add extra blocks for ternary operators, &&, and ||. We also
285/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000286CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
287 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000288 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000289 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000290
291 // Create the confluence block that will "merge" the results
292 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000293 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
294 ConfluenceBlock->appendStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000295 if (!FinishBlock(ConfluenceBlock))
296 return 0;
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());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000307 if (!FinishBlock(LHSBlock))
308 return 0;
309 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000310 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000311
Ted Kremenekecc04c92007-11-26 18:20:26 +0000312 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000313 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000314 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000315 if (!FinishBlock(RHSBlock))
316 return 0;
317
Ted Kremenekecc04c92007-11-26 18:20:26 +0000318 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000319 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000320
321 if (LHSBlock)
322 Block->addSuccessor(LHSBlock);
323 else {
324 // If we have no LHS expression, add the ConfluenceBlock as a direct
325 // successor for the block containing the condition. Moreover,
326 // we need to reverse the order of the predecessors in the
327 // ConfluenceBlock because the RHSBlock will have been added to
328 // the succcessors already, and we want the first predecessor to the
329 // the block containing the expression for the case when the ternary
330 // expression evaluates to true.
331 Block->addSuccessor(ConfluenceBlock);
332 assert (ConfluenceBlock->pred_size() == 2);
333 std::reverse(ConfluenceBlock->pred_begin(),
334 ConfluenceBlock->pred_end());
335 }
336
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000337 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000338
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000339 Block->setTerminator(C);
340 return addStmt(C->getCond());
341 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000342
343 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000344 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000345
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000346 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek49a436d2007-08-31 17:03:41 +0000347 ConfluenceBlock->appendStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000348 if (!FinishBlock(ConfluenceBlock))
349 return 0;
Ted Kremenek49a436d2007-08-31 17:03:41 +0000350
351 Succ = ConfluenceBlock;
352 Block = NULL;
353 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000354 if (!FinishBlock(LHSBlock))
355 return 0;
Ted Kremenekf50ec102007-09-11 21:29:43 +0000356
Ted Kremenek49a436d2007-08-31 17:03:41 +0000357 Succ = ConfluenceBlock;
358 Block = NULL;
359 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000360 if (!FinishBlock(RHSBlock))
361 return 0;
Ted Kremenek49a436d2007-08-31 17:03:41 +0000362
363 Block = createBlock(false);
364 Block->addSuccessor(LHSBlock);
365 Block->addSuccessor(RHSBlock);
366 Block->setTerminator(C);
367 return addStmt(C->getCond());
368 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000369
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000370 case Stmt::DeclStmtClass: {
Ted Kremenek53061c82008-10-06 20:56:19 +0000371 DeclStmt *DS = cast<DeclStmt>(Terminator);
Chris Lattner7e24e822009-03-28 06:33:19 +0000372 if (DS->isSingleDecl()) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000373 Block->appendStmt(Terminator);
Chris Lattner7e24e822009-03-28 06:33:19 +0000374 return WalkAST_VisitDeclSubExpr(DS->getSingleDecl());
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000375 }
Chris Lattner7e24e822009-03-28 06:33:19 +0000376
Chris Lattner7e24e822009-03-28 06:33:19 +0000377 CFGBlock* B = 0;
Ted Kremenek53061c82008-10-06 20:56:19 +0000378
Chris Lattner7e24e822009-03-28 06:33:19 +0000379 // FIXME: Add a reverse iterator for DeclStmt to avoid this
380 // extra copy.
Chris Lattnere66a8cf2009-03-28 06:53:40 +0000381 typedef llvm::SmallVector<Decl*,10> BufTy;
382 BufTy Buf(DS->decl_begin(), DS->decl_end());
Chris Lattner7e24e822009-03-28 06:33:19 +0000383
384 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
385 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
386 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
387 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Ted Kremenek53061c82008-10-06 20:56:19 +0000388
Chris Lattner7e24e822009-03-28 06:33:19 +0000389 // Allocate the DeclStmt using the BumpPtrAllocator. It will
390 // get automatically freed with the CFG.
391 DeclGroupRef DG(*I);
392 Decl* D = *I;
393 void* Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
394
Chris Lattnere66a8cf2009-03-28 06:53:40 +0000395 DeclStmt* DS = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Chris Lattner7e24e822009-03-28 06:33:19 +0000396
397 // Append the fake DeclStmt to block.
398 Block->appendStmt(DS);
399 B = WalkAST_VisitDeclSubExpr(D);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000400 }
Chris Lattner7e24e822009-03-28 06:33:19 +0000401 return B;
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000402 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000403
Ted Kremenek19bb3562007-08-28 19:26:49 +0000404 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000406 AddressTakenLabels.insert(A->getLabel());
407
Ted Kremenek411cdee2008-04-16 21:10:48 +0000408 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000409 return Block;
410 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000411
Ted Kremenek15c27a82007-08-28 18:30:10 +0000412 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000413 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000414
Sebastian Redl05189992008-11-11 17:56:53 +0000415 case Stmt::SizeOfAlignOfExprClass: {
416 SizeOfAlignOfExpr* E = cast<SizeOfAlignOfExpr>(Terminator);
Ted Kremenek610a09e2008-09-26 22:58:57 +0000417
418 // VLA types have expressions that must be evaluated.
Sebastian Redl05189992008-11-11 17:56:53 +0000419 if (E->isArgumentType()) {
420 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
421 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
422 addStmt(VA->getSizeExpr());
423 }
424 // Expressions in sizeof/alignof are not evaluated and thus have no
425 // control flow.
426 else
427 Block->appendStmt(Terminator);
Ted Kremenek610a09e2008-09-26 22:58:57 +0000428
429 return Block;
430 }
431
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000432 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000433 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000434
435 if (B->isLogicalOp()) { // && or ||
436 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
437 ConfluenceBlock->appendStmt(B);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000438 if (!FinishBlock(ConfluenceBlock))
439 return 0;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000440
441 // create the block evaluating the LHS
442 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000443 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000444
445 // create the block evaluating the RHS
446 Succ = ConfluenceBlock;
447 Block = NULL;
448 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000449 if (!FinishBlock(RHSBlock))
450 return 0;
Ted Kremenekafe54332007-12-21 19:49:00 +0000451
452 // Now link the LHSBlock with RHSBlock.
453 if (B->getOpcode() == BinaryOperator::LOr) {
454 LHSBlock->addSuccessor(ConfluenceBlock);
455 LHSBlock->addSuccessor(RHSBlock);
456 }
457 else {
458 assert (B->getOpcode() == BinaryOperator::LAnd);
459 LHSBlock->addSuccessor(RHSBlock);
460 LHSBlock->addSuccessor(ConfluenceBlock);
461 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000462
463 // Generate the blocks for evaluating the LHS.
464 Block = LHSBlock;
465 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000466 }
467 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
468 Block->appendStmt(B);
469 addStmt(B->getRHS());
470 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000471 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000472
473 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000474 }
Ted Kremenek00c0a302008-09-26 18:17:07 +0000475
476 // Blocks: No support for blocks ... yet
477 case Stmt::BlockExprClass:
478 case Stmt::BlockDeclRefExprClass:
479 return NYS();
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000480
481 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000482 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000483
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000484 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000485 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000486 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000487
Ted Kremenek411cdee2008-04-16 21:10:48 +0000488 if (AlwaysAddStmt) Block->appendStmt(Terminator);
489 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000490}
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000491
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000492/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
493/// for initializers in Decls.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000494CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(Decl* D) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000495 VarDecl* VD = dyn_cast<VarDecl>(D);
496
497 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000498 return Block;
499
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000500 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000501
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000502 if (Init) {
Mike Stump54cc43f2009-02-26 08:00:25 +0000503 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000504 switch (Init->getStmtClass()) {
505 case Stmt::IntegerLiteralClass:
506 case Stmt::CharacterLiteralClass:
507 case Stmt::StringLiteralClass:
508 break;
509 default:
510 Block = addStmt(Init);
511 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000512 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000513
514 // If the type of VD is a VLA, then we must process its size expressions.
515 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
516 VA = FindVA(VA->getElementType().getTypePtr()))
517 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000518
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000519 return Block;
520}
521
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000522/// WalkAST_VisitChildren - Utility method to call WalkAST on the
523/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000524CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000525 CFGBlock* B = Block;
Mike Stump54cc43f2009-02-26 08:00:25 +0000526 for (Stmt::child_iterator I = Terminator->child_begin(),
527 E = Terminator->child_end();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000528 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000529 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000530
531 return B;
532}
533
Ted Kremenek15c27a82007-08-28 18:30:10 +0000534/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
535/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000536CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
537 Block->appendStmt(Terminator);
538 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000539}
540
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000541/// VisitStmt - Handle statements with no branching control flow.
542CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
543 // We cannot assume that we are in the middle of a basic block, since
544 // the CFG might only be constructed for this single statement. If
545 // we have no current basic block, just create one lazily.
546 if (!Block) Block = createBlock();
547
548 // Simply add the statement to the current block. We actually
549 // insert statements in reverse order; this order is reversed later
550 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000551 addStmt(Statement);
552
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000553 return Block;
554}
555
556CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
557 return Block;
558}
559
560CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000561
562 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000563
Ted Kremenekd34066c2008-02-26 00:22:58 +0000564 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
565 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000566 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000567 }
568
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000569 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000570}
571
572CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
573 // We may see an if statement in the middle of a basic block, or
574 // it may be the first statement we are processing. In either case,
575 // we create a new basic block. First, we create the blocks for
576 // the then...else statements, and then we create the block containing
577 // the if statement. If we were in the middle of a block, we
578 // stop processing that block and reverse its statements. That block
579 // is then the implicit successor for the "then" and "else" clauses.
580
581 // The block we were proccessing is now finished. Make it the
582 // successor block.
583 if (Block) {
584 Succ = Block;
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000585 if (!FinishBlock(Block))
586 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000587 }
588
589 // Process the false branch. NULL out Block so that the recursive
590 // call to Visit will create a new basic block.
591 // Null out Block so that all successor
592 CFGBlock* ElseBlock = Succ;
593
594 if (Stmt* Else = I->getElse()) {
595 SaveAndRestore<CFGBlock*> sv(Succ);
596
597 // NULL out Block so that the recursive call to Visit will
598 // create a new basic block.
599 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000600 ElseBlock = Visit(Else);
601
602 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
603 ElseBlock = sv.get();
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000604 else if (Block) {
605 if (!FinishBlock(ElseBlock))
606 return 0;
607 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000608 }
609
610 // Process the true branch. NULL out Block so that the recursive
611 // call to Visit will create a new basic block.
612 // Null out Block so that all successor
613 CFGBlock* ThenBlock;
614 {
615 Stmt* Then = I->getThen();
616 assert (Then);
617 SaveAndRestore<CFGBlock*> sv(Succ);
618 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000619 ThenBlock = Visit(Then);
620
Ted Kremenekdbdf7942009-04-01 03:52:47 +0000621 if (!ThenBlock) {
622 // We can reach here if the "then" body has all NullStmts.
623 // Create an empty block so we can distinguish between true and false
624 // branches in path-sensitive analyses.
625 ThenBlock = createBlock(false);
626 ThenBlock->addSuccessor(sv.get());
627 }
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000628 else if (Block) {
629 if (!FinishBlock(ThenBlock))
630 return 0;
631 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000632 }
633
634 // Now create a new block containing the if statement.
635 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000636
637 // Set the terminator of the new block to the If statement.
638 Block->setTerminator(I);
639
640 // Now add the successors.
641 Block->addSuccessor(ThenBlock);
642 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000643
644 // Add the condition as the last statement in the new block. This
645 // may create new blocks as the condition may contain control-flow. Any
646 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000647 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000648}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000649
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000650
651CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
652 // If we were in the middle of a block we stop processing that block
653 // and reverse its statements.
654 //
655 // NOTE: If a "return" appears in the middle of a block, this means
656 // that the code afterwards is DEAD (unreachable). We still
657 // keep a basic block for that code; a simple "mark-and-sweep"
658 // from the entry block will be able to report such dead
659 // blocks.
660 if (Block) FinishBlock(Block);
661
662 // Create the new block.
663 Block = createBlock(false);
664
665 // The Exit block is the only successor.
666 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000667
668 // Add the return statement to the block. This may create new blocks
669 // if R contains control-flow (short-circuit operations).
670 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000671}
672
673CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
674 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000675 Visit(L->getSubStmt());
676 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000677
678 if (!LabelBlock) // This can happen when the body is empty, i.e.
679 LabelBlock=createBlock(); // scopes that only contains NullStmts.
680
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000681 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
682 LabelMap[ L ] = LabelBlock;
683
684 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000685 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000686 // label (and we have already processed the substatement) there is no
687 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000688 LabelBlock->setLabel(L);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000689 if (!FinishBlock(LabelBlock))
690 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000691
692 // We set Block to NULL to allow lazy creation of a new block
693 // (if necessary);
694 Block = NULL;
695
696 // This block is now the implicit successor of other blocks.
697 Succ = LabelBlock;
698
699 return LabelBlock;
700}
701
702CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
703 // Goto is a control-flow statement. Thus we stop processing the
704 // current block and create a new one.
705 if (Block) FinishBlock(Block);
706 Block = createBlock(false);
707 Block->setTerminator(G);
708
709 // If we already know the mapping to the label block add the
710 // successor now.
711 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
712
713 if (I == LabelMap.end())
714 // We will need to backpatch this block later.
715 BackpatchBlocks.push_back(Block);
716 else
717 Block->addSuccessor(I->second);
718
719 return Block;
720}
721
722CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
723 // "for" is a control-flow statement. Thus we stop processing the
724 // current block.
725
726 CFGBlock* LoopSuccessor = NULL;
727
728 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000729 if (!FinishBlock(Block))
730 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000731 LoopSuccessor = Block;
732 }
733 else LoopSuccessor = Succ;
734
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000735 // Because of short-circuit evaluation, the condition of the loop
736 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
737 // blocks that evaluate the condition.
738 CFGBlock* ExitConditionBlock = createBlock(false);
739 CFGBlock* EntryConditionBlock = ExitConditionBlock;
740
741 // Set the terminator for the "exit" condition block.
742 ExitConditionBlock->setTerminator(F);
743
744 // Now add the actual condition to the condition block. Because the
745 // condition itself may contain control-flow, new blocks may be created.
746 if (Stmt* C = F->getCond()) {
747 Block = ExitConditionBlock;
748 EntryConditionBlock = addStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000749 if (Block) {
750 if (!FinishBlock(EntryConditionBlock))
751 return 0;
752 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000753 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000754
755 // The condition block is the implicit successor for the loop body as
756 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000757 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000758
759 // Now create the loop body.
760 {
761 assert (F->getBody());
762
763 // Save the current values for Block, Succ, and continue and break targets
764 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
765 save_continue(ContinueTargetBlock),
766 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000767
Ted Kremenekaf603f72007-08-30 18:39:40 +0000768 // Create a new block to contain the (bottom) of the loop body.
769 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000770
Ted Kremeneke9334502008-09-04 21:48:47 +0000771 if (Stmt* I = F->getInc()) {
772 // Generate increment code in its own basic block. This is the target
773 // of continue statements.
Ted Kremenekd0172432008-11-24 20:50:24 +0000774 Succ = Visit(I);
Ted Kremeneke9334502008-09-04 21:48:47 +0000775 }
776 else {
Ted Kremenek3575f842009-04-28 00:51:56 +0000777 // No increment code. Create a special, empty, block that is used as
778 // the target block for "looping back" to the start of the loop.
779 assert(Succ == EntryConditionBlock);
780 Succ = createBlock();
Ted Kremeneke9334502008-09-04 21:48:47 +0000781 }
782
Ted Kremenek3575f842009-04-28 00:51:56 +0000783 // Finish up the increment (or empty) block if it hasn't been already.
784 if (Block) {
785 assert(Block == Succ);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000786 if (!FinishBlock(Block))
787 return 0;
Ted Kremenek3575f842009-04-28 00:51:56 +0000788 Block = 0;
789 }
790
791 ContinueTargetBlock = Succ;
792
793 // The starting block for the loop increment is the block that should
794 // represent the 'loop target' for looping back to the start of the loop.
795 ContinueTargetBlock->setLoopTarget(F);
796
Ted Kremeneke9334502008-09-04 21:48:47 +0000797 // All breaks should go to the code following the loop.
798 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000799
800 // Now populate the body block, and in the process create new blocks
801 // as we walk the body of the loop.
802 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000803
804 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000805 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000806 else if (Block) {
807 if (!FinishBlock(BodyBlock))
808 return 0;
809 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000810
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000811 // This new body block is a successor to our "exit" condition block.
812 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000813 }
814
815 // Link up the condition block with the code that follows the loop.
816 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000817 ExitConditionBlock->addSuccessor(LoopSuccessor);
818
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000819 // If the loop contains initialization, create a new block for those
820 // statements. This block can also contain statements that precede
821 // the loop.
822 if (Stmt* I = F->getInit()) {
823 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000824 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000825 }
826 else {
827 // There is no loop initialization. We are thus basically a while
828 // loop. NULL out Block to force lazy block construction.
829 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000830 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000831 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000832 }
833}
834
Ted Kremenek514de5a2008-11-11 17:10:00 +0000835CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
836 // Objective-C fast enumeration 'for' statements:
837 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
838 //
839 // for ( Type newVariable in collection_expression ) { statements }
840 //
841 // becomes:
842 //
843 // prologue:
844 // 1. collection_expression
845 // T. jump to loop_entry
846 // loop_entry:
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000847 // 1. side-effects of element expression
Ted Kremenek514de5a2008-11-11 17:10:00 +0000848 // 1. ObjCForCollectionStmt [performs binding to newVariable]
849 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
850 // TB:
851 // statements
852 // T. jump to loop_entry
853 // FB:
854 // what comes after
855 //
856 // and
857 //
858 // Type existingItem;
859 // for ( existingItem in expression ) { statements }
860 //
861 // becomes:
862 //
863 // the same with newVariable replaced with existingItem; the binding
864 // works the same except that for one ObjCForCollectionStmt::getElement()
865 // returns a DeclStmt and the other returns a DeclRefExpr.
866 //
867
868 CFGBlock* LoopSuccessor = 0;
869
870 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000871 if (!FinishBlock(Block))
872 return 0;
Ted Kremenek514de5a2008-11-11 17:10:00 +0000873 LoopSuccessor = Block;
874 Block = 0;
875 }
876 else LoopSuccessor = Succ;
877
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000878 // Build the condition blocks.
879 CFGBlock* ExitConditionBlock = createBlock(false);
880 CFGBlock* EntryConditionBlock = ExitConditionBlock;
881
882 // Set the terminator for the "exit" condition block.
883 ExitConditionBlock->setTerminator(S);
884
885 // The last statement in the block should be the ObjCForCollectionStmt,
886 // which performs the actual binding to 'element' and determines if there
887 // are any more items in the collection.
888 ExitConditionBlock->appendStmt(S);
889 Block = ExitConditionBlock;
890
891 // Walk the 'element' expression to see if there are any side-effects. We
892 // generate new blocks as necesary. We DON'T add the statement by default
893 // to the CFG unless it contains control-flow.
894 EntryConditionBlock = WalkAST(S->getElement(), false);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000895 if (Block) {
896 if (!FinishBlock(EntryConditionBlock))
897 return 0;
898 Block = 0;
899 }
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000900
901 // The condition block is the implicit successor for the loop body as
902 // well as any code above the loop.
903 Succ = EntryConditionBlock;
Ted Kremenek514de5a2008-11-11 17:10:00 +0000904
905 // Now create the true branch.
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000906 {
907 // Save the current values for Succ, continue and break targets.
908 SaveAndRestore<CFGBlock*> save_Succ(Succ),
909 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
910
911 BreakTargetBlock = LoopSuccessor;
912 ContinueTargetBlock = EntryConditionBlock;
913
914 CFGBlock* BodyBlock = Visit(S->getBody());
915
916 if (!BodyBlock)
917 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000918 else if (Block) {
919 if (!FinishBlock(BodyBlock))
920 return 0;
921 }
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000922
923 // This new body block is a successor to our "exit" condition block.
924 ExitConditionBlock->addSuccessor(BodyBlock);
925 }
Ted Kremenekfc335522008-11-13 06:36:45 +0000926
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000927 // Link up the condition block with the code that follows the loop.
928 // (the false branch).
929 ExitConditionBlock->addSuccessor(LoopSuccessor);
930
Ted Kremenek514de5a2008-11-11 17:10:00 +0000931 // Now create a prologue block to contain the collection expression.
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000932 Block = createBlock();
Ted Kremenek514de5a2008-11-11 17:10:00 +0000933 return addStmt(S->getCollection());
934}
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000935
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000936CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
937 // FIXME: Add locking 'primitives' to CFG for @synchronized.
938
939 // Inline the body.
Ted Kremenekda5348e2009-05-05 23:11:51 +0000940 CFGBlock *SyncBlock = Visit(S->getSynchBody());
941
942 // The sync body starts its own basic block. This makes it a little easier
943 // for diagnostic clients.
944 if (SyncBlock) {
945 if (!FinishBlock(SyncBlock))
946 return 0;
947
948 Block = 0;
949 }
950
951 Succ = SyncBlock;
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000952
953 // Inline the sync expression.
954 return Visit(S->getSynchExpr());
955}
956
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000957CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
Ted Kremenek90658ec2009-04-07 04:26:02 +0000958 return NYS();
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000959}
Ted Kremenek514de5a2008-11-11 17:10:00 +0000960
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000961CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
962 // "while" is a control-flow statement. Thus we stop processing the
963 // current block.
964
965 CFGBlock* LoopSuccessor = NULL;
966
967 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000968 if (!FinishBlock(Block))
969 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000970 LoopSuccessor = Block;
971 }
972 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000973
974 // Because of short-circuit evaluation, the condition of the loop
975 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
976 // blocks that evaluate the condition.
977 CFGBlock* ExitConditionBlock = createBlock(false);
978 CFGBlock* EntryConditionBlock = ExitConditionBlock;
979
980 // Set the terminator for the "exit" condition block.
981 ExitConditionBlock->setTerminator(W);
982
983 // Now add the actual condition to the condition block. Because the
984 // condition itself may contain control-flow, new blocks may be created.
985 // Thus we update "Succ" after adding the condition.
986 if (Stmt* C = W->getCond()) {
987 Block = ExitConditionBlock;
988 EntryConditionBlock = addStmt(C);
Ted Kremenekf6e85412009-04-28 03:09:44 +0000989 assert(Block == EntryConditionBlock);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000990 if (Block) {
991 if (!FinishBlock(EntryConditionBlock))
992 return 0;
993 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000994 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000995
996 // The condition block is the implicit successor for the loop body as
997 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000998 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000999
1000 // Process the loop body.
1001 {
Ted Kremenekf6e85412009-04-28 03:09:44 +00001002 assert(W->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001003
1004 // Save the current values for Block, Succ, and continue and break targets
1005 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1006 save_continue(ContinueTargetBlock),
1007 save_break(BreakTargetBlock);
Ted Kremenekf6e85412009-04-28 03:09:44 +00001008
1009 // Create an empty block to represent the transition block for looping
1010 // back to the head of the loop.
1011 Block = 0;
1012 assert(Succ == EntryConditionBlock);
1013 Succ = createBlock();
1014 Succ->setLoopTarget(W);
1015 ContinueTargetBlock = Succ;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001016
1017 // All breaks should go to the code following the loop.
1018 BreakTargetBlock = LoopSuccessor;
1019
1020 // NULL out Block to force lazy instantiation of blocks for the body.
1021 Block = NULL;
1022
1023 // Create the body. The returned block is the entry to the loop body.
1024 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +00001025
1026 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +00001027 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001028 else if (Block) {
1029 if (!FinishBlock(BodyBlock))
1030 return 0;
1031 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001032
1033 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001034 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001035 }
1036
1037 // Link up the condition block with the code that follows the loop.
1038 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001039 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001040
1041 // There can be no more statements in the condition block
1042 // since we loop back to this block. NULL out Block to force
1043 // lazy creation of another block.
1044 Block = NULL;
1045
1046 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +00001047 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001048 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001049}
Ted Kremenek2fda5042008-12-09 20:20:09 +00001050
1051CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1052 // FIXME: This isn't complete. We basically treat @throw like a return
1053 // statement.
1054
1055 // If we were in the middle of a block we stop processing that block
1056 // and reverse its statements.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001057 if (Block) {
1058 if (!FinishBlock(Block))
1059 return 0;
1060 }
Ted Kremenek2fda5042008-12-09 20:20:09 +00001061
1062 // Create the new block.
1063 Block = createBlock(false);
1064
1065 // The Exit block is the only successor.
1066 Block->addSuccessor(&cfg->getExit());
1067
1068 // Add the statement to the block. This may create new blocks
1069 // if S contains control-flow (short-circuit operations).
1070 return addStmt(S);
1071}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001072
1073CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
1074 // "do...while" is a control-flow statement. Thus we stop processing the
1075 // current block.
1076
1077 CFGBlock* LoopSuccessor = NULL;
1078
1079 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001080 if (!FinishBlock(Block))
1081 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001082 LoopSuccessor = Block;
1083 }
1084 else LoopSuccessor = Succ;
1085
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001086 // Because of short-circuit evaluation, the condition of the loop
1087 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
1088 // blocks that evaluate the condition.
1089 CFGBlock* ExitConditionBlock = createBlock(false);
1090 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1091
1092 // Set the terminator for the "exit" condition block.
1093 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001094
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001095 // Now add the actual condition to the condition block. Because the
1096 // condition itself may contain control-flow, new blocks may be created.
1097 if (Stmt* C = D->getCond()) {
1098 Block = ExitConditionBlock;
1099 EntryConditionBlock = addStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001100 if (Block) {
1101 if (!FinishBlock(EntryConditionBlock))
1102 return 0;
1103 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001104 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001105
Ted Kremenek54827132008-02-27 07:20:00 +00001106 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001107 Succ = EntryConditionBlock;
1108
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001109 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001110 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001111 {
1112 assert (D->getBody());
1113
1114 // Save the current values for Block, Succ, and continue and break targets
1115 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1116 save_continue(ContinueTargetBlock),
1117 save_break(BreakTargetBlock);
1118
1119 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001120 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001121
1122 // All breaks should go to the code following the loop.
1123 BreakTargetBlock = LoopSuccessor;
1124
1125 // NULL out Block to force lazy instantiation of blocks for the body.
1126 Block = NULL;
1127
1128 // Create the body. The returned block is the entry to the loop body.
1129 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001130
Ted Kremenekaf603f72007-08-30 18:39:40 +00001131 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +00001132 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001133 else if (Block) {
1134 if (!FinishBlock(BodyBlock))
1135 return 0;
1136 }
Ted Kremenekaf603f72007-08-30 18:39:40 +00001137
Ted Kremenek8f08c9d2009-04-28 04:22:00 +00001138 // Add an intermediate block between the BodyBlock and the
1139 // ExitConditionBlock to represent the "loop back" transition.
1140 // Create an empty block to represent the transition block for looping
1141 // back to the head of the loop.
1142 // FIXME: Can we do this more efficiently without adding another block?
1143 Block = NULL;
1144 Succ = BodyBlock;
1145 CFGBlock *LoopBackBlock = createBlock();
1146 LoopBackBlock->setLoopTarget(D);
1147
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001148 // Add the loop body entry as a successor to the condition.
Ted Kremenek8f08c9d2009-04-28 04:22:00 +00001149 ExitConditionBlock->addSuccessor(LoopBackBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001150 }
1151
1152 // Link up the condition block with the code that follows the loop.
1153 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001154 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001155
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001156 // There can be no more statements in the body block(s)
1157 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001158 // lazy creation of another block.
1159 Block = NULL;
1160
1161 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +00001162 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001163 return BodyBlock;
1164}
1165
1166CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1167 // "continue" is a control-flow statement. Thus we stop processing the
1168 // current block.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001169 if (Block) {
1170 if (!FinishBlock(Block))
1171 return 0;
1172 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001173
1174 // Now create a new block that ends with the continue statement.
1175 Block = createBlock(false);
1176 Block->setTerminator(C);
1177
1178 // If there is no target for the continue, then we are looking at an
Ted Kremenek235c5ed2009-04-07 18:53:24 +00001179 // incomplete AST. This means the CFG cannot be constructed.
1180 if (ContinueTargetBlock)
1181 Block->addSuccessor(ContinueTargetBlock);
1182 else
1183 badCFG = true;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001184
1185 return Block;
1186}
1187
1188CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
1189 // "break" is a control-flow statement. Thus we stop processing the
1190 // current block.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001191 if (Block) {
1192 if (!FinishBlock(Block))
1193 return 0;
1194 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001195
1196 // Now create a new block that ends with the continue statement.
1197 Block = createBlock(false);
1198 Block->setTerminator(B);
1199
1200 // If there is no target for the break, then we are looking at an
Ted Kremenek235c5ed2009-04-07 18:53:24 +00001201 // incomplete AST. This means that the CFG cannot be constructed.
1202 if (BreakTargetBlock)
1203 Block->addSuccessor(BreakTargetBlock);
1204 else
1205 badCFG = true;
1206
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001207
1208 return Block;
1209}
1210
Ted Kremenek411cdee2008-04-16 21:10:48 +00001211CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001212 // "switch" is a control-flow statement. Thus we stop processing the
1213 // current block.
1214 CFGBlock* SwitchSuccessor = NULL;
1215
1216 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001217 if (!FinishBlock(Block))
1218 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001219 SwitchSuccessor = Block;
1220 }
1221 else SwitchSuccessor = Succ;
1222
1223 // Save the current "switch" context.
1224 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001225 save_break(BreakTargetBlock),
1226 save_default(DefaultCaseBlock);
1227
1228 // Set the "default" case to be the block after the switch statement.
1229 // If the switch statement contains a "default:", this value will
1230 // be overwritten with the block for that code.
1231 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001232
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001233 // Create a new block that will contain the switch statement.
1234 SwitchTerminatedBlock = createBlock(false);
1235
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001236 // Now process the switch body. The code after the switch is the implicit
1237 // successor.
1238 Succ = SwitchSuccessor;
1239 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001240
1241 // When visiting the body, the case statements should automatically get
1242 // linked up to the switch. We also don't keep a pointer to the body,
1243 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001244 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001245 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001246 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001247 if (Block) {
1248 if (!FinishBlock(BodyBlock))
1249 return 0;
1250 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001251
Ted Kremenek295222c2008-02-13 21:46:34 +00001252 // If we have no "default:" case, the default transition is to the
1253 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001254 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001255
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001256 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001257 SwitchTerminatedBlock->setTerminator(Terminator);
1258 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001259 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001260
Ted Kremenek411cdee2008-04-16 21:10:48 +00001261 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001262}
1263
Ted Kremenek411cdee2008-04-16 21:10:48 +00001264CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001265 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001266 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001267
Ted Kremenek411cdee2008-04-16 21:10:48 +00001268 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001269 CFGBlock* CaseBlock = Block;
1270 if (!CaseBlock) CaseBlock = createBlock();
1271
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001272 // Cases statements partition blocks, so this is the top of
1273 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001274 CaseBlock->setLabel(Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001275 if (!FinishBlock(CaseBlock))
1276 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001277
1278 // Add this block to the list of successors for the block with the
1279 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001280 assert (SwitchTerminatedBlock);
1281 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001282
1283 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1284 Block = NULL;
1285
1286 // This block is now the implicit successor of other blocks.
1287 Succ = CaseBlock;
1288
Ted Kremenek2677ea82008-03-15 07:45:02 +00001289 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001290}
Ted Kremenek295222c2008-02-13 21:46:34 +00001291
Ted Kremenek411cdee2008-04-16 21:10:48 +00001292CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1293 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001294 DefaultCaseBlock = Block;
1295 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1296
1297 // Default statements partition blocks, so this is the top of
1298 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001299 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001300 if (!FinishBlock(DefaultCaseBlock))
1301 return 0;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001302
1303 // Unlike case statements, we don't add the default block to the
1304 // successors for the switch statement immediately. This is done
1305 // when we finish processing the switch statement. This allows for
1306 // the default case (including a fall-through to the code after the
1307 // switch statement) to always be the last successor of a switch-terminated
1308 // block.
1309
1310 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1311 Block = NULL;
1312
1313 // This block is now the implicit successor of other blocks.
1314 Succ = DefaultCaseBlock;
1315
1316 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001317}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001318
Ted Kremenek19bb3562007-08-28 19:26:49 +00001319CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1320 // Lazily create the indirect-goto dispatch block if there isn't one
1321 // already.
1322 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1323
1324 if (!IBlock) {
1325 IBlock = createBlock(false);
1326 cfg->setIndirectGotoBlock(IBlock);
1327 }
1328
1329 // IndirectGoto is a control-flow statement. Thus we stop processing the
1330 // current block and create a new one.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001331 if (Block) {
1332 if (!FinishBlock(Block))
1333 return 0;
1334 }
Ted Kremenek19bb3562007-08-28 19:26:49 +00001335 Block = createBlock(false);
1336 Block->setTerminator(I);
1337 Block->addSuccessor(IBlock);
1338 return addStmt(I->getTarget());
1339}
1340
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001341
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001342} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001343
1344/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1345/// block has no successors or predecessors. If this is the first block
1346/// created in the CFG, it is automatically set to be the Entry and Exit
1347/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001348CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001349 bool first_block = begin() == end();
1350
1351 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001352 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001353
1354 // If this is the first block, set it as the Entry and Exit.
1355 if (first_block) Entry = Exit = &front();
1356
1357 // Return the block.
1358 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001359}
1360
Ted Kremenek026473c2007-08-23 16:51:22 +00001361/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1362/// CFG is returned to the caller.
1363CFG* CFG::buildCFG(Stmt* Statement) {
1364 CFGBuilder Builder;
1365 return Builder.buildCFG(Statement);
1366}
1367
1368/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001369void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1370
Ted Kremenek63f58872007-10-01 19:33:33 +00001371//===----------------------------------------------------------------------===//
1372// CFG: Queries for BlkExprs.
1373//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001374
Ted Kremenek63f58872007-10-01 19:33:33 +00001375namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001376 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001377}
1378
Ted Kremenek411cdee2008-04-16 21:10:48 +00001379static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1380 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001381 return;
1382
Ted Kremenek411cdee2008-04-16 21:10:48 +00001383 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001384 if (!*I) continue;
1385
1386 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1387 if (B->isAssignmentOp()) Set.insert(B);
1388
1389 FindSubExprAssignments(*I, Set);
1390 }
1391}
1392
Ted Kremenek63f58872007-10-01 19:33:33 +00001393static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1394 BlkExprMapTy* M = new BlkExprMapTy();
1395
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001396 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001397 // only assignments that we want to *possibly* register as a block-level
1398 // expression. Basically, if an assignment occurs both in a subexpression
1399 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001400 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1401
Ted Kremenek63f58872007-10-01 19:33:33 +00001402 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1403 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001404 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001405
Ted Kremenek411cdee2008-04-16 21:10:48 +00001406 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1407
1408 // Iterate over the statements again on identify the Expr* and Stmt* at
1409 // the block-level that are block-level expressions.
1410
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001411 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001412 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001413
Ted Kremenek411cdee2008-04-16 21:10:48 +00001414 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001415 // Assignment expressions that are not nested within another
1416 // expression are really "statements" whose value is never
1417 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001418 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001419 continue;
1420 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001421 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001422 // Special handling for statement expressions. The last statement
1423 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001424 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001425 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001426 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001427 (*M)[C->body_back()] = x;
1428 }
1429 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001430
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001431 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001432 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001433 }
1434
Ted Kremenek411cdee2008-04-16 21:10:48 +00001435 // Look at terminators. The condition is a block-level expression.
1436
Ted Kremenek390e48b2008-11-12 21:11:49 +00001437 Stmt* S = I->getTerminatorCondition();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001438
Ted Kremenek390e48b2008-11-12 21:11:49 +00001439 if (S && M->find(S) == M->end()) {
Ted Kremenek411cdee2008-04-16 21:10:48 +00001440 unsigned x = M->size();
Ted Kremenek390e48b2008-11-12 21:11:49 +00001441 (*M)[S] = x;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001442 }
1443 }
1444
Ted Kremenek63f58872007-10-01 19:33:33 +00001445 return M;
1446}
1447
Ted Kremenek86946742008-01-17 20:48:37 +00001448CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1449 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001450 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1451
1452 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001453 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001454
1455 if (I == M->end()) return CFG::BlkExprNumTy();
1456 else return CFG::BlkExprNumTy(I->second);
1457}
1458
1459unsigned CFG::getNumBlkExprs() {
1460 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1461 return M->size();
1462 else {
1463 // We assume callers interested in the number of BlkExprs will want
1464 // the map constructed if it doesn't already exist.
1465 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1466 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1467 }
1468}
1469
Ted Kremenek274f4332008-04-28 18:00:46 +00001470//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001471// Cleanup: CFG dstor.
1472//===----------------------------------------------------------------------===//
1473
Ted Kremenek63f58872007-10-01 19:33:33 +00001474CFG::~CFG() {
1475 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1476}
1477
Ted Kremenek7dba8602007-08-29 21:56:09 +00001478//===----------------------------------------------------------------------===//
1479// CFG pretty printing
1480//===----------------------------------------------------------------------===//
1481
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001482namespace {
1483
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001484class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001485
Ted Kremenek42a509f2007-08-31 21:30:12 +00001486 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1487 StmtMapTy StmtMap;
1488 signed CurrentBlock;
1489 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001490
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001491public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001492
Ted Kremenek42a509f2007-08-31 21:30:12 +00001493 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1494 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1495 unsigned j = 1;
1496 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1497 BI != BEnd; ++BI, ++j )
1498 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1499 }
1500 }
1501
1502 virtual ~StmtPrinterHelper() {}
1503
1504 void setBlockID(signed i) { CurrentBlock = i; }
1505 void setStmtID(unsigned i) { CurrentStmt = i; }
1506
Ted Kremeneka95d3752008-09-13 05:16:45 +00001507 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001508
Ted Kremenek411cdee2008-04-16 21:10:48 +00001509 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001510
1511 if (I == StmtMap.end())
1512 return false;
1513
1514 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1515 && I->second.second == CurrentStmt)
1516 return false;
1517
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001518 OS << "[B" << I->second.first << "." << I->second.second << "]";
1519 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001520 }
1521};
1522
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001523class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1524 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1525
Ted Kremeneka95d3752008-09-13 05:16:45 +00001526 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001527 StmtPrinterHelper* Helper;
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001528 PrintingPolicy Policy;
1529
Ted Kremenek42a509f2007-08-31 21:30:12 +00001530public:
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001531 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1532 const PrintingPolicy &Policy = PrintingPolicy())
1533 : OS(os), Helper(helper), Policy(Policy) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001534
1535 void VisitIfStmt(IfStmt* I) {
1536 OS << "if ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001537 I->getCond()->printPretty(OS,Helper,Policy);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001538 }
1539
1540 // Default case.
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001541 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS, Helper, Policy); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001542
1543 void VisitForStmt(ForStmt* F) {
1544 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001545 if (F->getInit()) OS << "...";
1546 OS << "; ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001547 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek535bb202007-08-30 21:28:02 +00001548 OS << "; ";
1549 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001550 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001551 }
1552
1553 void VisitWhileStmt(WhileStmt* W) {
1554 OS << "while " ;
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001555 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001556 }
1557
1558 void VisitDoStmt(DoStmt* D) {
1559 OS << "do ... while ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001560 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001561 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001562
Ted Kremenek411cdee2008-04-16 21:10:48 +00001563 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001564 OS << "switch ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001565 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001566 }
1567
Ted Kremenek805e9a82007-08-31 21:49:40 +00001568 void VisitConditionalOperator(ConditionalOperator* C) {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001569 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremeneka2925852008-01-30 23:02:42 +00001570 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001571 }
1572
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001573 void VisitChooseExpr(ChooseExpr* C) {
1574 OS << "__builtin_choose_expr( ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001575 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremeneka2925852008-01-30 23:02:42 +00001576 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001577 }
1578
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001579 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1580 OS << "goto *";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001581 I->getTarget()->printPretty(OS, Helper, Policy);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001582 }
1583
Ted Kremenek805e9a82007-08-31 21:49:40 +00001584 void VisitBinaryOperator(BinaryOperator* B) {
1585 if (!B->isLogicalOp()) {
1586 VisitExpr(B);
1587 return;
1588 }
1589
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001590 B->getLHS()->printPretty(OS, Helper, Policy);
Ted Kremenek805e9a82007-08-31 21:49:40 +00001591
1592 switch (B->getOpcode()) {
1593 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001594 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001595 return;
1596 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001597 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001598 return;
1599 default:
1600 assert(false && "Invalid logical operator.");
1601 }
1602 }
1603
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001604 void VisitExpr(Expr* E) {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001605 E->printPretty(OS, Helper, Policy);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001606 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001607};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001608
1609
Ted Kremeneka95d3752008-09-13 05:16:45 +00001610void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001611 if (Helper) {
1612 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001613 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001614 CompoundStmt* Sub = SE->getSubStmt();
1615
1616 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001617 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001618 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001619 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001620 return;
1621 }
1622 }
1623
1624 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001625 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001626 if (B->getOpcode() == BinaryOperator::Comma) {
1627 OS << "... , ";
1628 Helper->handledStmt(B->getRHS(),OS);
1629 OS << '\n';
1630 return;
1631 }
1632 }
1633 }
1634
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001635 Terminator->printPretty(OS, Helper, /*FIXME:*/PrintingPolicy());
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001636
1637 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001638 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001639}
1640
Ted Kremeneka95d3752008-09-13 05:16:45 +00001641void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001642 StmtPrinterHelper* Helper, bool print_edges) {
1643
1644 if (Helper) Helper->setBlockID(B.getBlockID());
1645
Ted Kremenek7dba8602007-08-29 21:56:09 +00001646 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001647 OS << "\n [ B" << B.getBlockID();
1648
1649 if (&B == &cfg->getEntry())
1650 OS << " (ENTRY) ]\n";
1651 else if (&B == &cfg->getExit())
1652 OS << " (EXIT) ]\n";
1653 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001654 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001655 else
1656 OS << " ]\n";
1657
Ted Kremenek9cffe732007-08-29 23:20:49 +00001658 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001659 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001660
1661 if (print_edges)
1662 OS << " ";
1663
Ted Kremenek411cdee2008-04-16 21:10:48 +00001664 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001665 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001666 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001667 OS << "case ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001668 C->getLHS()->printPretty(OS, Helper, /*FIXME:*/PrintingPolicy());
Ted Kremenek9cffe732007-08-29 23:20:49 +00001669 if (C->getRHS()) {
1670 OS << " ... ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001671 C->getRHS()->printPretty(OS, Helper, /*FIXME:*/PrintingPolicy());
Ted Kremenek9cffe732007-08-29 23:20:49 +00001672 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001673 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001674 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001675 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001676 else
1677 assert(false && "Invalid label statement in CFGBlock.");
1678
Ted Kremenek9cffe732007-08-29 23:20:49 +00001679 OS << ":\n";
1680 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001681
Ted Kremenekfddd5182007-08-21 21:42:03 +00001682 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001683 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001684
1685 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1686 I != E ; ++I, ++j ) {
1687
Ted Kremenek9cffe732007-08-29 23:20:49 +00001688 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001689 if (print_edges)
1690 OS << " ";
1691
Ted Kremeneka95d3752008-09-13 05:16:45 +00001692 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001693
1694 if (Helper)
1695 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001696
1697 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001698 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001699
Ted Kremenek9cffe732007-08-29 23:20:49 +00001700 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001701 if (B.getTerminator()) {
1702 if (print_edges)
1703 OS << " ";
1704
Ted Kremenek9cffe732007-08-29 23:20:49 +00001705 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001706
1707 if (Helper) Helper->setBlockID(-1);
1708
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001709 CFGBlockTerminatorPrint TPrinter(OS, Helper, /*FIXME*/PrintingPolicy());
Ted Kremenek42a509f2007-08-31 21:30:12 +00001710 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001711 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001712 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001713
Ted Kremenek9cffe732007-08-29 23:20:49 +00001714 if (print_edges) {
1715 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001716 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001717 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001718
Ted Kremenek42a509f2007-08-31 21:30:12 +00001719 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1720 I != E; ++I, ++i) {
1721
1722 if (i == 8 || (i-8) == 0)
1723 OS << "\n ";
1724
Ted Kremenek9cffe732007-08-29 23:20:49 +00001725 OS << " B" << (*I)->getBlockID();
1726 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001727
1728 OS << '\n';
1729
1730 // Print the successors of this block.
1731 OS << " Successors (" << B.succ_size() << "):";
1732 i = 0;
1733
1734 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1735 I != E; ++I, ++i) {
1736
1737 if (i == 8 || (i-8) % 10 == 0)
1738 OS << "\n ";
1739
1740 OS << " B" << (*I)->getBlockID();
1741 }
1742
Ted Kremenek9cffe732007-08-29 23:20:49 +00001743 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001744 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001745}
1746
1747} // end anonymous namespace
1748
1749/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001750void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001751
1752/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001753void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001754
1755 StmtPrinterHelper Helper(this);
1756
1757 // Print the entry block.
1758 print_block(OS, this, getEntry(), &Helper, true);
1759
1760 // Iterate through the CFGBlocks and print them one by one.
1761 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1762 // Skip the entry block, because we already printed it.
1763 if (&(*I) == &getEntry() || &(*I) == &getExit())
1764 continue;
1765
1766 print_block(OS, this, *I, &Helper, true);
1767 }
1768
1769 // Print the exit block.
1770 print_block(OS, this, getExit(), &Helper, true);
Ted Kremenekd0172432008-11-24 20:50:24 +00001771 OS.flush();
Ted Kremenek42a509f2007-08-31 21:30:12 +00001772}
1773
1774/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001775void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001776
1777/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1778/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001779void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001780 StmtPrinterHelper Helper(cfg);
1781 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001782}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001783
Ted Kremeneka2925852008-01-30 23:02:42 +00001784/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001785void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001786 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1787 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1788}
1789
Ted Kremenek390e48b2008-11-12 21:11:49 +00001790Stmt* CFGBlock::getTerminatorCondition() {
Ted Kremenek411cdee2008-04-16 21:10:48 +00001791
1792 if (!Terminator)
1793 return NULL;
1794
1795 Expr* E = NULL;
1796
1797 switch (Terminator->getStmtClass()) {
1798 default:
1799 break;
1800
1801 case Stmt::ForStmtClass:
1802 E = cast<ForStmt>(Terminator)->getCond();
1803 break;
1804
1805 case Stmt::WhileStmtClass:
1806 E = cast<WhileStmt>(Terminator)->getCond();
1807 break;
1808
1809 case Stmt::DoStmtClass:
1810 E = cast<DoStmt>(Terminator)->getCond();
1811 break;
1812
1813 case Stmt::IfStmtClass:
1814 E = cast<IfStmt>(Terminator)->getCond();
1815 break;
1816
1817 case Stmt::ChooseExprClass:
1818 E = cast<ChooseExpr>(Terminator)->getCond();
1819 break;
1820
1821 case Stmt::IndirectGotoStmtClass:
1822 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1823 break;
1824
1825 case Stmt::SwitchStmtClass:
1826 E = cast<SwitchStmt>(Terminator)->getCond();
1827 break;
1828
1829 case Stmt::ConditionalOperatorClass:
1830 E = cast<ConditionalOperator>(Terminator)->getCond();
1831 break;
1832
1833 case Stmt::BinaryOperatorClass: // '&&' and '||'
1834 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek390e48b2008-11-12 21:11:49 +00001835 break;
1836
1837 case Stmt::ObjCForCollectionStmtClass:
1838 return Terminator;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001839 }
1840
1841 return E ? E->IgnoreParens() : NULL;
1842}
1843
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001844bool CFGBlock::hasBinaryBranchTerminator() const {
1845
1846 if (!Terminator)
1847 return false;
1848
1849 Expr* E = NULL;
1850
1851 switch (Terminator->getStmtClass()) {
1852 default:
1853 return false;
1854
1855 case Stmt::ForStmtClass:
1856 case Stmt::WhileStmtClass:
1857 case Stmt::DoStmtClass:
1858 case Stmt::IfStmtClass:
1859 case Stmt::ChooseExprClass:
1860 case Stmt::ConditionalOperatorClass:
1861 case Stmt::BinaryOperatorClass:
1862 return true;
1863 }
1864
1865 return E ? E->IgnoreParens() : NULL;
1866}
1867
Ted Kremeneka2925852008-01-30 23:02:42 +00001868
Ted Kremenek7dba8602007-08-29 21:56:09 +00001869//===----------------------------------------------------------------------===//
1870// CFG Graphviz Visualization
1871//===----------------------------------------------------------------------===//
1872
Ted Kremenek42a509f2007-08-31 21:30:12 +00001873
1874#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001875static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001876#endif
1877
1878void CFG::viewCFG() const {
1879#ifndef NDEBUG
1880 StmtPrinterHelper H(this);
1881 GraphHelper = &H;
1882 llvm::ViewGraph(this,"CFG");
1883 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001884#endif
1885}
1886
Ted Kremenek7dba8602007-08-29 21:56:09 +00001887namespace llvm {
1888template<>
1889struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Owen Anderson02995ce2009-06-24 17:37:55 +00001890 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph,
1891 bool ShortNames) {
Ted Kremenek7dba8602007-08-29 21:56:09 +00001892
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001893#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001894 std::string OutSStr;
1895 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001896 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001897 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001898
1899 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1900
1901 // Process string output to make it nicer...
1902 for (unsigned i = 0; i != OutStr.length(); ++i)
1903 if (OutStr[i] == '\n') { // Left justify
1904 OutStr[i] = '\\';
1905 OutStr.insert(OutStr.begin()+i+1, 'l');
1906 }
1907
1908 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001909#else
1910 return "";
1911#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001912 }
1913};
1914} // end namespace llvm