blob: c77f8cebda0a45aa435253077ad7ab93698a8346 [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Kremenek97f75312007-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
Ted Kremenekba927fc2009-07-16 18:13:04 +000015#include "clang/Analysis/CFG.h"
Ted Kremenek95e854d2007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenekd058a9c2008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000024#include <llvm/Support/Format.h>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000025
Ted Kremenek97f75312007-08-21 21:42:03 +000026using namespace clang;
27
28namespace {
29
Ted Kremenekd6e50602007-08-23 21:26:19 +000030// SaveAndRestore - A utility class that uses RIIA to save and restore
31// the value of a variable.
32template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000033struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000034 SaveAndRestore(T& x) : X(x), old_value(x) {}
35 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000036 T get() { return old_value; }
37
Ted Kremenekd6e50602007-08-23 21:26:19 +000038 T& X;
39 T old_value;
40};
Ted Kremenek97f75312007-08-21 21:42:03 +000041
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +000042static SourceLocation GetEndLoc(Decl* D) {
Ted Kremenek0865a992008-08-06 23:20:50 +000043 if (VarDecl* VD = dyn_cast<VarDecl>(D))
44 if (Expr* Ex = VD->getInit())
45 return Ex->getSourceRange().getEnd();
46
47 return D->getLocation();
48}
49
Ted Kremeneka3195a32008-08-04 22:51:42 +000050/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek97f75312007-08-21 21:42:03 +000051/// The builder is stateful: an instance of the builder should be used to only
52/// construct a single CFG.
53///
54/// Example usage:
55///
56/// CFGBuilder builder;
57/// CFG* cfg = builder.BuildAST(stmt1);
58///
Ted Kremenek95e854d2007-08-21 22:06:14 +000059/// CFG construction is done via a recursive walk of an AST.
60/// We actually parse the AST in reverse order so that the successor
61/// of a basic block is constructed prior to its predecessor. This
62/// allows us to nicely capture implicit fall-throughs without extra
63/// basic blocks.
64///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000065class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000066 CFG* cfg;
67 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000068 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000069 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000070 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000071 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +000072 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000073
Ted Kremenek0edd3a92007-08-28 19:26:49 +000074 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000075 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
76 LabelMapTy LabelMap;
77
Ted Kremenek0edd3a92007-08-28 19:26:49 +000078 // A list of blocks that end with a "goto" that must be backpatched to
79 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000080 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000081 BackpatchBlocksTy BackpatchBlocks;
82
Ted Kremenek0edd3a92007-08-28 19:26:49 +000083 // A list of labels whose address has been taken (for indirect gotos).
84 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
85 LabelSetTy AddressTakenLabels;
86
Ted Kremenek97f75312007-08-21 21:42:03 +000087public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000088 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000089 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +000090 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000091 // Create an empty CFG.
92 cfg = new CFG();
93 }
94
95 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000096
Ted Kremenek73543912007-08-23 21:42:29 +000097 // buildCFG - Used by external clients to construct the CFG.
98 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000099
Ted Kremenek73543912007-08-23 21:42:29 +0000100 // Visitors to walk an AST and construct the CFG. Called by
101 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +0000102
Ted Kremenek73543912007-08-23 21:42:29 +0000103 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000104 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek05335162008-11-11 17:10:00 +0000105 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
106 CFGBlock* VisitContinueStmt(ContinueStmt* C);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000107 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek05335162008-11-11 17:10:00 +0000108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitForStmt(ForStmt* F);
110 CFGBlock* VisitGotoStmt(GotoStmt* G);
111 CFGBlock* VisitIfStmt(IfStmt* I);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000112 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek05335162008-11-11 17:10:00 +0000113 CFGBlock* VisitLabelStmt(LabelStmt* L);
114 CFGBlock* VisitNullStmt(NullStmt* Statement);
115 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);
116 CFGBlock* VisitReturnStmt(ReturnStmt* R);
117 CFGBlock* VisitStmt(Stmt* Statement);
118 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
119 CFGBlock* VisitWhileStmt(WhileStmt* W);
Mike Stump30376792009-07-17 01:04:31 +0000120
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000121 // FIXME: Add support for ObjC-specific control-flow structures.
Mike Stump30376792009-07-17 01:04:31 +0000122
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000123 // NYS == Not Yet Supported
124 CFGBlock* NYS() {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000125 badCFG = true;
126 return Block;
127 }
128
Ted Kremenek72037962009-03-30 22:29:21 +0000129 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S);
130 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
131 // FIXME: For now we pretend that @catch and the code it contains
132 // does not exit.
133 return Block;
134 }
135
Ted Kremenekc74ac3e2008-12-09 20:20:09 +0000136 // FIXME: This is not completely supported. We basically @throw like
137 // a 'return'.
138 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S);
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000139
Ted Kremenek9b8c9522009-05-02 01:49:13 +0000140 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S);
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000141
Ted Kremenekd68a8d32008-09-26 18:17:07 +0000142 // Blocks.
143 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
144 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
145
Ted Kremenek73543912007-08-23 21:42:29 +0000146private:
147 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000148 CFGBlock* addStmt(Stmt* Terminator);
149 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
150 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000151 CFGBlock* WalkAST_VisitDeclSubExpr(Decl* D);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000152 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000153 bool FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000154
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000155 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000156};
Ted Kremenek09535672008-09-26 22:58:57 +0000157
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000158// FIXME: Add support for dependent-sized array types in C++?
159// Does it even make sense to build a CFG for an uninstantiated template?
Ted Kremenek09535672008-09-26 22:58:57 +0000160static VariableArrayType* FindVA(Type* t) {
161 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
162 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
163 if (vat->getSizeExpr())
164 return vat;
165
166 t = vt->getElementType().getTypePtr();
167 }
168
169 return 0;
170}
Ted Kremenek73543912007-08-23 21:42:29 +0000171
172/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
173/// represent an arbitrary statement. Examples include a single expression
174/// or a function body (compound statement). The ownership of the returned
175/// CFG is transferred to the caller. If CFG construction fails, this method
176/// returns NULL.
177CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000178 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000179 if (!Statement) return NULL;
180
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000181 badCFG = false;
182
Ted Kremenek73543912007-08-23 21:42:29 +0000183 // Create an empty block that will serve as the exit block for the CFG.
184 // Since this is the first block added to the CFG, it will be implicitly
185 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000186 Succ = createBlock();
187 assert (Succ == &cfg->getExit());
188 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000189
190 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000191 CFGBlock* B = Visit(Statement);
192 if (!B) B = Succ;
193
194 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000195 // Finalize the last constructed block. This usually involves
196 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000197 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000198
199 // Backpatch the gotos whose label -> block mappings we didn't know
200 // when we encountered them.
201 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
202 E = BackpatchBlocks.end(); I != E; ++I ) {
203
204 CFGBlock* B = *I;
205 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
206 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
207
208 // If there is no target for the goto, then we are looking at an
209 // incomplete AST. Handle this by not registering a successor.
210 if (LI == LabelMap.end()) continue;
211
212 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000213 }
Ted Kremenek73543912007-08-23 21:42:29 +0000214
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000215 // Add successors to the Indirect Goto Dispatch block (if we have one).
216 if (CFGBlock* B = cfg->getIndirectGotoBlock())
217 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
218 E = AddressTakenLabels.end(); I != E; ++I ) {
219
220 // Lookup the target block.
221 LabelMapTy::iterator LI = LabelMap.find(*I);
222
223 // If there is no target block that contains label, then we are looking
224 // at an incomplete AST. Handle this by not registering a successor.
225 if (LI == LabelMap.end()) continue;
226
227 B->addSuccessor(LI->second);
228 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000229
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000230 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000231 }
232
233 // Create an empty entry block that has no predecessors.
234 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000235
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000236 if (badCFG) {
237 delete cfg;
238 cfg = NULL;
239 return NULL;
240 }
241
Ted Kremenek680fcb82007-09-26 21:23:31 +0000242 // NULL out cfg so that repeated calls to the builder will fail and that
243 // the ownership of the constructed CFG is passed to the caller.
244 CFG* t = cfg;
245 cfg = NULL;
246 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000247}
248
249/// createBlock - Used to lazily create blocks that are connected
250/// to the current (global) succcessor.
251CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000252 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000253 if (add_successor && Succ) B->addSuccessor(Succ);
254 return B;
255}
256
257/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000258/// we must reverse the statements because they have been inserted
259/// in reverse order.
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000260bool CFGBuilder::FinishBlock(CFGBlock* B) {
261 if (badCFG)
262 return false;
263
Ted Kremenek73543912007-08-23 21:42:29 +0000264 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000265 B->reverseStmts();
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000266 return true;
Ted Kremenek73543912007-08-23 21:42:29 +0000267}
268
Ted Kremenek65cfa562007-08-27 21:27:44 +0000269/// addStmt - Used to add statements/expressions to the current CFGBlock
270/// "Block". This method calls WalkAST on the passed statement to see if it
271/// contains any short-circuit expressions. If so, it recursively creates
272/// the necessary blocks for such expressions. It returns the "topmost" block
273/// of the created blocks, or the original value of "Block" when this method
274/// was called if no additional blocks are created.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000275CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000276 if (!Block) Block = createBlock();
Ted Kremenek79f0a632008-04-16 21:10:48 +0000277 return WalkAST(Terminator,true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000278}
279
280/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000281/// add extra blocks for ternary operators, &&, and ||. We also
282/// process "," and DeclStmts (which may contain nested control-flow).
Mike Stump30376792009-07-17 01:04:31 +0000283CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000284 switch (Terminator->getStmtClass()) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000285 case Stmt::ConditionalOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000286 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000287
288 // Create the confluence block that will "merge" the results
289 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000290 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
291 ConfluenceBlock->appendStmt(C);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000292 if (!FinishBlock(ConfluenceBlock))
293 return 0;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000294
295 // Create a block for the LHS expression if there is an LHS expression.
296 // A GCC extension allows LHS to be NULL, causing the condition to
297 // be the value that is returned instead.
298 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000299 Succ = ConfluenceBlock;
300 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000301 CFGBlock* LHSBlock = NULL;
302 if (C->getLHS()) {
303 LHSBlock = Visit(C->getLHS());
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000304 if (!FinishBlock(LHSBlock))
305 return 0;
306 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000307 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000308
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000309 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000310 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000311 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000312 if (!FinishBlock(RHSBlock))
313 return 0;
314
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000315 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000316 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000317
318 if (LHSBlock)
319 Block->addSuccessor(LHSBlock);
320 else {
321 // If we have no LHS expression, add the ConfluenceBlock as a direct
322 // successor for the block containing the condition. Moreover,
323 // we need to reverse the order of the predecessors in the
324 // ConfluenceBlock because the RHSBlock will have been added to
325 // the succcessors already, and we want the first predecessor to the
326 // the block containing the expression for the case when the ternary
327 // expression evaluates to true.
328 Block->addSuccessor(ConfluenceBlock);
329 assert (ConfluenceBlock->pred_size() == 2);
330 std::reverse(ConfluenceBlock->pred_begin(),
331 ConfluenceBlock->pred_end());
332 }
333
Ted Kremenek65cfa562007-08-27 21:27:44 +0000334 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000335
Ted Kremenek65cfa562007-08-27 21:27:44 +0000336 Block->setTerminator(C);
337 return addStmt(C->getCond());
338 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000339
340 case Stmt::ChooseExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000341 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek7f788422007-08-31 17:03:41 +0000342
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000343 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek7f788422007-08-31 17:03:41 +0000344 ConfluenceBlock->appendStmt(C);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000345 if (!FinishBlock(ConfluenceBlock))
346 return 0;
Ted Kremenek7f788422007-08-31 17:03:41 +0000347
348 Succ = ConfluenceBlock;
349 Block = NULL;
350 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000351 if (!FinishBlock(LHSBlock))
352 return 0;
Ted Kremenekd11620d2007-09-11 21:29:43 +0000353
Ted Kremenek7f788422007-08-31 17:03:41 +0000354 Succ = ConfluenceBlock;
355 Block = NULL;
356 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000357 if (!FinishBlock(RHSBlock))
358 return 0;
Ted Kremenek7f788422007-08-31 17:03:41 +0000359
360 Block = createBlock(false);
361 Block->addSuccessor(LHSBlock);
362 Block->addSuccessor(RHSBlock);
363 Block->setTerminator(C);
364 return addStmt(C->getCond());
365 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000366
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000367 case Stmt::DeclStmtClass: {
Ted Kremenekbcc375a2008-10-06 20:56:19 +0000368 DeclStmt *DS = cast<DeclStmt>(Terminator);
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000369 if (DS->isSingleDecl()) {
Ted Kremenek0865a992008-08-06 23:20:50 +0000370 Block->appendStmt(Terminator);
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000371 return WalkAST_VisitDeclSubExpr(DS->getSingleDecl());
Ted Kremenek0865a992008-08-06 23:20:50 +0000372 }
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000373
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000374 CFGBlock* B = 0;
Ted Kremenekbcc375a2008-10-06 20:56:19 +0000375
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000376 // FIXME: Add a reverse iterator for DeclStmt to avoid this
377 // extra copy.
Chris Lattnerffae0dd2009-03-28 06:53:40 +0000378 typedef llvm::SmallVector<Decl*,10> BufTy;
379 BufTy Buf(DS->decl_begin(), DS->decl_end());
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000380
381 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
382 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
383 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
384 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Ted Kremenekbcc375a2008-10-06 20:56:19 +0000385
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000386 // Allocate the DeclStmt using the BumpPtrAllocator. It will
387 // get automatically freed with the CFG.
388 DeclGroupRef DG(*I);
389 Decl* D = *I;
390 void* Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
391
Chris Lattnerffae0dd2009-03-28 06:53:40 +0000392 DeclStmt* DS = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000393
394 // Append the fake DeclStmt to block.
395 Block->appendStmt(DS);
396 B = WalkAST_VisitDeclSubExpr(D);
Ted Kremenek0865a992008-08-06 23:20:50 +0000397 }
Chris Lattner4a9a85e2009-03-28 06:33:19 +0000398 return B;
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000399 }
Ted Kremenek0865a992008-08-06 23:20:50 +0000400
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000401 case Stmt::AddrLabelExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000402 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000403 AddressTakenLabels.insert(A->getLabel());
404
Ted Kremenek79f0a632008-04-16 21:10:48 +0000405 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000406 return Block;
407 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000408
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000409 case Stmt::StmtExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000410 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremeneke822b622007-08-28 18:14:37 +0000411
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000412 case Stmt::SizeOfAlignOfExprClass: {
413 SizeOfAlignOfExpr* E = cast<SizeOfAlignOfExpr>(Terminator);
Ted Kremenek09535672008-09-26 22:58:57 +0000414
415 // VLA types have expressions that must be evaluated.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000416 if (E->isArgumentType()) {
417 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
418 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
419 addStmt(VA->getSizeExpr());
420 }
421 // Expressions in sizeof/alignof are not evaluated and thus have no
422 // control flow.
423 else
424 Block->appendStmt(Terminator);
Ted Kremenek09535672008-09-26 22:58:57 +0000425
426 return Block;
427 }
428
Ted Kremenekcfaae762007-08-27 21:54:41 +0000429 case Stmt::BinaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000430 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000431
432 if (B->isLogicalOp()) { // && or ||
433 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
434 ConfluenceBlock->appendStmt(B);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000435 if (!FinishBlock(ConfluenceBlock))
436 return 0;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000437
438 // create the block evaluating the LHS
439 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000440 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000441
442 // create the block evaluating the RHS
443 Succ = ConfluenceBlock;
444 Block = NULL;
445 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000446 if (!FinishBlock(RHSBlock))
447 return 0;
Ted Kremenekb2348522007-12-21 19:49:00 +0000448
449 // Now link the LHSBlock with RHSBlock.
450 if (B->getOpcode() == BinaryOperator::LOr) {
451 LHSBlock->addSuccessor(ConfluenceBlock);
452 LHSBlock->addSuccessor(RHSBlock);
453 }
454 else {
455 assert (B->getOpcode() == BinaryOperator::LAnd);
456 LHSBlock->addSuccessor(RHSBlock);
457 LHSBlock->addSuccessor(ConfluenceBlock);
458 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000459
460 // Generate the blocks for evaluating the LHS.
461 Block = LHSBlock;
462 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000463 }
464 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
465 Block->appendStmt(B);
466 addStmt(B->getRHS());
467 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000468 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000469
470 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000471 }
Ted Kremenekd68a8d32008-09-26 18:17:07 +0000472
473 // Blocks: No support for blocks ... yet
474 case Stmt::BlockExprClass:
475 case Stmt::BlockDeclRefExprClass:
476 return NYS();
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000477
478 case Stmt::ParenExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000479 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000480
Mike Stump30376792009-07-17 01:04:31 +0000481 case Stmt::CallExprClass: {
482 bool NoReturn = false;
483 CallExpr *C = cast<CallExpr>(Terminator);
484 Expr *CEE = C->getCallee()->IgnoreParenCasts();
485 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
486 // FIXME: We can follow objective-c methods and C++ member functions...
487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
488 if (FD->hasAttr<NoReturnAttr>())
489 NoReturn = true;
490 }
491 }
492
493 if (!NoReturn)
494 break;
495
496 if (Block) {
497 if (!FinishBlock(Block))
498 return 0;
499 }
500
501 // Create new block with no successor for the remaining pieces.
502 Block = createBlock(false);
503 Block->appendStmt(Terminator);
504
505 // Wire this to the exit block directly.
506 Block->addSuccessor(&cfg->getExit());
507
508 return WalkAST_VisitChildren(Terminator);
509 }
510
Ted Kremenek65cfa562007-08-27 21:27:44 +0000511 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000512 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000513 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000514
Ted Kremenek79f0a632008-04-16 21:10:48 +0000515 if (AlwaysAddStmt) Block->appendStmt(Terminator);
516 return WalkAST_VisitChildren(Terminator);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000517}
Ted Kremenekdf8c7d72008-09-26 16:26:36 +0000518
Ted Kremenek0865a992008-08-06 23:20:50 +0000519/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
520/// for initializers in Decls.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000521CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(Decl* D) {
Ted Kremenek0865a992008-08-06 23:20:50 +0000522 VarDecl* VD = dyn_cast<VarDecl>(D);
523
524 if (!VD)
Ted Kremenekf4e35622007-11-18 20:06:01 +0000525 return Block;
526
Ted Kremenek0865a992008-08-06 23:20:50 +0000527 Expr* Init = VD->getInit();
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000528
Ted Kremenekdf8c7d72008-09-26 16:26:36 +0000529 if (Init) {
Mike Stumpd8472f22009-02-26 08:00:25 +0000530 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenekdf8c7d72008-09-26 16:26:36 +0000531 switch (Init->getStmtClass()) {
532 case Stmt::IntegerLiteralClass:
533 case Stmt::CharacterLiteralClass:
534 case Stmt::StringLiteralClass:
535 break;
536 default:
537 Block = addStmt(Init);
538 }
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000539 }
Ted Kremenekdf8c7d72008-09-26 16:26:36 +0000540
541 // If the type of VD is a VLA, then we must process its size expressions.
542 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
543 VA = FindVA(VA->getElementType().getTypePtr()))
544 Block = addStmt(VA->getSizeExpr());
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000545
Ted Kremeneke822b622007-08-28 18:14:37 +0000546 return Block;
547}
548
Ted Kremenek65cfa562007-08-27 21:27:44 +0000549/// WalkAST_VisitChildren - Utility method to call WalkAST on the
550/// children of a Stmt.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000551CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000552 CFGBlock* B = Block;
Mike Stumpd8472f22009-02-26 08:00:25 +0000553 for (Stmt::child_iterator I = Terminator->child_begin(),
554 E = Terminator->child_end();
Ted Kremenek65cfa562007-08-27 21:27:44 +0000555 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000556 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000557
558 return B;
559}
560
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000561/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
562/// expressions (a GCC extension).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000563CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
564 Block->appendStmt(Terminator);
565 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000566}
567
Ted Kremenek73543912007-08-23 21:42:29 +0000568/// VisitStmt - Handle statements with no branching control flow.
569CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
570 // We cannot assume that we are in the middle of a basic block, since
571 // the CFG might only be constructed for this single statement. If
572 // we have no current basic block, just create one lazily.
573 if (!Block) Block = createBlock();
574
575 // Simply add the statement to the current block. We actually
576 // insert statements in reverse order; this order is reversed later
577 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000578 addStmt(Statement);
579
Ted Kremenek73543912007-08-23 21:42:29 +0000580 return Block;
581}
582
583CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
584 return Block;
585}
586
587CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000588
Ted Kremenek1094f4c2009-07-03 00:10:50 +0000589 CFGBlock* LastBlock = Block;
Ted Kremenek73543912007-08-23 21:42:29 +0000590
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000591 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
592 I != E; ++I ) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000593 LastBlock = Visit(*I);
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000594 }
595
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000596 return LastBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000597}
598
599CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
600 // We may see an if statement in the middle of a basic block, or
601 // it may be the first statement we are processing. In either case,
602 // we create a new basic block. First, we create the blocks for
603 // the then...else statements, and then we create the block containing
604 // the if statement. If we were in the middle of a block, we
605 // stop processing that block and reverse its statements. That block
606 // is then the implicit successor for the "then" and "else" clauses.
607
608 // The block we were proccessing is now finished. Make it the
609 // successor block.
610 if (Block) {
611 Succ = Block;
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000612 if (!FinishBlock(Block))
613 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000614 }
615
616 // Process the false branch. NULL out Block so that the recursive
617 // call to Visit will create a new basic block.
618 // Null out Block so that all successor
619 CFGBlock* ElseBlock = Succ;
620
621 if (Stmt* Else = I->getElse()) {
622 SaveAndRestore<CFGBlock*> sv(Succ);
623
624 // NULL out Block so that the recursive call to Visit will
625 // create a new basic block.
626 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000627 ElseBlock = Visit(Else);
628
629 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
630 ElseBlock = sv.get();
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000631 else if (Block) {
632 if (!FinishBlock(ElseBlock))
633 return 0;
634 }
Ted Kremenek73543912007-08-23 21:42:29 +0000635 }
636
637 // Process the true branch. NULL out Block so that the recursive
638 // call to Visit will create a new basic block.
639 // Null out Block so that all successor
640 CFGBlock* ThenBlock;
641 {
642 Stmt* Then = I->getThen();
643 assert (Then);
644 SaveAndRestore<CFGBlock*> sv(Succ);
645 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000646 ThenBlock = Visit(Then);
647
Ted Kremeneke5a3c022009-04-01 03:52:47 +0000648 if (!ThenBlock) {
649 // We can reach here if the "then" body has all NullStmts.
650 // Create an empty block so we can distinguish between true and false
651 // branches in path-sensitive analyses.
652 ThenBlock = createBlock(false);
653 ThenBlock->addSuccessor(sv.get());
654 }
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000655 else if (Block) {
656 if (!FinishBlock(ThenBlock))
657 return 0;
658 }
Ted Kremenek73543912007-08-23 21:42:29 +0000659 }
660
661 // Now create a new block containing the if statement.
662 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000663
664 // Set the terminator of the new block to the If statement.
665 Block->setTerminator(I);
666
667 // Now add the successors.
668 Block->addSuccessor(ThenBlock);
669 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000670
671 // Add the condition as the last statement in the new block. This
672 // may create new blocks as the condition may contain control-flow. Any
673 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000674 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000675}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000676
Ted Kremenek73543912007-08-23 21:42:29 +0000677
678CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
679 // If we were in the middle of a block we stop processing that block
680 // and reverse its statements.
681 //
682 // NOTE: If a "return" appears in the middle of a block, this means
683 // that the code afterwards is DEAD (unreachable). We still
684 // keep a basic block for that code; a simple "mark-and-sweep"
685 // from the entry block will be able to report such dead
686 // blocks.
687 if (Block) FinishBlock(Block);
688
689 // Create the new block.
690 Block = createBlock(false);
691
692 // The Exit block is the only successor.
693 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000694
695 // Add the return statement to the block. This may create new blocks
696 // if R contains control-flow (short-circuit operations).
697 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000698}
699
700CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
701 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek82e8a192008-03-15 07:45:02 +0000702 Visit(L->getSubStmt());
703 CFGBlock* LabelBlock = Block;
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000704
705 if (!LabelBlock) // This can happen when the body is empty, i.e.
706 LabelBlock=createBlock(); // scopes that only contains NullStmts.
707
Ted Kremenek73543912007-08-23 21:42:29 +0000708 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
709 LabelMap[ L ] = LabelBlock;
710
711 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000712 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000713 // label (and we have already processed the substatement) there is no
714 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000715 LabelBlock->setLabel(L);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000716 if (!FinishBlock(LabelBlock))
717 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000718
719 // We set Block to NULL to allow lazy creation of a new block
720 // (if necessary);
721 Block = NULL;
722
723 // This block is now the implicit successor of other blocks.
724 Succ = LabelBlock;
725
726 return LabelBlock;
727}
728
729CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
730 // Goto is a control-flow statement. Thus we stop processing the
731 // current block and create a new one.
732 if (Block) FinishBlock(Block);
733 Block = createBlock(false);
734 Block->setTerminator(G);
735
736 // If we already know the mapping to the label block add the
737 // successor now.
738 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
739
740 if (I == LabelMap.end())
741 // We will need to backpatch this block later.
742 BackpatchBlocks.push_back(Block);
743 else
744 Block->addSuccessor(I->second);
745
746 return Block;
747}
748
749CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
750 // "for" is a control-flow statement. Thus we stop processing the
751 // current block.
752
753 CFGBlock* LoopSuccessor = NULL;
754
755 if (Block) {
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000756 if (!FinishBlock(Block))
757 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000758 LoopSuccessor = Block;
759 }
760 else LoopSuccessor = Succ;
761
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000762 // Because of short-circuit evaluation, the condition of the loop
763 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
764 // blocks that evaluate the condition.
765 CFGBlock* ExitConditionBlock = createBlock(false);
766 CFGBlock* EntryConditionBlock = ExitConditionBlock;
767
768 // Set the terminator for the "exit" condition block.
769 ExitConditionBlock->setTerminator(F);
770
771 // Now add the actual condition to the condition block. Because the
772 // condition itself may contain control-flow, new blocks may be created.
773 if (Stmt* C = F->getCond()) {
774 Block = ExitConditionBlock;
775 EntryConditionBlock = addStmt(C);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000776 if (Block) {
777 if (!FinishBlock(EntryConditionBlock))
778 return 0;
779 }
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000780 }
Ted Kremenek73543912007-08-23 21:42:29 +0000781
782 // The condition block is the implicit successor for the loop body as
783 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000784 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000785
786 // Now create the loop body.
787 {
788 assert (F->getBody());
789
790 // Save the current values for Block, Succ, and continue and break targets
791 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
792 save_continue(ContinueTargetBlock),
793 save_break(BreakTargetBlock);
Ted Kremenek77f93372008-09-04 21:48:47 +0000794
Ted Kremenek390b9762007-08-30 18:39:40 +0000795 // Create a new block to contain the (bottom) of the loop body.
796 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000797
Ted Kremenek77f93372008-09-04 21:48:47 +0000798 if (Stmt* I = F->getInc()) {
799 // Generate increment code in its own basic block. This is the target
800 // of continue statements.
Ted Kremenekd19e99e2008-11-24 20:50:24 +0000801 Succ = Visit(I);
Ted Kremenek77f93372008-09-04 21:48:47 +0000802 }
803 else {
Ted Kremenekca7cdcf2009-04-28 00:51:56 +0000804 // No increment code. Create a special, empty, block that is used as
805 // the target block for "looping back" to the start of the loop.
806 assert(Succ == EntryConditionBlock);
807 Succ = createBlock();
Ted Kremenek77f93372008-09-04 21:48:47 +0000808 }
809
Ted Kremenekca7cdcf2009-04-28 00:51:56 +0000810 // Finish up the increment (or empty) block if it hasn't been already.
811 if (Block) {
812 assert(Block == Succ);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000813 if (!FinishBlock(Block))
814 return 0;
Ted Kremenekca7cdcf2009-04-28 00:51:56 +0000815 Block = 0;
816 }
817
818 ContinueTargetBlock = Succ;
819
820 // The starting block for the loop increment is the block that should
821 // represent the 'loop target' for looping back to the start of the loop.
822 ContinueTargetBlock->setLoopTarget(F);
823
Ted Kremenek77f93372008-09-04 21:48:47 +0000824 // All breaks should go to the code following the loop.
825 BreakTargetBlock = LoopSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000826
827 // Now populate the body block, and in the process create new blocks
828 // as we walk the body of the loop.
829 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000830
831 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000832 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000833 else if (Block) {
834 if (!FinishBlock(BodyBlock))
835 return 0;
836 }
Ted Kremenek73543912007-08-23 21:42:29 +0000837
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000838 // This new body block is a successor to our "exit" condition block.
839 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000840 }
841
842 // Link up the condition block with the code that follows the loop.
843 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000844 ExitConditionBlock->addSuccessor(LoopSuccessor);
845
Ted Kremenek73543912007-08-23 21:42:29 +0000846 // If the loop contains initialization, create a new block for those
847 // statements. This block can also contain statements that precede
848 // the loop.
849 if (Stmt* I = F->getInit()) {
850 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000851 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000852 }
853 else {
854 // There is no loop initialization. We are thus basically a while
855 // loop. NULL out Block to force lazy block construction.
856 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000857 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000858 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000859 }
860}
861
Ted Kremenek05335162008-11-11 17:10:00 +0000862CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
863 // Objective-C fast enumeration 'for' statements:
864 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
865 //
866 // for ( Type newVariable in collection_expression ) { statements }
867 //
868 // becomes:
869 //
870 // prologue:
871 // 1. collection_expression
872 // T. jump to loop_entry
873 // loop_entry:
Ted Kremenek65514842008-11-14 01:57:41 +0000874 // 1. side-effects of element expression
Ted Kremenek05335162008-11-11 17:10:00 +0000875 // 1. ObjCForCollectionStmt [performs binding to newVariable]
876 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
877 // TB:
878 // statements
879 // T. jump to loop_entry
880 // FB:
881 // what comes after
882 //
883 // and
884 //
885 // Type existingItem;
886 // for ( existingItem in expression ) { statements }
887 //
888 // becomes:
889 //
890 // the same with newVariable replaced with existingItem; the binding
891 // works the same except that for one ObjCForCollectionStmt::getElement()
892 // returns a DeclStmt and the other returns a DeclRefExpr.
893 //
894
895 CFGBlock* LoopSuccessor = 0;
896
897 if (Block) {
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000898 if (!FinishBlock(Block))
899 return 0;
Ted Kremenek05335162008-11-11 17:10:00 +0000900 LoopSuccessor = Block;
901 Block = 0;
902 }
903 else LoopSuccessor = Succ;
904
Ted Kremenek65514842008-11-14 01:57:41 +0000905 // Build the condition blocks.
906 CFGBlock* ExitConditionBlock = createBlock(false);
907 CFGBlock* EntryConditionBlock = ExitConditionBlock;
908
909 // Set the terminator for the "exit" condition block.
910 ExitConditionBlock->setTerminator(S);
911
912 // The last statement in the block should be the ObjCForCollectionStmt,
913 // which performs the actual binding to 'element' and determines if there
914 // are any more items in the collection.
915 ExitConditionBlock->appendStmt(S);
916 Block = ExitConditionBlock;
917
918 // Walk the 'element' expression to see if there are any side-effects. We
919 // generate new blocks as necesary. We DON'T add the statement by default
920 // to the CFG unless it contains control-flow.
921 EntryConditionBlock = WalkAST(S->getElement(), false);
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000922 if (Block) {
923 if (!FinishBlock(EntryConditionBlock))
924 return 0;
925 Block = 0;
926 }
Ted Kremenek65514842008-11-14 01:57:41 +0000927
928 // The condition block is the implicit successor for the loop body as
929 // well as any code above the loop.
930 Succ = EntryConditionBlock;
Ted Kremenek05335162008-11-11 17:10:00 +0000931
932 // Now create the true branch.
Ted Kremenek65514842008-11-14 01:57:41 +0000933 {
934 // Save the current values for Succ, continue and break targets.
935 SaveAndRestore<CFGBlock*> save_Succ(Succ),
936 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
937
938 BreakTargetBlock = LoopSuccessor;
939 ContinueTargetBlock = EntryConditionBlock;
940
941 CFGBlock* BodyBlock = Visit(S->getBody());
942
943 if (!BodyBlock)
944 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000945 else if (Block) {
946 if (!FinishBlock(BodyBlock))
947 return 0;
948 }
Ted Kremenek65514842008-11-14 01:57:41 +0000949
950 // This new body block is a successor to our "exit" condition block.
951 ExitConditionBlock->addSuccessor(BodyBlock);
952 }
Ted Kremenekf5383072008-11-13 06:36:45 +0000953
Ted Kremenek65514842008-11-14 01:57:41 +0000954 // Link up the condition block with the code that follows the loop.
955 // (the false branch).
956 ExitConditionBlock->addSuccessor(LoopSuccessor);
957
Ted Kremenek05335162008-11-11 17:10:00 +0000958 // Now create a prologue block to contain the collection expression.
Ted Kremenek65514842008-11-14 01:57:41 +0000959 Block = createBlock();
Ted Kremenek05335162008-11-11 17:10:00 +0000960 return addStmt(S->getCollection());
961}
Ted Kremenek72037962009-03-30 22:29:21 +0000962
Ted Kremenek9b8c9522009-05-02 01:49:13 +0000963CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
964 // FIXME: Add locking 'primitives' to CFG for @synchronized.
965
966 // Inline the body.
Ted Kremenekd23abca2009-05-05 23:11:51 +0000967 CFGBlock *SyncBlock = Visit(S->getSynchBody());
968
969 // The sync body starts its own basic block. This makes it a little easier
970 // for diagnostic clients.
971 if (SyncBlock) {
972 if (!FinishBlock(SyncBlock))
973 return 0;
974
975 Block = 0;
976 }
977
978 Succ = SyncBlock;
Ted Kremenek9b8c9522009-05-02 01:49:13 +0000979
980 // Inline the sync expression.
981 return Visit(S->getSynchExpr());
982}
983
Ted Kremenek72037962009-03-30 22:29:21 +0000984CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
Ted Kremenek417d4692009-04-07 04:26:02 +0000985 return NYS();
Ted Kremenek72037962009-03-30 22:29:21 +0000986}
Ted Kremenek05335162008-11-11 17:10:00 +0000987
Ted Kremenek73543912007-08-23 21:42:29 +0000988CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
989 // "while" is a control-flow statement. Thus we stop processing the
990 // current block.
991
992 CFGBlock* LoopSuccessor = NULL;
993
994 if (Block) {
Ted Kremenek2504e8b2009-05-02 00:13:27 +0000995 if (!FinishBlock(Block))
996 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000997 LoopSuccessor = Block;
998 }
999 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001000
1001 // Because of short-circuit evaluation, the condition of the loop
1002 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
1003 // blocks that evaluate the condition.
1004 CFGBlock* ExitConditionBlock = createBlock(false);
1005 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1006
1007 // Set the terminator for the "exit" condition block.
1008 ExitConditionBlock->setTerminator(W);
1009
1010 // Now add the actual condition to the condition block. Because the
1011 // condition itself may contain control-flow, new blocks may be created.
1012 // Thus we update "Succ" after adding the condition.
1013 if (Stmt* C = W->getCond()) {
1014 Block = ExitConditionBlock;
1015 EntryConditionBlock = addStmt(C);
Ted Kremenek64f918f2009-04-28 03:09:44 +00001016 assert(Block == EntryConditionBlock);
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001017 if (Block) {
1018 if (!FinishBlock(EntryConditionBlock))
1019 return 0;
1020 }
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001021 }
Ted Kremenek73543912007-08-23 21:42:29 +00001022
1023 // The condition block is the implicit successor for the loop body as
1024 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001025 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001026
1027 // Process the loop body.
1028 {
Ted Kremenek64f918f2009-04-28 03:09:44 +00001029 assert(W->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +00001030
1031 // Save the current values for Block, Succ, and continue and break targets
1032 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1033 save_continue(ContinueTargetBlock),
1034 save_break(BreakTargetBlock);
Ted Kremenek64f918f2009-04-28 03:09:44 +00001035
1036 // Create an empty block to represent the transition block for looping
1037 // back to the head of the loop.
1038 Block = 0;
1039 assert(Succ == EntryConditionBlock);
1040 Succ = createBlock();
1041 Succ->setLoopTarget(W);
1042 ContinueTargetBlock = Succ;
Ted Kremenek73543912007-08-23 21:42:29 +00001043
1044 // All breaks should go to the code following the loop.
1045 BreakTargetBlock = LoopSuccessor;
1046
1047 // NULL out Block to force lazy instantiation of blocks for the body.
1048 Block = NULL;
1049
1050 // Create the body. The returned block is the entry to the loop body.
1051 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +00001052
1053 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +00001054 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001055 else if (Block) {
1056 if (!FinishBlock(BodyBlock))
1057 return 0;
1058 }
Ted Kremenek73543912007-08-23 21:42:29 +00001059
1060 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001061 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +00001062 }
1063
1064 // Link up the condition block with the code that follows the loop.
1065 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001066 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +00001067
1068 // There can be no more statements in the condition block
1069 // since we loop back to this block. NULL out Block to force
1070 // lazy creation of another block.
1071 Block = NULL;
1072
1073 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +00001074 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001075 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001076}
Ted Kremenekc74ac3e2008-12-09 20:20:09 +00001077
1078CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1079 // FIXME: This isn't complete. We basically treat @throw like a return
1080 // statement.
1081
1082 // If we were in the middle of a block we stop processing that block
1083 // and reverse its statements.
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001084 if (Block) {
1085 if (!FinishBlock(Block))
1086 return 0;
1087 }
Ted Kremenekc74ac3e2008-12-09 20:20:09 +00001088
1089 // Create the new block.
1090 Block = createBlock(false);
1091
1092 // The Exit block is the only successor.
1093 Block->addSuccessor(&cfg->getExit());
1094
1095 // Add the statement to the block. This may create new blocks
1096 // if S contains control-flow (short-circuit operations).
1097 return addStmt(S);
1098}
Ted Kremenek73543912007-08-23 21:42:29 +00001099
1100CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
1101 // "do...while" is a control-flow statement. Thus we stop processing the
1102 // current block.
1103
1104 CFGBlock* LoopSuccessor = NULL;
1105
1106 if (Block) {
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001107 if (!FinishBlock(Block))
1108 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +00001109 LoopSuccessor = Block;
1110 }
1111 else LoopSuccessor = Succ;
1112
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001113 // Because of short-circuit evaluation, the condition of the loop
1114 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
1115 // blocks that evaluate the condition.
1116 CFGBlock* ExitConditionBlock = createBlock(false);
1117 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1118
1119 // Set the terminator for the "exit" condition block.
1120 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +00001121
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001122 // Now add the actual condition to the condition block. Because the
1123 // condition itself may contain control-flow, new blocks may be created.
1124 if (Stmt* C = D->getCond()) {
1125 Block = ExitConditionBlock;
1126 EntryConditionBlock = addStmt(C);
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001127 if (Block) {
1128 if (!FinishBlock(EntryConditionBlock))
1129 return 0;
1130 }
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001131 }
Ted Kremenek73543912007-08-23 21:42:29 +00001132
Ted Kremenek9ff572c2008-02-27 07:20:00 +00001133 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001134 Succ = EntryConditionBlock;
1135
Ted Kremenek73543912007-08-23 21:42:29 +00001136 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001137 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +00001138 {
1139 assert (D->getBody());
1140
1141 // Save the current values for Block, Succ, and continue and break targets
1142 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1143 save_continue(ContinueTargetBlock),
1144 save_break(BreakTargetBlock);
1145
1146 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001147 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001148
1149 // All breaks should go to the code following the loop.
1150 BreakTargetBlock = LoopSuccessor;
1151
1152 // NULL out Block to force lazy instantiation of blocks for the body.
1153 Block = NULL;
1154
1155 // Create the body. The returned block is the entry to the loop body.
1156 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +00001157
Ted Kremenek390b9762007-08-30 18:39:40 +00001158 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +00001159 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001160 else if (Block) {
1161 if (!FinishBlock(BodyBlock))
1162 return 0;
1163 }
Ted Kremenek390b9762007-08-30 18:39:40 +00001164
Ted Kremenek1b697ca2009-04-28 04:22:00 +00001165 // Add an intermediate block between the BodyBlock and the
1166 // ExitConditionBlock to represent the "loop back" transition.
1167 // Create an empty block to represent the transition block for looping
1168 // back to the head of the loop.
1169 // FIXME: Can we do this more efficiently without adding another block?
1170 Block = NULL;
1171 Succ = BodyBlock;
1172 CFGBlock *LoopBackBlock = createBlock();
1173 LoopBackBlock->setLoopTarget(D);
1174
Ted Kremenek73543912007-08-23 21:42:29 +00001175 // Add the loop body entry as a successor to the condition.
Ted Kremenek1b697ca2009-04-28 04:22:00 +00001176 ExitConditionBlock->addSuccessor(LoopBackBlock);
Ted Kremenek73543912007-08-23 21:42:29 +00001177 }
1178
1179 // Link up the condition block with the code that follows the loop.
1180 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001181 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +00001182
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001183 // There can be no more statements in the body block(s)
1184 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +00001185 // lazy creation of another block.
1186 Block = NULL;
1187
1188 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +00001189 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001190 return BodyBlock;
1191}
1192
1193CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1194 // "continue" is a control-flow statement. Thus we stop processing the
1195 // current block.
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001196 if (Block) {
1197 if (!FinishBlock(Block))
1198 return 0;
1199 }
Ted Kremenek73543912007-08-23 21:42:29 +00001200
1201 // Now create a new block that ends with the continue statement.
1202 Block = createBlock(false);
1203 Block->setTerminator(C);
1204
1205 // If there is no target for the continue, then we are looking at an
Ted Kremenek819b7c02009-04-07 18:53:24 +00001206 // incomplete AST. This means the CFG cannot be constructed.
1207 if (ContinueTargetBlock)
1208 Block->addSuccessor(ContinueTargetBlock);
1209 else
1210 badCFG = true;
Ted Kremenek73543912007-08-23 21:42:29 +00001211
1212 return Block;
1213}
1214
1215CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
1216 // "break" is a control-flow statement. Thus we stop processing the
1217 // current block.
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001218 if (Block) {
1219 if (!FinishBlock(Block))
1220 return 0;
1221 }
Ted Kremenek73543912007-08-23 21:42:29 +00001222
Mike Stump30376792009-07-17 01:04:31 +00001223 // Now create a new block that ends with the break statement.
Ted Kremenek73543912007-08-23 21:42:29 +00001224 Block = createBlock(false);
1225 Block->setTerminator(B);
1226
1227 // If there is no target for the break, then we are looking at an
Ted Kremenek819b7c02009-04-07 18:53:24 +00001228 // incomplete AST. This means that the CFG cannot be constructed.
1229 if (BreakTargetBlock)
1230 Block->addSuccessor(BreakTargetBlock);
1231 else
1232 badCFG = true;
1233
Ted Kremenek73543912007-08-23 21:42:29 +00001234
1235 return Block;
1236}
1237
Ted Kremenek79f0a632008-04-16 21:10:48 +00001238CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek73543912007-08-23 21:42:29 +00001239 // "switch" is a control-flow statement. Thus we stop processing the
1240 // current block.
1241 CFGBlock* SwitchSuccessor = NULL;
1242
1243 if (Block) {
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001244 if (!FinishBlock(Block))
1245 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +00001246 SwitchSuccessor = Block;
1247 }
1248 else SwitchSuccessor = Succ;
1249
1250 // Save the current "switch" context.
1251 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +00001252 save_break(BreakTargetBlock),
1253 save_default(DefaultCaseBlock);
1254
1255 // Set the "default" case to be the block after the switch statement.
1256 // If the switch statement contains a "default:", this value will
1257 // be overwritten with the block for that code.
1258 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001259
Ted Kremenek73543912007-08-23 21:42:29 +00001260 // Create a new block that will contain the switch statement.
1261 SwitchTerminatedBlock = createBlock(false);
1262
Ted Kremenek73543912007-08-23 21:42:29 +00001263 // Now process the switch body. The code after the switch is the implicit
1264 // successor.
1265 Succ = SwitchSuccessor;
1266 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +00001267
1268 // When visiting the body, the case statements should automatically get
1269 // linked up to the switch. We also don't keep a pointer to the body,
1270 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001271 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001272 Block = NULL;
Ted Kremenek79f0a632008-04-16 21:10:48 +00001273 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001274 if (Block) {
1275 if (!FinishBlock(BodyBlock))
1276 return 0;
1277 }
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001278
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001279 // If we have no "default:" case, the default transition is to the
1280 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +00001281 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001282
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001283 // Add the terminator and condition in the switch block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001284 SwitchTerminatedBlock->setTerminator(Terminator);
1285 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +00001286 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001287
Ted Kremenek79f0a632008-04-16 21:10:48 +00001288 return addStmt(Terminator->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +00001289}
1290
Ted Kremenek79f0a632008-04-16 21:10:48 +00001291CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenek97bc3422008-02-13 22:05:39 +00001292 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +00001293 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +00001294
Ted Kremenek79f0a632008-04-16 21:10:48 +00001295 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek44659d82007-08-30 18:48:11 +00001296 CFGBlock* CaseBlock = Block;
1297 if (!CaseBlock) CaseBlock = createBlock();
1298
Ted Kremenek97bc3422008-02-13 22:05:39 +00001299 // Cases statements partition blocks, so this is the top of
1300 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001301 CaseBlock->setLabel(Terminator);
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001302 if (!FinishBlock(CaseBlock))
1303 return 0;
Ted Kremenek73543912007-08-23 21:42:29 +00001304
1305 // Add this block to the list of successors for the block with the
1306 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +00001307 assert (SwitchTerminatedBlock);
1308 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +00001309
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 = CaseBlock;
1315
Ted Kremenek82e8a192008-03-15 07:45:02 +00001316 return CaseBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001317}
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001318
Ted Kremenek79f0a632008-04-16 21:10:48 +00001319CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1320 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek97bc3422008-02-13 22:05:39 +00001321 DefaultCaseBlock = Block;
1322 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1323
1324 // Default statements partition blocks, so this is the top of
1325 // the basic block we were processing (the "default:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001326 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001327 if (!FinishBlock(DefaultCaseBlock))
1328 return 0;
Ted Kremenek97bc3422008-02-13 22:05:39 +00001329
1330 // Unlike case statements, we don't add the default block to the
1331 // successors for the switch statement immediately. This is done
1332 // when we finish processing the switch statement. This allows for
1333 // the default case (including a fall-through to the code after the
1334 // switch statement) to always be the last successor of a switch-terminated
1335 // block.
1336
1337 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1338 Block = NULL;
1339
1340 // This block is now the implicit successor of other blocks.
1341 Succ = DefaultCaseBlock;
1342
1343 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001344}
Ted Kremenek73543912007-08-23 21:42:29 +00001345
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001346CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1347 // Lazily create the indirect-goto dispatch block if there isn't one
1348 // already.
1349 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1350
1351 if (!IBlock) {
1352 IBlock = createBlock(false);
1353 cfg->setIndirectGotoBlock(IBlock);
1354 }
1355
1356 // IndirectGoto is a control-flow statement. Thus we stop processing the
1357 // current block and create a new one.
Ted Kremenek2504e8b2009-05-02 00:13:27 +00001358 if (Block) {
1359 if (!FinishBlock(Block))
1360 return 0;
1361 }
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001362 Block = createBlock(false);
1363 Block->setTerminator(I);
1364 Block->addSuccessor(IBlock);
1365 return addStmt(I->getTarget());
1366}
1367
Ted Kremenek73543912007-08-23 21:42:29 +00001368
Ted Kremenekd6e50602007-08-23 21:26:19 +00001369} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001370
1371/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1372/// block has no successors or predecessors. If this is the first block
1373/// created in the CFG, it is automatically set to be the Entry and Exit
1374/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001375CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001376 bool first_block = begin() == end();
1377
1378 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001379 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001380
1381 // If this is the first block, set it as the Entry and Exit.
1382 if (first_block) Entry = Exit = &front();
1383
1384 // Return the block.
1385 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001386}
1387
Ted Kremenek4db5b452007-08-23 16:51:22 +00001388/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1389/// CFG is returned to the caller.
1390CFG* CFG::buildCFG(Stmt* Statement) {
1391 CFGBuilder Builder;
1392 return Builder.buildCFG(Statement);
1393}
1394
1395/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001396void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1397
Ted Kremenek3a819822007-10-01 19:33:33 +00001398//===----------------------------------------------------------------------===//
1399// CFG: Queries for BlkExprs.
1400//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001401
Ted Kremenek3a819822007-10-01 19:33:33 +00001402namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001403 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001404}
1405
Ted Kremenek79f0a632008-04-16 21:10:48 +00001406static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1407 if (!Terminator)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001408 return;
1409
Ted Kremenek79f0a632008-04-16 21:10:48 +00001410 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001411 if (!*I) continue;
1412
1413 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1414 if (B->isAssignmentOp()) Set.insert(B);
1415
1416 FindSubExprAssignments(*I, Set);
1417 }
1418}
1419
Ted Kremenek3a819822007-10-01 19:33:33 +00001420static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1421 BlkExprMapTy* M = new BlkExprMapTy();
1422
Ted Kremenekc6fda602008-01-26 00:03:27 +00001423 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek79f0a632008-04-16 21:10:48 +00001424 // only assignments that we want to *possibly* register as a block-level
1425 // expression. Basically, if an assignment occurs both in a subexpression
1426 // and at the block-level, it is a block-level expression.
Ted Kremenekc6fda602008-01-26 00:03:27 +00001427 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1428
Ted Kremenek3a819822007-10-01 19:33:33 +00001429 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1430 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001431 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001432
Ted Kremenek79f0a632008-04-16 21:10:48 +00001433 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1434
1435 // Iterate over the statements again on identify the Expr* and Stmt* at
1436 // the block-level that are block-level expressions.
1437
Ted Kremenekc6fda602008-01-26 00:03:27 +00001438 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek79f0a632008-04-16 21:10:48 +00001439 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001440
Ted Kremenek79f0a632008-04-16 21:10:48 +00001441 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001442 // Assignment expressions that are not nested within another
1443 // expression are really "statements" whose value is never
1444 // used by another expression.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001445 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenekc6fda602008-01-26 00:03:27 +00001446 continue;
1447 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001448 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001449 // Special handling for statement expressions. The last statement
1450 // in the statement expression is also a block-level expr.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001451 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001452 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001453 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001454 (*M)[C->body_back()] = x;
1455 }
1456 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001457
Ted Kremenekc6fda602008-01-26 00:03:27 +00001458 unsigned x = M->size();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001459 (*M)[Exp] = x;
Ted Kremenekc6fda602008-01-26 00:03:27 +00001460 }
1461
Ted Kremenek79f0a632008-04-16 21:10:48 +00001462 // Look at terminators. The condition is a block-level expression.
1463
Ted Kremenek16516e22008-11-12 21:11:49 +00001464 Stmt* S = I->getTerminatorCondition();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001465
Ted Kremenek16516e22008-11-12 21:11:49 +00001466 if (S && M->find(S) == M->end()) {
Ted Kremenek79f0a632008-04-16 21:10:48 +00001467 unsigned x = M->size();
Ted Kremenek16516e22008-11-12 21:11:49 +00001468 (*M)[S] = x;
Ted Kremenek79f0a632008-04-16 21:10:48 +00001469 }
1470 }
1471
Ted Kremenek3a819822007-10-01 19:33:33 +00001472 return M;
1473}
1474
Ted Kremenekab6c5902008-01-17 20:48:37 +00001475CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1476 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001477 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1478
1479 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001480 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001481
1482 if (I == M->end()) return CFG::BlkExprNumTy();
1483 else return CFG::BlkExprNumTy(I->second);
1484}
1485
1486unsigned CFG::getNumBlkExprs() {
1487 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1488 return M->size();
1489 else {
1490 // We assume callers interested in the number of BlkExprs will want
1491 // the map constructed if it doesn't already exist.
1492 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1493 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1494 }
1495}
1496
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001497//===----------------------------------------------------------------------===//
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001498// Cleanup: CFG dstor.
1499//===----------------------------------------------------------------------===//
1500
Ted Kremenek3a819822007-10-01 19:33:33 +00001501CFG::~CFG() {
1502 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1503}
1504
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001505//===----------------------------------------------------------------------===//
1506// CFG pretty printing
1507//===----------------------------------------------------------------------===//
1508
Ted Kremenekd8313202007-08-22 18:22:34 +00001509namespace {
1510
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001511class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001512
Ted Kremenek08176a52007-08-31 21:30:12 +00001513 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1514 StmtMapTy StmtMap;
1515 signed CurrentBlock;
1516 unsigned CurrentStmt;
Chris Lattner7099c782009-06-30 01:26:17 +00001517 const LangOptions &LangOpts;
Ted Kremenek73543912007-08-23 21:42:29 +00001518public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001519
Chris Lattner7099c782009-06-30 01:26:17 +00001520 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1521 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001522 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1523 unsigned j = 1;
1524 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1525 BI != BEnd; ++BI, ++j )
1526 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1527 }
1528 }
1529
1530 virtual ~StmtPrinterHelper() {}
1531
Chris Lattner7099c782009-06-30 01:26:17 +00001532 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek08176a52007-08-31 21:30:12 +00001533 void setBlockID(signed i) { CurrentBlock = i; }
1534 void setStmtID(unsigned i) { CurrentStmt = i; }
1535
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001536 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001537
Ted Kremenek79f0a632008-04-16 21:10:48 +00001538 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek08176a52007-08-31 21:30:12 +00001539
1540 if (I == StmtMap.end())
1541 return false;
1542
1543 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1544 && I->second.second == CurrentStmt)
1545 return false;
1546
Ted Kremenek86afc042007-08-31 22:26:13 +00001547 OS << "[B" << I->second.first << "." << I->second.second << "]";
1548 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001549 }
1550};
Chris Lattner7099c782009-06-30 01:26:17 +00001551} // end anonymous namespace
Ted Kremenek08176a52007-08-31 21:30:12 +00001552
Chris Lattner7099c782009-06-30 01:26:17 +00001553
1554namespace {
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001555class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1556 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1557
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001558 llvm::raw_ostream& OS;
Ted Kremenek08176a52007-08-31 21:30:12 +00001559 StmtPrinterHelper* Helper;
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001560 PrintingPolicy Policy;
1561
Ted Kremenek08176a52007-08-31 21:30:12 +00001562public:
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001563 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
Chris Lattner7099c782009-06-30 01:26:17 +00001564 const PrintingPolicy &Policy)
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001565 : OS(os), Helper(helper), Policy(Policy) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001566
1567 void VisitIfStmt(IfStmt* I) {
1568 OS << "if ";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001569 I->getCond()->printPretty(OS,Helper,Policy);
Ted Kremenek73543912007-08-23 21:42:29 +00001570 }
1571
1572 // Default case.
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001573 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS, Helper, Policy); }
Ted Kremenek73543912007-08-23 21:42:29 +00001574
1575 void VisitForStmt(ForStmt* F) {
1576 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001577 if (F->getInit()) OS << "...";
1578 OS << "; ";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001579 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001580 OS << "; ";
1581 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001582 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001583 }
1584
1585 void VisitWhileStmt(WhileStmt* W) {
1586 OS << "while " ;
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001587 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek73543912007-08-23 21:42:29 +00001588 }
1589
1590 void VisitDoStmt(DoStmt* D) {
1591 OS << "do ... while ";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001592 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001593 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001594
Ted Kremenek79f0a632008-04-16 21:10:48 +00001595 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +00001596 OS << "switch ";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001597 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001598 }
1599
Ted Kremenek621e1592007-08-31 21:49:40 +00001600 void VisitConditionalOperator(ConditionalOperator* C) {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001601 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001602 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001603 }
1604
Ted Kremenek2025cc92007-08-31 22:29:13 +00001605 void VisitChooseExpr(ChooseExpr* C) {
1606 OS << "__builtin_choose_expr( ";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001607 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001608 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001609 }
1610
Ted Kremenek86afc042007-08-31 22:26:13 +00001611 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1612 OS << "goto *";
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001613 I->getTarget()->printPretty(OS, Helper, Policy);
Ted Kremenek86afc042007-08-31 22:26:13 +00001614 }
1615
Ted Kremenek621e1592007-08-31 21:49:40 +00001616 void VisitBinaryOperator(BinaryOperator* B) {
1617 if (!B->isLogicalOp()) {
1618 VisitExpr(B);
1619 return;
1620 }
1621
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001622 B->getLHS()->printPretty(OS, Helper, Policy);
Ted Kremenek621e1592007-08-31 21:49:40 +00001623
1624 switch (B->getOpcode()) {
1625 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001626 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001627 return;
1628 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001629 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001630 return;
1631 default:
1632 assert(false && "Invalid logical operator.");
1633 }
1634 }
1635
Ted Kremenekcfaae762007-08-27 21:54:41 +00001636 void VisitExpr(Expr* E) {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00001637 E->printPretty(OS, Helper, Policy);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001638 }
Ted Kremenek73543912007-08-23 21:42:29 +00001639};
Chris Lattner7099c782009-06-30 01:26:17 +00001640} // end anonymous namespace
1641
Ted Kremenek08176a52007-08-31 21:30:12 +00001642
Chris Lattner7099c782009-06-30 01:26:17 +00001643static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1644 Stmt* Terminator) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001645 if (Helper) {
1646 // special printing for statement-expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001647 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001648 CompoundStmt* Sub = SE->getSubStmt();
1649
1650 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001651 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001652 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001653 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001654 return;
1655 }
1656 }
1657
1658 // special printing for comma expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001659 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001660 if (B->getOpcode() == BinaryOperator::Comma) {
1661 OS << "... , ";
1662 Helper->handledStmt(B->getRHS(),OS);
1663 OS << '\n';
1664 return;
1665 }
1666 }
1667 }
1668
Chris Lattner7099c782009-06-30 01:26:17 +00001669 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek86afc042007-08-31 22:26:13 +00001670
1671 // Expressions need a newline.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001672 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek86afc042007-08-31 22:26:13 +00001673}
1674
Chris Lattner7099c782009-06-30 01:26:17 +00001675static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
1676 const CFGBlock& B,
1677 StmtPrinterHelper* Helper, bool print_edges) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001678
1679 if (Helper) Helper->setBlockID(B.getBlockID());
1680
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001681 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001682 OS << "\n [ B" << B.getBlockID();
1683
1684 if (&B == &cfg->getEntry())
1685 OS << " (ENTRY) ]\n";
1686 else if (&B == &cfg->getExit())
1687 OS << " (EXIT) ]\n";
1688 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001689 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001690 else
1691 OS << " ]\n";
1692
Ted Kremenekec055e12007-08-29 23:20:49 +00001693 // Print the label of this block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001694 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001695
1696 if (print_edges)
1697 OS << " ";
1698
Ted Kremenek79f0a632008-04-16 21:10:48 +00001699 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001700 OS << L->getName();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001701 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001702 OS << "case ";
Chris Lattner7099c782009-06-30 01:26:17 +00001703 C->getLHS()->printPretty(OS, Helper,
1704 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenekec055e12007-08-29 23:20:49 +00001705 if (C->getRHS()) {
1706 OS << " ... ";
Chris Lattner7099c782009-06-30 01:26:17 +00001707 C->getRHS()->printPretty(OS, Helper,
1708 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenekec055e12007-08-29 23:20:49 +00001709 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001710 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001711 else if (isa<DefaultStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001712 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001713 else
1714 assert(false && "Invalid label statement in CFGBlock.");
1715
Ted Kremenekec055e12007-08-29 23:20:49 +00001716 OS << ":\n";
1717 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001718
Ted Kremenek97f75312007-08-21 21:42:03 +00001719 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001720 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001721
1722 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1723 I != E ; ++I, ++j ) {
1724
Ted Kremenekec055e12007-08-29 23:20:49 +00001725 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001726 if (print_edges)
1727 OS << " ";
1728
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001729 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001730
1731 if (Helper)
1732 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001733
1734 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001735 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001736
Ted Kremenekec055e12007-08-29 23:20:49 +00001737 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001738 if (B.getTerminator()) {
1739 if (print_edges)
1740 OS << " ";
1741
Ted Kremenekec055e12007-08-29 23:20:49 +00001742 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001743
1744 if (Helper) Helper->setBlockID(-1);
1745
Chris Lattner7099c782009-06-30 01:26:17 +00001746 CFGBlockTerminatorPrint TPrinter(OS, Helper,
1747 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek08176a52007-08-31 21:30:12 +00001748 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001749 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001750 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001751
Ted Kremenekec055e12007-08-29 23:20:49 +00001752 if (print_edges) {
1753 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001754 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001755 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001756
Ted Kremenek08176a52007-08-31 21:30:12 +00001757 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1758 I != E; ++I, ++i) {
1759
1760 if (i == 8 || (i-8) == 0)
1761 OS << "\n ";
1762
Ted Kremenekec055e12007-08-29 23:20:49 +00001763 OS << " B" << (*I)->getBlockID();
1764 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001765
1766 OS << '\n';
1767
1768 // Print the successors of this block.
1769 OS << " Successors (" << B.succ_size() << "):";
1770 i = 0;
1771
1772 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1773 I != E; ++I, ++i) {
1774
1775 if (i == 8 || (i-8) % 10 == 0)
1776 OS << "\n ";
1777
1778 OS << " B" << (*I)->getBlockID();
1779 }
1780
Ted Kremenekec055e12007-08-29 23:20:49 +00001781 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001782 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001783}
1784
Ted Kremenek08176a52007-08-31 21:30:12 +00001785
1786/// dump - A simple pretty printer of a CFG that outputs to stderr.
Chris Lattner7099c782009-06-30 01:26:17 +00001787void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001788
1789/// print - A simple pretty printer of a CFG that outputs to an ostream.
Chris Lattner7099c782009-06-30 01:26:17 +00001790void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
1791 StmtPrinterHelper Helper(this, LO);
Ted Kremenek08176a52007-08-31 21:30:12 +00001792
1793 // Print the entry block.
1794 print_block(OS, this, getEntry(), &Helper, true);
1795
1796 // Iterate through the CFGBlocks and print them one by one.
1797 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1798 // Skip the entry block, because we already printed it.
1799 if (&(*I) == &getEntry() || &(*I) == &getExit())
1800 continue;
1801
1802 print_block(OS, this, *I, &Helper, true);
1803 }
1804
1805 // Print the exit block.
1806 print_block(OS, this, getExit(), &Helper, true);
Ted Kremenekd19e99e2008-11-24 20:50:24 +00001807 OS.flush();
Ted Kremenek08176a52007-08-31 21:30:12 +00001808}
1809
1810/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Chris Lattner7099c782009-06-30 01:26:17 +00001811void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
1812 print(llvm::errs(), cfg, LO);
1813}
Ted Kremenek08176a52007-08-31 21:30:12 +00001814
1815/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1816/// Generally this will only be called from CFG::print.
Chris Lattner7099c782009-06-30 01:26:17 +00001817void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
1818 const LangOptions &LO) const {
1819 StmtPrinterHelper Helper(cfg, LO);
Ted Kremenek08176a52007-08-31 21:30:12 +00001820 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001821}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001822
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001823/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner7099c782009-06-30 01:26:17 +00001824void CFGBlock::printTerminator(llvm::raw_ostream &OS,
1825 const LangOptions &LO) const {
1826 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001827 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1828}
1829
Ted Kremenek16516e22008-11-12 21:11:49 +00001830Stmt* CFGBlock::getTerminatorCondition() {
Ted Kremenek79f0a632008-04-16 21:10:48 +00001831
1832 if (!Terminator)
1833 return NULL;
1834
1835 Expr* E = NULL;
1836
1837 switch (Terminator->getStmtClass()) {
1838 default:
1839 break;
1840
1841 case Stmt::ForStmtClass:
1842 E = cast<ForStmt>(Terminator)->getCond();
1843 break;
1844
1845 case Stmt::WhileStmtClass:
1846 E = cast<WhileStmt>(Terminator)->getCond();
1847 break;
1848
1849 case Stmt::DoStmtClass:
1850 E = cast<DoStmt>(Terminator)->getCond();
1851 break;
1852
1853 case Stmt::IfStmtClass:
1854 E = cast<IfStmt>(Terminator)->getCond();
1855 break;
1856
1857 case Stmt::ChooseExprClass:
1858 E = cast<ChooseExpr>(Terminator)->getCond();
1859 break;
1860
1861 case Stmt::IndirectGotoStmtClass:
1862 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1863 break;
1864
1865 case Stmt::SwitchStmtClass:
1866 E = cast<SwitchStmt>(Terminator)->getCond();
1867 break;
1868
1869 case Stmt::ConditionalOperatorClass:
1870 E = cast<ConditionalOperator>(Terminator)->getCond();
1871 break;
1872
1873 case Stmt::BinaryOperatorClass: // '&&' and '||'
1874 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek16516e22008-11-12 21:11:49 +00001875 break;
1876
1877 case Stmt::ObjCForCollectionStmtClass:
1878 return Terminator;
Ted Kremenek79f0a632008-04-16 21:10:48 +00001879 }
1880
1881 return E ? E->IgnoreParens() : NULL;
1882}
1883
Ted Kremenekbdbd1b52008-05-16 16:06:00 +00001884bool CFGBlock::hasBinaryBranchTerminator() const {
1885
1886 if (!Terminator)
1887 return false;
1888
1889 Expr* E = NULL;
1890
1891 switch (Terminator->getStmtClass()) {
1892 default:
1893 return false;
1894
1895 case Stmt::ForStmtClass:
1896 case Stmt::WhileStmtClass:
1897 case Stmt::DoStmtClass:
1898 case Stmt::IfStmtClass:
1899 case Stmt::ChooseExprClass:
1900 case Stmt::ConditionalOperatorClass:
1901 case Stmt::BinaryOperatorClass:
1902 return true;
1903 }
1904
1905 return E ? E->IgnoreParens() : NULL;
1906}
1907
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001908
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001909//===----------------------------------------------------------------------===//
1910// CFG Graphviz Visualization
1911//===----------------------------------------------------------------------===//
1912
Ted Kremenek08176a52007-08-31 21:30:12 +00001913
1914#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001915static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001916#endif
1917
Chris Lattner7099c782009-06-30 01:26:17 +00001918void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek08176a52007-08-31 21:30:12 +00001919#ifndef NDEBUG
Chris Lattner7099c782009-06-30 01:26:17 +00001920 StmtPrinterHelper H(this, LO);
Ted Kremenek08176a52007-08-31 21:30:12 +00001921 GraphHelper = &H;
1922 llvm::ViewGraph(this,"CFG");
1923 GraphHelper = NULL;
Ted Kremenek08176a52007-08-31 21:30:12 +00001924#endif
1925}
1926
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001927namespace llvm {
1928template<>
1929struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Owen Anderson18ead7b2009-06-24 17:37:55 +00001930 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph,
1931 bool ShortNames) {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001932
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001933#ifndef NDEBUG
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001934 std::string OutSStr;
1935 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek08176a52007-08-31 21:30:12 +00001936 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001937 std::string& OutStr = Out.str();
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001938
1939 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1940
1941 // Process string output to make it nicer...
1942 for (unsigned i = 0; i != OutStr.length(); ++i)
1943 if (OutStr[i] == '\n') { // Left justify
1944 OutStr[i] = '\\';
1945 OutStr.insert(OutStr.begin()+i+1, 'l');
1946 }
1947
1948 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001949#else
1950 return "";
1951#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001952 }
1953};
1954} // end namespace llvm