blob: 8e9c3fb10ba65d9619e6a878a3417fbdd38e89d3 [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 Kremenek00c0a302008-09-26 18:17:07 +0000168 // Blocks.
169 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
170 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
171
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000172private:
173 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000174 CFGBlock* addStmt(Stmt* Terminator);
175 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
176 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000177 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000178 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000179 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000180
Ted Kremenek4102af92008-03-13 03:04:22 +0000181 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000182};
Ted Kremenek610a09e2008-09-26 22:58:57 +0000183
184static VariableArrayType* FindVA(Type* t) {
185 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
186 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
187 if (vat->getSizeExpr())
188 return vat;
189
190 t = vt->getElementType().getTypePtr();
191 }
192
193 return 0;
194}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000195
196/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
197/// represent an arbitrary statement. Examples include a single expression
198/// or a function body (compound statement). The ownership of the returned
199/// CFG is transferred to the caller. If CFG construction fails, this method
200/// returns NULL.
201CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000202 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203 if (!Statement) return NULL;
204
Ted Kremenek4102af92008-03-13 03:04:22 +0000205 badCFG = false;
206
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000207 // Create an empty block that will serve as the exit block for the CFG.
208 // Since this is the first block added to the CFG, it will be implicitly
209 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000210 Succ = createBlock();
211 assert (Succ == &cfg->getExit());
212 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000213
214 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000215 CFGBlock* B = Visit(Statement);
216 if (!B) B = Succ;
217
218 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000219 // Finalize the last constructed block. This usually involves
220 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000221 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000222
223 // Backpatch the gotos whose label -> block mappings we didn't know
224 // when we encountered them.
225 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
226 E = BackpatchBlocks.end(); I != E; ++I ) {
227
228 CFGBlock* B = *I;
229 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
230 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
231
232 // If there is no target for the goto, then we are looking at an
233 // incomplete AST. Handle this by not registering a successor.
234 if (LI == LabelMap.end()) continue;
235
236 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000237 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000238
Ted Kremenek19bb3562007-08-28 19:26:49 +0000239 // Add successors to the Indirect Goto Dispatch block (if we have one).
240 if (CFGBlock* B = cfg->getIndirectGotoBlock())
241 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
242 E = AddressTakenLabels.end(); I != E; ++I ) {
243
244 // Lookup the target block.
245 LabelMapTy::iterator LI = LabelMap.find(*I);
246
247 // If there is no target block that contains label, then we are looking
248 // at an incomplete AST. Handle this by not registering a successor.
249 if (LI == LabelMap.end()) continue;
250
251 B->addSuccessor(LI->second);
252 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000253
Ted Kremenek94b33162007-09-17 16:18:02 +0000254 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000255 }
256
257 // Create an empty entry block that has no predecessors.
258 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000259
Ted Kremenek4102af92008-03-13 03:04:22 +0000260 if (badCFG) {
261 delete cfg;
262 cfg = NULL;
263 return NULL;
264 }
265
Ted Kremenek322f58d2007-09-26 21:23:31 +0000266 // NULL out cfg so that repeated calls to the builder will fail and that
267 // the ownership of the constructed CFG is passed to the caller.
268 CFG* t = cfg;
269 cfg = NULL;
270 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000271}
272
273/// createBlock - Used to lazily create blocks that are connected
274/// to the current (global) succcessor.
275CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000276 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000277 if (add_successor && Succ) B->addSuccessor(Succ);
278 return B;
279}
280
281/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000282/// we must reverse the statements because they have been inserted
283/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000284void CFGBuilder::FinishBlock(CFGBlock* B) {
285 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000286 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000287}
288
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000289/// addStmt - Used to add statements/expressions to the current CFGBlock
290/// "Block". This method calls WalkAST on the passed statement to see if it
291/// contains any short-circuit expressions. If so, it recursively creates
292/// the necessary blocks for such expressions. It returns the "topmost" block
293/// of the created blocks, or the original value of "Block" when this method
294/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000295CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000296 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000297 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000298}
299
300/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000301/// add extra blocks for ternary operators, &&, and ||. We also
302/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000303CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
304 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000305 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000306 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000307
308 // Create the confluence block that will "merge" the results
309 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000310 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
311 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000312 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000313
314 // Create a block for the LHS expression if there is an LHS expression.
315 // A GCC extension allows LHS to be NULL, causing the condition to
316 // be the value that is returned instead.
317 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000318 Succ = ConfluenceBlock;
319 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000320 CFGBlock* LHSBlock = NULL;
321 if (C->getLHS()) {
322 LHSBlock = Visit(C->getLHS());
323 FinishBlock(LHSBlock);
324 Block = NULL;
325 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000326
Ted Kremenekecc04c92007-11-26 18:20:26 +0000327 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000328 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000329 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000330 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000331
Ted Kremenekecc04c92007-11-26 18:20:26 +0000332 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000333 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000334
335 if (LHSBlock)
336 Block->addSuccessor(LHSBlock);
337 else {
338 // If we have no LHS expression, add the ConfluenceBlock as a direct
339 // successor for the block containing the condition. Moreover,
340 // we need to reverse the order of the predecessors in the
341 // ConfluenceBlock because the RHSBlock will have been added to
342 // the succcessors already, and we want the first predecessor to the
343 // the block containing the expression for the case when the ternary
344 // expression evaluates to true.
345 Block->addSuccessor(ConfluenceBlock);
346 assert (ConfluenceBlock->pred_size() == 2);
347 std::reverse(ConfluenceBlock->pred_begin(),
348 ConfluenceBlock->pred_end());
349 }
350
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000351 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000352
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000353 Block->setTerminator(C);
354 return addStmt(C->getCond());
355 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000356
357 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000358 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000359
360 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
361 ConfluenceBlock->appendStmt(C);
362 FinishBlock(ConfluenceBlock);
363
364 Succ = ConfluenceBlock;
365 Block = NULL;
366 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000367 FinishBlock(LHSBlock);
368
Ted Kremenek49a436d2007-08-31 17:03:41 +0000369 Succ = ConfluenceBlock;
370 Block = NULL;
371 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000372 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000373
374 Block = createBlock(false);
375 Block->addSuccessor(LHSBlock);
376 Block->addSuccessor(RHSBlock);
377 Block->setTerminator(C);
378 return addStmt(C->getCond());
379 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000380
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000381 case Stmt::DeclStmtClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000382 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000383
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000384 if (!D->getNextDeclarator()) {
385 Block->appendStmt(Terminator);
386 return WalkAST_VisitDeclSubExpr(D);
387 }
388 else {
389 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
390 BufTy Buf;
391 CFGBlock* B = 0;
392 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
393 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
394 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
395 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
396 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
397
398 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
399 // get automatically freed with the CFG.
400 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
401 // Append the fake DeclStmt to block.
402 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
403 B = WalkAST_VisitDeclSubExpr(*I);
404 }
405 return B;
406 }
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000407 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000408
Ted Kremenek19bb3562007-08-28 19:26:49 +0000409 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000410 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000411 AddressTakenLabels.insert(A->getLabel());
412
Ted Kremenek411cdee2008-04-16 21:10:48 +0000413 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000414 return Block;
415 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000416
Ted Kremenek15c27a82007-08-28 18:30:10 +0000417 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000418 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000419
Ted Kremenek610a09e2008-09-26 22:58:57 +0000420 case Stmt::SizeOfAlignOfTypeExprClass: {
421 SizeOfAlignOfTypeExpr* E = cast<SizeOfAlignOfTypeExpr>(Terminator);
422
423 // VLA types have expressions that must be evaluated.
424 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
425 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
426 addStmt(VA->getSizeExpr());
427
428 return Block;
429 }
430
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000431 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000432 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000433
434 // sizeof(expressions). For such expressions,
435 // the subexpression is not really evaluated, so
436 // we don't care about control-flow within the sizeof.
437 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000438 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000439 return Block;
440 }
441
442 break;
443 }
444
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000445 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000446 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000447
448 if (B->isLogicalOp()) { // && or ||
449 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
450 ConfluenceBlock->appendStmt(B);
451 FinishBlock(ConfluenceBlock);
452
453 // create the block evaluating the LHS
454 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000455 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000456
457 // create the block evaluating the RHS
458 Succ = ConfluenceBlock;
459 Block = NULL;
460 CFGBlock* RHSBlock = Visit(B->getRHS());
Zhongxing Xu924d9a82008-10-04 05:48:38 +0000461 FinishBlock(RHSBlock);
Ted Kremenekafe54332007-12-21 19:49:00 +0000462
463 // Now link the LHSBlock with RHSBlock.
464 if (B->getOpcode() == BinaryOperator::LOr) {
465 LHSBlock->addSuccessor(ConfluenceBlock);
466 LHSBlock->addSuccessor(RHSBlock);
467 }
468 else {
469 assert (B->getOpcode() == BinaryOperator::LAnd);
470 LHSBlock->addSuccessor(RHSBlock);
471 LHSBlock->addSuccessor(ConfluenceBlock);
472 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000473
474 // Generate the blocks for evaluating the LHS.
475 Block = LHSBlock;
476 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000477 }
478 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
479 Block->appendStmt(B);
480 addStmt(B->getRHS());
481 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000482 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000483
484 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000485 }
Ted Kremenek00c0a302008-09-26 18:17:07 +0000486
487 // Blocks: No support for blocks ... yet
488 case Stmt::BlockExprClass:
489 case Stmt::BlockDeclRefExprClass:
490 return NYS();
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000491
492 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000493 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000494
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000495 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000496 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000497 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000498
Ted Kremenek411cdee2008-04-16 21:10:48 +0000499 if (AlwaysAddStmt) Block->appendStmt(Terminator);
500 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000501}
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000502
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000503/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
504/// for initializers in Decls.
505CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
506 VarDecl* VD = dyn_cast<VarDecl>(D);
507
508 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000509 return Block;
510
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000511 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000512
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000513 if (Init) {
514 // Optimization: Don't create separate block-level statements for literals.
515 switch (Init->getStmtClass()) {
516 case Stmt::IntegerLiteralClass:
517 case Stmt::CharacterLiteralClass:
518 case Stmt::StringLiteralClass:
519 break;
520 default:
521 Block = addStmt(Init);
522 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000523 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000524
525 // If the type of VD is a VLA, then we must process its size expressions.
526 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
527 VA = FindVA(VA->getElementType().getTypePtr()))
528 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000529
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000530 return Block;
531}
532
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000533/// WalkAST_VisitChildren - Utility method to call WalkAST on the
534/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000535CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000536 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000537 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000538 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000539 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000540
541 return B;
542}
543
Ted Kremenek15c27a82007-08-28 18:30:10 +0000544/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
545/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000546CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
547 Block->appendStmt(Terminator);
548 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000549}
550
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000551/// VisitStmt - Handle statements with no branching control flow.
552CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
553 // We cannot assume that we are in the middle of a basic block, since
554 // the CFG might only be constructed for this single statement. If
555 // we have no current basic block, just create one lazily.
556 if (!Block) Block = createBlock();
557
558 // Simply add the statement to the current block. We actually
559 // insert statements in reverse order; this order is reversed later
560 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000561 addStmt(Statement);
562
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000563 return Block;
564}
565
566CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
567 return Block;
568}
569
570CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000571
572 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000573
Ted Kremenekd34066c2008-02-26 00:22:58 +0000574 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
575 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000576 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000577 }
578
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000579 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000580}
581
582CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
583 // We may see an if statement in the middle of a basic block, or
584 // it may be the first statement we are processing. In either case,
585 // we create a new basic block. First, we create the blocks for
586 // the then...else statements, and then we create the block containing
587 // the if statement. If we were in the middle of a block, we
588 // stop processing that block and reverse its statements. That block
589 // is then the implicit successor for the "then" and "else" clauses.
590
591 // The block we were proccessing is now finished. Make it the
592 // successor block.
593 if (Block) {
594 Succ = Block;
595 FinishBlock(Block);
596 }
597
598 // Process the false branch. NULL out Block so that the recursive
599 // call to Visit will create a new basic block.
600 // Null out Block so that all successor
601 CFGBlock* ElseBlock = Succ;
602
603 if (Stmt* Else = I->getElse()) {
604 SaveAndRestore<CFGBlock*> sv(Succ);
605
606 // NULL out Block so that the recursive call to Visit will
607 // create a new basic block.
608 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000609 ElseBlock = Visit(Else);
610
611 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
612 ElseBlock = sv.get();
613 else if (Block)
614 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000615 }
616
617 // Process the true branch. NULL out Block so that the recursive
618 // call to Visit will create a new basic block.
619 // Null out Block so that all successor
620 CFGBlock* ThenBlock;
621 {
622 Stmt* Then = I->getThen();
623 assert (Then);
624 SaveAndRestore<CFGBlock*> sv(Succ);
625 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000626 ThenBlock = Visit(Then);
627
628 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
629 ThenBlock = sv.get();
630 else if (Block)
631 FinishBlock(ThenBlock);
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 Kremenekd4fdee32007-08-23 21:42:29 +0000689 FinishBlock(LabelBlock);
690
691 // We set Block to NULL to allow lazy creation of a new block
692 // (if necessary);
693 Block = NULL;
694
695 // This block is now the implicit successor of other blocks.
696 Succ = LabelBlock;
697
698 return LabelBlock;
699}
700
701CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
702 // Goto is a control-flow statement. Thus we stop processing the
703 // current block and create a new one.
704 if (Block) FinishBlock(Block);
705 Block = createBlock(false);
706 Block->setTerminator(G);
707
708 // If we already know the mapping to the label block add the
709 // successor now.
710 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
711
712 if (I == LabelMap.end())
713 // We will need to backpatch this block later.
714 BackpatchBlocks.push_back(Block);
715 else
716 Block->addSuccessor(I->second);
717
718 return Block;
719}
720
721CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
722 // "for" is a control-flow statement. Thus we stop processing the
723 // current block.
724
725 CFGBlock* LoopSuccessor = NULL;
726
727 if (Block) {
728 FinishBlock(Block);
729 LoopSuccessor = Block;
730 }
731 else LoopSuccessor = Succ;
732
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000733 // Because of short-circuit evaluation, the condition of the loop
734 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
735 // blocks that evaluate the condition.
736 CFGBlock* ExitConditionBlock = createBlock(false);
737 CFGBlock* EntryConditionBlock = ExitConditionBlock;
738
739 // Set the terminator for the "exit" condition block.
740 ExitConditionBlock->setTerminator(F);
741
742 // Now add the actual condition to the condition block. Because the
743 // condition itself may contain control-flow, new blocks may be created.
744 if (Stmt* C = F->getCond()) {
745 Block = ExitConditionBlock;
746 EntryConditionBlock = addStmt(C);
747 if (Block) FinishBlock(EntryConditionBlock);
748 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000749
750 // The condition block is the implicit successor for the loop body as
751 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000752 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000753
754 // Now create the loop body.
755 {
756 assert (F->getBody());
757
758 // Save the current values for Block, Succ, and continue and break targets
759 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
760 save_continue(ContinueTargetBlock),
761 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000762
Ted Kremenekaf603f72007-08-30 18:39:40 +0000763 // Create a new block to contain the (bottom) of the loop body.
764 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000765
Ted Kremeneke9334502008-09-04 21:48:47 +0000766 if (Stmt* I = F->getInc()) {
767 // Generate increment code in its own basic block. This is the target
768 // of continue statements.
769 Succ = addStmt(I);
770 Block = 0;
771 ContinueTargetBlock = Succ;
772 }
773 else {
774 // No increment code. Continues should go the the entry condition block.
775 ContinueTargetBlock = EntryConditionBlock;
776 }
777
778 // All breaks should go to the code following the loop.
779 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000780
781 // Now populate the body block, and in the process create new blocks
782 // as we walk the body of the loop.
783 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000784
785 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000786 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000787 else if (Block)
788 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000789
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000790 // This new body block is a successor to our "exit" condition block.
791 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000792 }
793
794 // Link up the condition block with the code that follows the loop.
795 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000796 ExitConditionBlock->addSuccessor(LoopSuccessor);
797
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000798 // If the loop contains initialization, create a new block for those
799 // statements. This block can also contain statements that precede
800 // the loop.
801 if (Stmt* I = F->getInit()) {
802 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000803 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000804 }
805 else {
806 // There is no loop initialization. We are thus basically a while
807 // loop. NULL out Block to force lazy block construction.
808 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000809 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000810 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000811 }
812}
813
814CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
815 // "while" is a control-flow statement. Thus we stop processing the
816 // current block.
817
818 CFGBlock* LoopSuccessor = NULL;
819
820 if (Block) {
821 FinishBlock(Block);
822 LoopSuccessor = Block;
823 }
824 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000825
826 // Because of short-circuit evaluation, the condition of the loop
827 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
828 // blocks that evaluate the condition.
829 CFGBlock* ExitConditionBlock = createBlock(false);
830 CFGBlock* EntryConditionBlock = ExitConditionBlock;
831
832 // Set the terminator for the "exit" condition block.
833 ExitConditionBlock->setTerminator(W);
834
835 // Now add the actual condition to the condition block. Because the
836 // condition itself may contain control-flow, new blocks may be created.
837 // Thus we update "Succ" after adding the condition.
838 if (Stmt* C = W->getCond()) {
839 Block = ExitConditionBlock;
840 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000841 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000842 if (Block) FinishBlock(EntryConditionBlock);
843 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000844
845 // The condition block is the implicit successor for the loop body as
846 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000847 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000848
849 // Process the loop body.
850 {
851 assert (W->getBody());
852
853 // Save the current values for Block, Succ, and continue and break targets
854 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
855 save_continue(ContinueTargetBlock),
856 save_break(BreakTargetBlock);
857
858 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000859 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000860
861 // All breaks should go to the code following the loop.
862 BreakTargetBlock = LoopSuccessor;
863
864 // NULL out Block to force lazy instantiation of blocks for the body.
865 Block = NULL;
866
867 // Create the body. The returned block is the entry to the loop body.
868 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000869
870 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000871 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000872 else if (Block)
873 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000874
875 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000876 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000877 }
878
879 // Link up the condition block with the code that follows the loop.
880 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000881 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000882
883 // There can be no more statements in the condition block
884 // since we loop back to this block. NULL out Block to force
885 // lazy creation of another block.
886 Block = NULL;
887
888 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000889 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000890 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000891}
892
893CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
894 // "do...while" is a control-flow statement. Thus we stop processing the
895 // current block.
896
897 CFGBlock* LoopSuccessor = NULL;
898
899 if (Block) {
900 FinishBlock(Block);
901 LoopSuccessor = Block;
902 }
903 else LoopSuccessor = Succ;
904
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000905 // Because of short-circuit evaluation, the condition of the loop
906 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
907 // blocks that evaluate the condition.
908 CFGBlock* ExitConditionBlock = createBlock(false);
909 CFGBlock* EntryConditionBlock = ExitConditionBlock;
910
911 // Set the terminator for the "exit" condition block.
912 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000913
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000914 // Now add the actual condition to the condition block. Because the
915 // condition itself may contain control-flow, new blocks may be created.
916 if (Stmt* C = D->getCond()) {
917 Block = ExitConditionBlock;
918 EntryConditionBlock = addStmt(C);
919 if (Block) FinishBlock(EntryConditionBlock);
920 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000921
Ted Kremenek54827132008-02-27 07:20:00 +0000922 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000923 Succ = EntryConditionBlock;
924
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000925 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000926 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000927 {
928 assert (D->getBody());
929
930 // Save the current values for Block, Succ, and continue and break targets
931 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
932 save_continue(ContinueTargetBlock),
933 save_break(BreakTargetBlock);
934
935 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000936 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000937
938 // All breaks should go to the code following the loop.
939 BreakTargetBlock = LoopSuccessor;
940
941 // NULL out Block to force lazy instantiation of blocks for the body.
942 Block = NULL;
943
944 // Create the body. The returned block is the entry to the loop body.
945 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000946
Ted Kremenekaf603f72007-08-30 18:39:40 +0000947 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000948 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000949 else if (Block)
950 FinishBlock(BodyBlock);
951
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000952 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000953 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000954 }
955
956 // Link up the condition block with the code that follows the loop.
957 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000958 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000959
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000960 // There can be no more statements in the body block(s)
961 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000962 // lazy creation of another block.
963 Block = NULL;
964
965 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000966 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000967 return BodyBlock;
968}
969
970CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
971 // "continue" is a control-flow statement. Thus we stop processing the
972 // current block.
973 if (Block) FinishBlock(Block);
974
975 // Now create a new block that ends with the continue statement.
976 Block = createBlock(false);
977 Block->setTerminator(C);
978
979 // If there is no target for the continue, then we are looking at an
980 // incomplete AST. Handle this by not registering a successor.
981 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
982
983 return Block;
984}
985
986CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
987 // "break" is a control-flow statement. Thus we stop processing the
988 // current block.
989 if (Block) FinishBlock(Block);
990
991 // Now create a new block that ends with the continue statement.
992 Block = createBlock(false);
993 Block->setTerminator(B);
994
995 // If there is no target for the break, then we are looking at an
996 // incomplete AST. Handle this by not registering a successor.
997 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
998
999 return Block;
1000}
1001
Ted Kremenek411cdee2008-04-16 21:10:48 +00001002CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001003 // "switch" is a control-flow statement. Thus we stop processing the
1004 // current block.
1005 CFGBlock* SwitchSuccessor = NULL;
1006
1007 if (Block) {
1008 FinishBlock(Block);
1009 SwitchSuccessor = Block;
1010 }
1011 else SwitchSuccessor = Succ;
1012
1013 // Save the current "switch" context.
1014 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001015 save_break(BreakTargetBlock),
1016 save_default(DefaultCaseBlock);
1017
1018 // Set the "default" case to be the block after the switch statement.
1019 // If the switch statement contains a "default:", this value will
1020 // be overwritten with the block for that code.
1021 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001022
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001023 // Create a new block that will contain the switch statement.
1024 SwitchTerminatedBlock = createBlock(false);
1025
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001026 // Now process the switch body. The code after the switch is the implicit
1027 // successor.
1028 Succ = SwitchSuccessor;
1029 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001030
1031 // When visiting the body, the case statements should automatically get
1032 // linked up to the switch. We also don't keep a pointer to the body,
1033 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001034 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001035 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001036 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001037 if (Block) FinishBlock(BodyBlock);
1038
Ted Kremenek295222c2008-02-13 21:46:34 +00001039 // If we have no "default:" case, the default transition is to the
1040 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001041 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001042
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001043 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001044 SwitchTerminatedBlock->setTerminator(Terminator);
1045 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001046 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001047
Ted Kremenek411cdee2008-04-16 21:10:48 +00001048 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001049}
1050
Ted Kremenek411cdee2008-04-16 21:10:48 +00001051CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001052 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001053 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001054
Ted Kremenek411cdee2008-04-16 21:10:48 +00001055 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001056 CFGBlock* CaseBlock = Block;
1057 if (!CaseBlock) CaseBlock = createBlock();
1058
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001059 // Cases statements partition blocks, so this is the top of
1060 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001061 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001062 FinishBlock(CaseBlock);
1063
1064 // Add this block to the list of successors for the block with the
1065 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001066 assert (SwitchTerminatedBlock);
1067 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001068
1069 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1070 Block = NULL;
1071
1072 // This block is now the implicit successor of other blocks.
1073 Succ = CaseBlock;
1074
Ted Kremenek2677ea82008-03-15 07:45:02 +00001075 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001076}
Ted Kremenek295222c2008-02-13 21:46:34 +00001077
Ted Kremenek411cdee2008-04-16 21:10:48 +00001078CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1079 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001080 DefaultCaseBlock = Block;
1081 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1082
1083 // Default statements partition blocks, so this is the top of
1084 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001085 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001086 FinishBlock(DefaultCaseBlock);
1087
1088 // Unlike case statements, we don't add the default block to the
1089 // successors for the switch statement immediately. This is done
1090 // when we finish processing the switch statement. This allows for
1091 // the default case (including a fall-through to the code after the
1092 // switch statement) to always be the last successor of a switch-terminated
1093 // block.
1094
1095 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1096 Block = NULL;
1097
1098 // This block is now the implicit successor of other blocks.
1099 Succ = DefaultCaseBlock;
1100
1101 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001102}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001103
Ted Kremenek19bb3562007-08-28 19:26:49 +00001104CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1105 // Lazily create the indirect-goto dispatch block if there isn't one
1106 // already.
1107 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1108
1109 if (!IBlock) {
1110 IBlock = createBlock(false);
1111 cfg->setIndirectGotoBlock(IBlock);
1112 }
1113
1114 // IndirectGoto is a control-flow statement. Thus we stop processing the
1115 // current block and create a new one.
1116 if (Block) FinishBlock(Block);
1117 Block = createBlock(false);
1118 Block->setTerminator(I);
1119 Block->addSuccessor(IBlock);
1120 return addStmt(I->getTarget());
1121}
1122
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001123
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001124} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001125
1126/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1127/// block has no successors or predecessors. If this is the first block
1128/// created in the CFG, it is automatically set to be the Entry and Exit
1129/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001130CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001131 bool first_block = begin() == end();
1132
1133 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001134 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001135
1136 // If this is the first block, set it as the Entry and Exit.
1137 if (first_block) Entry = Exit = &front();
1138
1139 // Return the block.
1140 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001141}
1142
Ted Kremenek026473c2007-08-23 16:51:22 +00001143/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1144/// CFG is returned to the caller.
1145CFG* CFG::buildCFG(Stmt* Statement) {
1146 CFGBuilder Builder;
1147 return Builder.buildCFG(Statement);
1148}
1149
1150/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001151void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1152
Ted Kremenek63f58872007-10-01 19:33:33 +00001153//===----------------------------------------------------------------------===//
1154// CFG: Queries for BlkExprs.
1155//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001156
Ted Kremenek63f58872007-10-01 19:33:33 +00001157namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001158 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001159}
1160
Ted Kremenek411cdee2008-04-16 21:10:48 +00001161static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1162 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001163 return;
1164
Ted Kremenek411cdee2008-04-16 21:10:48 +00001165 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001166 if (!*I) continue;
1167
1168 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1169 if (B->isAssignmentOp()) Set.insert(B);
1170
1171 FindSubExprAssignments(*I, Set);
1172 }
1173}
1174
Ted Kremenek63f58872007-10-01 19:33:33 +00001175static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1176 BlkExprMapTy* M = new BlkExprMapTy();
1177
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001178 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001179 // only assignments that we want to *possibly* register as a block-level
1180 // expression. Basically, if an assignment occurs both in a subexpression
1181 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001182 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1183
Ted Kremenek63f58872007-10-01 19:33:33 +00001184 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1185 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001186 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001187
Ted Kremenek411cdee2008-04-16 21:10:48 +00001188 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1189
1190 // Iterate over the statements again on identify the Expr* and Stmt* at
1191 // the block-level that are block-level expressions.
1192
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001193 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001194 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001195
Ted Kremenek411cdee2008-04-16 21:10:48 +00001196 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001197 // Assignment expressions that are not nested within another
1198 // expression are really "statements" whose value is never
1199 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001200 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001201 continue;
1202 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001203 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001204 // Special handling for statement expressions. The last statement
1205 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001206 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001207 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001208 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001209 (*M)[C->body_back()] = x;
1210 }
1211 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001212
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001213 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001214 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001215 }
1216
Ted Kremenek411cdee2008-04-16 21:10:48 +00001217 // Look at terminators. The condition is a block-level expression.
1218
1219 Expr* Exp = I->getTerminatorCondition();
1220
1221 if (Exp && M->find(Exp) == M->end()) {
1222 unsigned x = M->size();
1223 (*M)[Exp] = x;
1224 }
1225 }
1226
Ted Kremenek63f58872007-10-01 19:33:33 +00001227 return M;
1228}
1229
Ted Kremenek86946742008-01-17 20:48:37 +00001230CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1231 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001232 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1233
1234 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001235 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001236
1237 if (I == M->end()) return CFG::BlkExprNumTy();
1238 else return CFG::BlkExprNumTy(I->second);
1239}
1240
1241unsigned CFG::getNumBlkExprs() {
1242 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1243 return M->size();
1244 else {
1245 // We assume callers interested in the number of BlkExprs will want
1246 // the map constructed if it doesn't already exist.
1247 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1248 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1249 }
1250}
1251
Ted Kremenek274f4332008-04-28 18:00:46 +00001252//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001253// Cleanup: CFG dstor.
1254//===----------------------------------------------------------------------===//
1255
Ted Kremenek63f58872007-10-01 19:33:33 +00001256CFG::~CFG() {
1257 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1258}
1259
Ted Kremenek7dba8602007-08-29 21:56:09 +00001260//===----------------------------------------------------------------------===//
1261// CFG pretty printing
1262//===----------------------------------------------------------------------===//
1263
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001264namespace {
1265
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001266class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001267
Ted Kremenek42a509f2007-08-31 21:30:12 +00001268 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1269 StmtMapTy StmtMap;
1270 signed CurrentBlock;
1271 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001272
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001273public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001274
Ted Kremenek42a509f2007-08-31 21:30:12 +00001275 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1276 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1277 unsigned j = 1;
1278 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1279 BI != BEnd; ++BI, ++j )
1280 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1281 }
1282 }
1283
1284 virtual ~StmtPrinterHelper() {}
1285
1286 void setBlockID(signed i) { CurrentBlock = i; }
1287 void setStmtID(unsigned i) { CurrentStmt = i; }
1288
Ted Kremeneka95d3752008-09-13 05:16:45 +00001289 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001290
Ted Kremenek411cdee2008-04-16 21:10:48 +00001291 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001292
1293 if (I == StmtMap.end())
1294 return false;
1295
1296 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1297 && I->second.second == CurrentStmt)
1298 return false;
1299
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001300 OS << "[B" << I->second.first << "." << I->second.second << "]";
1301 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001302 }
1303};
1304
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001305class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1306 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1307
Ted Kremeneka95d3752008-09-13 05:16:45 +00001308 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001309 StmtPrinterHelper* Helper;
1310public:
Ted Kremeneka95d3752008-09-13 05:16:45 +00001311 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper)
Ted Kremenek42a509f2007-08-31 21:30:12 +00001312 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001313
1314 void VisitIfStmt(IfStmt* I) {
1315 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001316 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001317 }
1318
1319 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001320 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001321
1322 void VisitForStmt(ForStmt* F) {
1323 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001324 if (F->getInit()) OS << "...";
1325 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001326 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001327 OS << "; ";
1328 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001329 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001330 }
1331
1332 void VisitWhileStmt(WhileStmt* W) {
1333 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001334 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001335 }
1336
1337 void VisitDoStmt(DoStmt* D) {
1338 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001339 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001340 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001341
Ted Kremenek411cdee2008-04-16 21:10:48 +00001342 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001343 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001344 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001345 }
1346
Ted Kremenek805e9a82007-08-31 21:49:40 +00001347 void VisitConditionalOperator(ConditionalOperator* C) {
1348 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001349 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001350 }
1351
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001352 void VisitChooseExpr(ChooseExpr* C) {
1353 OS << "__builtin_choose_expr( ";
1354 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001355 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001356 }
1357
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001358 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1359 OS << "goto *";
1360 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001361 }
1362
Ted Kremenek805e9a82007-08-31 21:49:40 +00001363 void VisitBinaryOperator(BinaryOperator* B) {
1364 if (!B->isLogicalOp()) {
1365 VisitExpr(B);
1366 return;
1367 }
1368
1369 B->getLHS()->printPretty(OS,Helper);
1370
1371 switch (B->getOpcode()) {
1372 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001373 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001374 return;
1375 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001376 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001377 return;
1378 default:
1379 assert(false && "Invalid logical operator.");
1380 }
1381 }
1382
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001383 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001384 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001385 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001386};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001387
1388
Ted Kremeneka95d3752008-09-13 05:16:45 +00001389void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001390 if (Helper) {
1391 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001392 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001393 CompoundStmt* Sub = SE->getSubStmt();
1394
1395 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001396 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001397 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001398 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001399 return;
1400 }
1401 }
1402
1403 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001404 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001405 if (B->getOpcode() == BinaryOperator::Comma) {
1406 OS << "... , ";
1407 Helper->handledStmt(B->getRHS(),OS);
1408 OS << '\n';
1409 return;
1410 }
1411 }
1412 }
1413
Ted Kremenek411cdee2008-04-16 21:10:48 +00001414 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001415
1416 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001417 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001418}
1419
Ted Kremeneka95d3752008-09-13 05:16:45 +00001420void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001421 StmtPrinterHelper* Helper, bool print_edges) {
1422
1423 if (Helper) Helper->setBlockID(B.getBlockID());
1424
Ted Kremenek7dba8602007-08-29 21:56:09 +00001425 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426 OS << "\n [ B" << B.getBlockID();
1427
1428 if (&B == &cfg->getEntry())
1429 OS << " (ENTRY) ]\n";
1430 else if (&B == &cfg->getExit())
1431 OS << " (EXIT) ]\n";
1432 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001433 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001434 else
1435 OS << " ]\n";
1436
Ted Kremenek9cffe732007-08-29 23:20:49 +00001437 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001438 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001439
1440 if (print_edges)
1441 OS << " ";
1442
Ted Kremenek411cdee2008-04-16 21:10:48 +00001443 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001444 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001445 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001446 OS << "case ";
1447 C->getLHS()->printPretty(OS);
1448 if (C->getRHS()) {
1449 OS << " ... ";
1450 C->getRHS()->printPretty(OS);
1451 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001452 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001453 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001454 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001455 else
1456 assert(false && "Invalid label statement in CFGBlock.");
1457
Ted Kremenek9cffe732007-08-29 23:20:49 +00001458 OS << ":\n";
1459 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001460
Ted Kremenekfddd5182007-08-21 21:42:03 +00001461 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001462 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001463
1464 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1465 I != E ; ++I, ++j ) {
1466
Ted Kremenek9cffe732007-08-29 23:20:49 +00001467 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001468 if (print_edges)
1469 OS << " ";
1470
Ted Kremeneka95d3752008-09-13 05:16:45 +00001471 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001472
1473 if (Helper)
1474 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001475
1476 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001477 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001478
Ted Kremenek9cffe732007-08-29 23:20:49 +00001479 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001480 if (B.getTerminator()) {
1481 if (print_edges)
1482 OS << " ";
1483
Ted Kremenek9cffe732007-08-29 23:20:49 +00001484 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001485
1486 if (Helper) Helper->setBlockID(-1);
1487
1488 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1489 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001490 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001491 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001492
Ted Kremenek9cffe732007-08-29 23:20:49 +00001493 if (print_edges) {
1494 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001495 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001496 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001497
Ted Kremenek42a509f2007-08-31 21:30:12 +00001498 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1499 I != E; ++I, ++i) {
1500
1501 if (i == 8 || (i-8) == 0)
1502 OS << "\n ";
1503
Ted Kremenek9cffe732007-08-29 23:20:49 +00001504 OS << " B" << (*I)->getBlockID();
1505 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001506
1507 OS << '\n';
1508
1509 // Print the successors of this block.
1510 OS << " Successors (" << B.succ_size() << "):";
1511 i = 0;
1512
1513 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1514 I != E; ++I, ++i) {
1515
1516 if (i == 8 || (i-8) % 10 == 0)
1517 OS << "\n ";
1518
1519 OS << " B" << (*I)->getBlockID();
1520 }
1521
Ted Kremenek9cffe732007-08-29 23:20:49 +00001522 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001523 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001524}
1525
1526} // end anonymous namespace
1527
1528/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001529void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001530
1531/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001532void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001533
1534 StmtPrinterHelper Helper(this);
1535
1536 // Print the entry block.
1537 print_block(OS, this, getEntry(), &Helper, true);
1538
1539 // Iterate through the CFGBlocks and print them one by one.
1540 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1541 // Skip the entry block, because we already printed it.
1542 if (&(*I) == &getEntry() || &(*I) == &getExit())
1543 continue;
1544
1545 print_block(OS, this, *I, &Helper, true);
1546 }
1547
1548 // Print the exit block.
1549 print_block(OS, this, getExit(), &Helper, true);
1550}
1551
1552/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001553void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001554
1555/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1556/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001557void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001558 StmtPrinterHelper Helper(cfg);
1559 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001560}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001561
Ted Kremeneka2925852008-01-30 23:02:42 +00001562/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001563void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001564 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1565 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1566}
1567
Ted Kremenek411cdee2008-04-16 21:10:48 +00001568Expr* CFGBlock::getTerminatorCondition() {
1569
1570 if (!Terminator)
1571 return NULL;
1572
1573 Expr* E = NULL;
1574
1575 switch (Terminator->getStmtClass()) {
1576 default:
1577 break;
1578
1579 case Stmt::ForStmtClass:
1580 E = cast<ForStmt>(Terminator)->getCond();
1581 break;
1582
1583 case Stmt::WhileStmtClass:
1584 E = cast<WhileStmt>(Terminator)->getCond();
1585 break;
1586
1587 case Stmt::DoStmtClass:
1588 E = cast<DoStmt>(Terminator)->getCond();
1589 break;
1590
1591 case Stmt::IfStmtClass:
1592 E = cast<IfStmt>(Terminator)->getCond();
1593 break;
1594
1595 case Stmt::ChooseExprClass:
1596 E = cast<ChooseExpr>(Terminator)->getCond();
1597 break;
1598
1599 case Stmt::IndirectGotoStmtClass:
1600 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1601 break;
1602
1603 case Stmt::SwitchStmtClass:
1604 E = cast<SwitchStmt>(Terminator)->getCond();
1605 break;
1606
1607 case Stmt::ConditionalOperatorClass:
1608 E = cast<ConditionalOperator>(Terminator)->getCond();
1609 break;
1610
1611 case Stmt::BinaryOperatorClass: // '&&' and '||'
1612 E = cast<BinaryOperator>(Terminator)->getLHS();
1613 break;
1614 }
1615
1616 return E ? E->IgnoreParens() : NULL;
1617}
1618
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001619bool CFGBlock::hasBinaryBranchTerminator() const {
1620
1621 if (!Terminator)
1622 return false;
1623
1624 Expr* E = NULL;
1625
1626 switch (Terminator->getStmtClass()) {
1627 default:
1628 return false;
1629
1630 case Stmt::ForStmtClass:
1631 case Stmt::WhileStmtClass:
1632 case Stmt::DoStmtClass:
1633 case Stmt::IfStmtClass:
1634 case Stmt::ChooseExprClass:
1635 case Stmt::ConditionalOperatorClass:
1636 case Stmt::BinaryOperatorClass:
1637 return true;
1638 }
1639
1640 return E ? E->IgnoreParens() : NULL;
1641}
1642
Ted Kremeneka2925852008-01-30 23:02:42 +00001643
Ted Kremenek7dba8602007-08-29 21:56:09 +00001644//===----------------------------------------------------------------------===//
1645// CFG Graphviz Visualization
1646//===----------------------------------------------------------------------===//
1647
Ted Kremenek42a509f2007-08-31 21:30:12 +00001648
1649#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001650static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001651#endif
1652
1653void CFG::viewCFG() const {
1654#ifndef NDEBUG
1655 StmtPrinterHelper H(this);
1656 GraphHelper = &H;
1657 llvm::ViewGraph(this,"CFG");
1658 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001659#endif
1660}
1661
Ted Kremenek7dba8602007-08-29 21:56:09 +00001662namespace llvm {
1663template<>
1664struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1665 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1666
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001667#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001668 std::string OutSStr;
1669 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001670 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001671 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001672
1673 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1674
1675 // Process string output to make it nicer...
1676 for (unsigned i = 0; i != OutStr.length(); ++i)
1677 if (OutStr[i] == '\n') { // Left justify
1678 OutStr[i] = '\\';
1679 OutStr.insert(OutStr.begin()+i+1, 'l');
1680 }
1681
1682 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001683#else
1684 return "";
1685#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001686 }
1687};
1688} // end namespace llvm