blob: 84bf1e72a4e405f25b9be2420521c34336c456c9 [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
15#include "clang/AST/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 Kremenek97f75312007-08-21 21:42:03 +000024#include <iomanip>
25#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000026#include <sstream>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000027
Ted Kremenek97f75312007-08-21 21:42:03 +000028using namespace clang;
29
30namespace {
31
Ted Kremenekd6e50602007-08-23 21:26:19 +000032// SaveAndRestore - A utility class that uses RIIA to save and restore
33// the value of a variable.
34template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000035struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000036 SaveAndRestore(T& x) : X(x), old_value(x) {}
37 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000038 T get() { return old_value; }
39
Ted Kremenekd6e50602007-08-23 21:26:19 +000040 T& X;
41 T old_value;
42};
Ted Kremenek97f75312007-08-21 21:42:03 +000043
Ted Kremenek0865a992008-08-06 23:20:50 +000044static SourceLocation GetEndLoc(ScopedDecl* D) {
45 if (VarDecl* VD = dyn_cast<VarDecl>(D))
46 if (Expr* Ex = VD->getInit())
47 return Ex->getSourceRange().getEnd();
48
49 return D->getLocation();
50}
51
52class VISIBILITY_HIDDEN UnaryDeclStmt : public DeclStmt {
53 Stmt* Ex;
54public:
55 UnaryDeclStmt(ScopedDecl* D)
56 : DeclStmt(D, D->getLocation(), GetEndLoc(D)), Ex(0) {
57 if (VarDecl* VD = dyn_cast<VarDecl>(D))
58 Ex = VD->getInit();
59 }
60
61 virtual ~UnaryDeclStmt() {}
62 virtual void Destroy(ASTContext& Ctx) { assert(false && "Do not call"); }
63
64 virtual child_iterator child_begin() {
65 return Ex ? &Ex : 0;
66 }
67 virtual child_iterator child_end() {
68 return Ex ? &Ex + 1 : 0;
69 }
70 virtual decl_iterator decl_begin() {
71 return getDecl();
72 }
73 virtual decl_iterator decl_end() {
74 ScopedDecl* D = getDecl();
75 return D ? D->getNextDeclarator() : 0;
76 }
77};
78
Ted Kremeneka3195a32008-08-04 22:51:42 +000079/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek97f75312007-08-21 21:42:03 +000080/// The builder is stateful: an instance of the builder should be used to only
81/// construct a single CFG.
82///
83/// Example usage:
84///
85/// CFGBuilder builder;
86/// CFG* cfg = builder.BuildAST(stmt1);
87///
Ted Kremenek95e854d2007-08-21 22:06:14 +000088/// CFG construction is done via a recursive walk of an AST.
89/// We actually parse the AST in reverse order so that the successor
90/// of a basic block is constructed prior to its predecessor. This
91/// allows us to nicely capture implicit fall-throughs without extra
92/// basic blocks.
93///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000094class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000095 CFG* cfg;
96 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000097 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000098 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000099 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000100 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +0000101 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +0000102
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000103 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +0000104 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
105 LabelMapTy LabelMap;
106
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000107 // A list of blocks that end with a "goto" that must be backpatched to
108 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +0000109 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000110 BackpatchBlocksTy BackpatchBlocks;
111
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000112 // A list of labels whose address has been taken (for indirect gotos).
113 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
114 LabelSetTy AddressTakenLabels;
115
Ted Kremenek97f75312007-08-21 21:42:03 +0000116public:
Ted Kremenek4db5b452007-08-23 16:51:22 +0000117 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +0000118 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000119 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +0000120 // Create an empty CFG.
121 cfg = new CFG();
122 }
123
124 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +0000125
Ted Kremenek73543912007-08-23 21:42:29 +0000126 // buildCFG - Used by external clients to construct the CFG.
127 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000128
Ted Kremenek73543912007-08-23 21:42:29 +0000129 // Visitors to walk an AST and construct the CFG. Called by
130 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +0000131
Ted Kremenek73543912007-08-23 21:42:29 +0000132 CFGBlock* VisitStmt(Stmt* Statement);
133 CFGBlock* VisitNullStmt(NullStmt* Statement);
134 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
135 CFGBlock* VisitIfStmt(IfStmt* I);
136 CFGBlock* VisitReturnStmt(ReturnStmt* R);
137 CFGBlock* VisitLabelStmt(LabelStmt* L);
138 CFGBlock* VisitGotoStmt(GotoStmt* G);
139 CFGBlock* VisitForStmt(ForStmt* F);
140 CFGBlock* VisitWhileStmt(WhileStmt* W);
141 CFGBlock* VisitDoStmt(DoStmt* D);
142 CFGBlock* VisitContinueStmt(ContinueStmt* C);
143 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000144 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
145 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000146 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000147 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000148
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000149 // FIXME: Add support for ObjC-specific control-flow structures.
150
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000151 // NYS == Not Yet Supported
152 CFGBlock* NYS() {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000153 badCFG = true;
154 return Block;
155 }
156
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000157 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
158 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
159 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
160 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
161 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
162
163 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
164 return NYS();
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000165 }
166
Ted Kremenek73543912007-08-23 21:42:29 +0000167private:
168 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000169 CFGBlock* addStmt(Stmt* Terminator);
170 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
171 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenek0865a992008-08-06 23:20:50 +0000172 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000173 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000174 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000175
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000176 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000177};
Ted Kremenek73543912007-08-23 21:42:29 +0000178
179/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
180/// represent an arbitrary statement. Examples include a single expression
181/// or a function body (compound statement). The ownership of the returned
182/// CFG is transferred to the caller. If CFG construction fails, this method
183/// returns NULL.
184CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000185 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000186 if (!Statement) return NULL;
187
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000188 badCFG = false;
189
Ted Kremenek73543912007-08-23 21:42:29 +0000190 // Create an empty block that will serve as the exit block for the CFG.
191 // Since this is the first block added to the CFG, it will be implicitly
192 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000193 Succ = createBlock();
194 assert (Succ == &cfg->getExit());
195 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000196
197 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000198 CFGBlock* B = Visit(Statement);
199 if (!B) B = Succ;
200
201 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000202 // Finalize the last constructed block. This usually involves
203 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000204 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000205
206 // Backpatch the gotos whose label -> block mappings we didn't know
207 // when we encountered them.
208 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
209 E = BackpatchBlocks.end(); I != E; ++I ) {
210
211 CFGBlock* B = *I;
212 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
213 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
214
215 // If there is no target for the goto, then we are looking at an
216 // incomplete AST. Handle this by not registering a successor.
217 if (LI == LabelMap.end()) continue;
218
219 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000220 }
Ted Kremenek73543912007-08-23 21:42:29 +0000221
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000222 // Add successors to the Indirect Goto Dispatch block (if we have one).
223 if (CFGBlock* B = cfg->getIndirectGotoBlock())
224 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
225 E = AddressTakenLabels.end(); I != E; ++I ) {
226
227 // Lookup the target block.
228 LabelMapTy::iterator LI = LabelMap.find(*I);
229
230 // If there is no target block that contains label, then we are looking
231 // at an incomplete AST. Handle this by not registering a successor.
232 if (LI == LabelMap.end()) continue;
233
234 B->addSuccessor(LI->second);
235 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000236
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000237 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000238 }
239
240 // Create an empty entry block that has no predecessors.
241 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000242
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000243 if (badCFG) {
244 delete cfg;
245 cfg = NULL;
246 return NULL;
247 }
248
Ted Kremenek680fcb82007-09-26 21:23:31 +0000249 // NULL out cfg so that repeated calls to the builder will fail and that
250 // the ownership of the constructed CFG is passed to the caller.
251 CFG* t = cfg;
252 cfg = NULL;
253 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000254}
255
256/// createBlock - Used to lazily create blocks that are connected
257/// to the current (global) succcessor.
258CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000259 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000260 if (add_successor && Succ) B->addSuccessor(Succ);
261 return B;
262}
263
264/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000265/// we must reverse the statements because they have been inserted
266/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000267void CFGBuilder::FinishBlock(CFGBlock* B) {
268 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000269 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000270}
271
Ted Kremenek65cfa562007-08-27 21:27:44 +0000272/// addStmt - Used to add statements/expressions to the current CFGBlock
273/// "Block". This method calls WalkAST on the passed statement to see if it
274/// contains any short-circuit expressions. If so, it recursively creates
275/// the necessary blocks for such expressions. It returns the "topmost" block
276/// of the created blocks, or the original value of "Block" when this method
277/// was called if no additional blocks are created.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000278CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000279 if (!Block) Block = createBlock();
Ted Kremenek79f0a632008-04-16 21:10:48 +0000280 return WalkAST(Terminator,true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000281}
282
283/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000284/// add extra blocks for ternary operators, &&, and ||. We also
285/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000286CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
287 switch (Terminator->getStmtClass()) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000288 case Stmt::ConditionalOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000289 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000290
291 // Create the confluence block that will "merge" the results
292 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000293 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
294 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000295 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000296
297 // Create a block for the LHS expression if there is an LHS expression.
298 // A GCC extension allows LHS to be NULL, causing the condition to
299 // be the value that is returned instead.
300 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000301 Succ = ConfluenceBlock;
302 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000303 CFGBlock* LHSBlock = NULL;
304 if (C->getLHS()) {
305 LHSBlock = Visit(C->getLHS());
306 FinishBlock(LHSBlock);
307 Block = NULL;
308 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000309
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000310 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000311 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000312 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000313 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000314
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
343 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
344 ConfluenceBlock->appendStmt(C);
345 FinishBlock(ConfluenceBlock);
346
347 Succ = ConfluenceBlock;
348 Block = NULL;
349 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000350 FinishBlock(LHSBlock);
351
Ted Kremenek7f788422007-08-31 17:03:41 +0000352 Succ = ConfluenceBlock;
353 Block = NULL;
354 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000355 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000356
357 Block = createBlock(false);
358 Block->addSuccessor(LHSBlock);
359 Block->addSuccessor(RHSBlock);
360 Block->setTerminator(C);
361 return addStmt(C->getCond());
362 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000363
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000364 case Stmt::DeclStmtClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000365 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000366
Ted Kremenek0865a992008-08-06 23:20:50 +0000367 if (!D->getNextDeclarator()) {
368 Block->appendStmt(Terminator);
369 return WalkAST_VisitDeclSubExpr(D);
370 }
371 else {
372 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
373 BufTy Buf;
374 CFGBlock* B = 0;
375 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
376 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
377 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
378 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
379 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
380
381 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
382 // get automatically freed with the CFG.
383 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
384 // Append the fake DeclStmt to block.
385 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
386 B = WalkAST_VisitDeclSubExpr(*I);
387 }
388 return B;
389 }
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000390 }
Ted Kremenek0865a992008-08-06 23:20:50 +0000391
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000392 case Stmt::AddrLabelExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000393 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000394 AddressTakenLabels.insert(A->getLabel());
395
Ted Kremenek79f0a632008-04-16 21:10:48 +0000396 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000397 return Block;
398 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000399
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000400 case Stmt::StmtExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000401 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremeneke822b622007-08-28 18:14:37 +0000402
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000403 case Stmt::UnaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000404 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000405
406 // sizeof(expressions). For such expressions,
407 // the subexpression is not really evaluated, so
408 // we don't care about control-flow within the sizeof.
409 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000410 Block->appendStmt(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000411 return Block;
412 }
413
414 break;
415 }
416
Ted Kremenekcfaae762007-08-27 21:54:41 +0000417 case Stmt::BinaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000418 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000419
420 if (B->isLogicalOp()) { // && or ||
421 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
422 ConfluenceBlock->appendStmt(B);
423 FinishBlock(ConfluenceBlock);
424
425 // create the block evaluating the LHS
426 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000427 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000428
429 // create the block evaluating the RHS
430 Succ = ConfluenceBlock;
431 Block = NULL;
432 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000433
434 // Now link the LHSBlock with RHSBlock.
435 if (B->getOpcode() == BinaryOperator::LOr) {
436 LHSBlock->addSuccessor(ConfluenceBlock);
437 LHSBlock->addSuccessor(RHSBlock);
438 }
439 else {
440 assert (B->getOpcode() == BinaryOperator::LAnd);
441 LHSBlock->addSuccessor(RHSBlock);
442 LHSBlock->addSuccessor(ConfluenceBlock);
443 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000444
445 // Generate the blocks for evaluating the LHS.
446 Block = LHSBlock;
447 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000448 }
449 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
450 Block->appendStmt(B);
451 addStmt(B->getRHS());
452 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000453 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000454
455 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000456 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000457
458 case Stmt::ParenExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000459 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000460
Ted Kremenek65cfa562007-08-27 21:27:44 +0000461 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000462 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000463 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000464
Ted Kremenek79f0a632008-04-16 21:10:48 +0000465 if (AlwaysAddStmt) Block->appendStmt(Terminator);
466 return WalkAST_VisitChildren(Terminator);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000467}
468
Ted Kremenek0865a992008-08-06 23:20:50 +0000469/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
470/// for initializers in Decls.
471CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
472 VarDecl* VD = dyn_cast<VarDecl>(D);
473
474 if (!VD)
Ted Kremenekf4e35622007-11-18 20:06:01 +0000475 return Block;
476
Ted Kremenek0865a992008-08-06 23:20:50 +0000477 Expr* Init = VD->getInit();
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000478
Ted Kremenek0865a992008-08-06 23:20:50 +0000479 if (!Init)
480 return Block;
481
482 // Optimization: Don't create separate block-level statements for literals.
483 switch (Init->getStmtClass()) {
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000484 case Stmt::IntegerLiteralClass:
485 case Stmt::CharacterLiteralClass:
486 case Stmt::StringLiteralClass:
487 break;
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000488 default:
Ted Kremenek0865a992008-08-06 23:20:50 +0000489 Block = addStmt(Init);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000490 }
491
Ted Kremeneke822b622007-08-28 18:14:37 +0000492 return Block;
493}
494
Ted Kremenek65cfa562007-08-27 21:27:44 +0000495/// WalkAST_VisitChildren - Utility method to call WalkAST on the
496/// children of a Stmt.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000497CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000498 CFGBlock* B = Block;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000499 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000500 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000501 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000502
503 return B;
504}
505
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000506/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
507/// expressions (a GCC extension).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000508CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
509 Block->appendStmt(Terminator);
510 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000511}
512
Ted Kremenek73543912007-08-23 21:42:29 +0000513/// VisitStmt - Handle statements with no branching control flow.
514CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
515 // We cannot assume that we are in the middle of a basic block, since
516 // the CFG might only be constructed for this single statement. If
517 // we have no current basic block, just create one lazily.
518 if (!Block) Block = createBlock();
519
520 // Simply add the statement to the current block. We actually
521 // insert statements in reverse order; this order is reversed later
522 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000523 addStmt(Statement);
524
Ted Kremenek73543912007-08-23 21:42:29 +0000525 return Block;
526}
527
528CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
529 return Block;
530}
531
532CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000533
534 CFGBlock* LastBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000535
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000536 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
537 I != E; ++I ) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000538 LastBlock = Visit(*I);
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000539 }
540
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000541 return LastBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000542}
543
544CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
545 // We may see an if statement in the middle of a basic block, or
546 // it may be the first statement we are processing. In either case,
547 // we create a new basic block. First, we create the blocks for
548 // the then...else statements, and then we create the block containing
549 // the if statement. If we were in the middle of a block, we
550 // stop processing that block and reverse its statements. That block
551 // is then the implicit successor for the "then" and "else" clauses.
552
553 // The block we were proccessing is now finished. Make it the
554 // successor block.
555 if (Block) {
556 Succ = Block;
557 FinishBlock(Block);
558 }
559
560 // Process the false branch. NULL out Block so that the recursive
561 // call to Visit will create a new basic block.
562 // Null out Block so that all successor
563 CFGBlock* ElseBlock = Succ;
564
565 if (Stmt* Else = I->getElse()) {
566 SaveAndRestore<CFGBlock*> sv(Succ);
567
568 // NULL out Block so that the recursive call to Visit will
569 // create a new basic block.
570 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000571 ElseBlock = Visit(Else);
572
573 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
574 ElseBlock = sv.get();
575 else if (Block)
576 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000577 }
578
579 // Process the true branch. NULL out Block so that the recursive
580 // call to Visit will create a new basic block.
581 // Null out Block so that all successor
582 CFGBlock* ThenBlock;
583 {
584 Stmt* Then = I->getThen();
585 assert (Then);
586 SaveAndRestore<CFGBlock*> sv(Succ);
587 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000588 ThenBlock = Visit(Then);
589
590 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
591 ThenBlock = sv.get();
592 else if (Block)
593 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000594 }
595
596 // Now create a new block containing the if statement.
597 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000598
599 // Set the terminator of the new block to the If statement.
600 Block->setTerminator(I);
601
602 // Now add the successors.
603 Block->addSuccessor(ThenBlock);
604 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000605
606 // Add the condition as the last statement in the new block. This
607 // may create new blocks as the condition may contain control-flow. Any
608 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000609 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000610}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000611
Ted Kremenek73543912007-08-23 21:42:29 +0000612
613CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
614 // If we were in the middle of a block we stop processing that block
615 // and reverse its statements.
616 //
617 // NOTE: If a "return" appears in the middle of a block, this means
618 // that the code afterwards is DEAD (unreachable). We still
619 // keep a basic block for that code; a simple "mark-and-sweep"
620 // from the entry block will be able to report such dead
621 // blocks.
622 if (Block) FinishBlock(Block);
623
624 // Create the new block.
625 Block = createBlock(false);
626
627 // The Exit block is the only successor.
628 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000629
630 // Add the return statement to the block. This may create new blocks
631 // if R contains control-flow (short-circuit operations).
632 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000633}
634
635CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
636 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek82e8a192008-03-15 07:45:02 +0000637 Visit(L->getSubStmt());
638 CFGBlock* LabelBlock = Block;
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000639
640 if (!LabelBlock) // This can happen when the body is empty, i.e.
641 LabelBlock=createBlock(); // scopes that only contains NullStmts.
642
Ted Kremenek73543912007-08-23 21:42:29 +0000643 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
644 LabelMap[ L ] = LabelBlock;
645
646 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000647 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000648 // label (and we have already processed the substatement) there is no
649 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000650 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000651 FinishBlock(LabelBlock);
652
653 // We set Block to NULL to allow lazy creation of a new block
654 // (if necessary);
655 Block = NULL;
656
657 // This block is now the implicit successor of other blocks.
658 Succ = LabelBlock;
659
660 return LabelBlock;
661}
662
663CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
664 // Goto is a control-flow statement. Thus we stop processing the
665 // current block and create a new one.
666 if (Block) FinishBlock(Block);
667 Block = createBlock(false);
668 Block->setTerminator(G);
669
670 // If we already know the mapping to the label block add the
671 // successor now.
672 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
673
674 if (I == LabelMap.end())
675 // We will need to backpatch this block later.
676 BackpatchBlocks.push_back(Block);
677 else
678 Block->addSuccessor(I->second);
679
680 return Block;
681}
682
683CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
684 // "for" is a control-flow statement. Thus we stop processing the
685 // current block.
686
687 CFGBlock* LoopSuccessor = NULL;
688
689 if (Block) {
690 FinishBlock(Block);
691 LoopSuccessor = Block;
692 }
693 else LoopSuccessor = Succ;
694
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000695 // Because of short-circuit evaluation, the condition of the loop
696 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
697 // blocks that evaluate the condition.
698 CFGBlock* ExitConditionBlock = createBlock(false);
699 CFGBlock* EntryConditionBlock = ExitConditionBlock;
700
701 // Set the terminator for the "exit" condition block.
702 ExitConditionBlock->setTerminator(F);
703
704 // Now add the actual condition to the condition block. Because the
705 // condition itself may contain control-flow, new blocks may be created.
706 if (Stmt* C = F->getCond()) {
707 Block = ExitConditionBlock;
708 EntryConditionBlock = addStmt(C);
709 if (Block) FinishBlock(EntryConditionBlock);
710 }
Ted Kremenek73543912007-08-23 21:42:29 +0000711
712 // The condition block is the implicit successor for the loop body as
713 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000714 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000715
716 // Now create the loop body.
717 {
718 assert (F->getBody());
719
720 // Save the current values for Block, Succ, and continue and break targets
721 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
722 save_continue(ContinueTargetBlock),
723 save_break(BreakTargetBlock);
Ted Kremenek77f93372008-09-04 21:48:47 +0000724
Ted Kremenek390b9762007-08-30 18:39:40 +0000725 // Create a new block to contain the (bottom) of the loop body.
726 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000727
Ted Kremenek77f93372008-09-04 21:48:47 +0000728 if (Stmt* I = F->getInc()) {
729 // Generate increment code in its own basic block. This is the target
730 // of continue statements.
731 Succ = addStmt(I);
732 Block = 0;
733 ContinueTargetBlock = Succ;
734 }
735 else {
736 // No increment code. Continues should go the the entry condition block.
737 ContinueTargetBlock = EntryConditionBlock;
738 }
739
740 // All breaks should go to the code following the loop.
741 BreakTargetBlock = LoopSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000742
743 // Now populate the body block, and in the process create new blocks
744 // as we walk the body of the loop.
745 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000746
747 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000748 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000749 else if (Block)
750 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000751
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000752 // This new body block is a successor to our "exit" condition block.
753 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000754 }
755
756 // Link up the condition block with the code that follows the loop.
757 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000758 ExitConditionBlock->addSuccessor(LoopSuccessor);
759
Ted Kremenek73543912007-08-23 21:42:29 +0000760 // If the loop contains initialization, create a new block for those
761 // statements. This block can also contain statements that precede
762 // the loop.
763 if (Stmt* I = F->getInit()) {
764 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000765 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000766 }
767 else {
768 // There is no loop initialization. We are thus basically a while
769 // loop. NULL out Block to force lazy block construction.
770 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000771 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000772 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000773 }
774}
775
776CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
777 // "while" is a control-flow statement. Thus we stop processing the
778 // current block.
779
780 CFGBlock* LoopSuccessor = NULL;
781
782 if (Block) {
783 FinishBlock(Block);
784 LoopSuccessor = Block;
785 }
786 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000787
788 // Because of short-circuit evaluation, the condition of the loop
789 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
790 // blocks that evaluate the condition.
791 CFGBlock* ExitConditionBlock = createBlock(false);
792 CFGBlock* EntryConditionBlock = ExitConditionBlock;
793
794 // Set the terminator for the "exit" condition block.
795 ExitConditionBlock->setTerminator(W);
796
797 // Now add the actual condition to the condition block. Because the
798 // condition itself may contain control-flow, new blocks may be created.
799 // Thus we update "Succ" after adding the condition.
800 if (Stmt* C = W->getCond()) {
801 Block = ExitConditionBlock;
802 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000803 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000804 if (Block) FinishBlock(EntryConditionBlock);
805 }
Ted Kremenek73543912007-08-23 21:42:29 +0000806
807 // The condition block is the implicit successor for the loop body as
808 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000809 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000810
811 // Process the loop body.
812 {
813 assert (W->getBody());
814
815 // Save the current values for Block, Succ, and continue and break targets
816 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
817 save_continue(ContinueTargetBlock),
818 save_break(BreakTargetBlock);
819
820 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000821 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000822
823 // All breaks should go to the code following the loop.
824 BreakTargetBlock = LoopSuccessor;
825
826 // NULL out Block to force lazy instantiation of blocks for the body.
827 Block = NULL;
828
829 // Create the body. The returned block is the entry to the loop body.
830 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000831
832 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000833 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000834 else if (Block)
835 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000836
837 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000838 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000839 }
840
841 // Link up the condition block with the code that follows the loop.
842 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000843 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000844
845 // There can be no more statements in the condition block
846 // since we loop back to this block. NULL out Block to force
847 // lazy creation of another block.
848 Block = NULL;
849
850 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000851 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000852 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000853}
854
855CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
856 // "do...while" is a control-flow statement. Thus we stop processing the
857 // current block.
858
859 CFGBlock* LoopSuccessor = NULL;
860
861 if (Block) {
862 FinishBlock(Block);
863 LoopSuccessor = Block;
864 }
865 else LoopSuccessor = Succ;
866
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000867 // Because of short-circuit evaluation, the condition of the loop
868 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
869 // blocks that evaluate the condition.
870 CFGBlock* ExitConditionBlock = createBlock(false);
871 CFGBlock* EntryConditionBlock = ExitConditionBlock;
872
873 // Set the terminator for the "exit" condition block.
874 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000875
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000876 // Now add the actual condition to the condition block. Because the
877 // condition itself may contain control-flow, new blocks may be created.
878 if (Stmt* C = D->getCond()) {
879 Block = ExitConditionBlock;
880 EntryConditionBlock = addStmt(C);
881 if (Block) FinishBlock(EntryConditionBlock);
882 }
Ted Kremenek73543912007-08-23 21:42:29 +0000883
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000884 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000885 Succ = EntryConditionBlock;
886
Ted Kremenek73543912007-08-23 21:42:29 +0000887 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000888 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000889 {
890 assert (D->getBody());
891
892 // Save the current values for Block, Succ, and continue and break targets
893 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
894 save_continue(ContinueTargetBlock),
895 save_break(BreakTargetBlock);
896
897 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000898 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000899
900 // All breaks should go to the code following the loop.
901 BreakTargetBlock = LoopSuccessor;
902
903 // NULL out Block to force lazy instantiation of blocks for the body.
904 Block = NULL;
905
906 // Create the body. The returned block is the entry to the loop body.
907 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000908
Ted Kremenek390b9762007-08-30 18:39:40 +0000909 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000910 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000911 else if (Block)
912 FinishBlock(BodyBlock);
913
Ted Kremenek73543912007-08-23 21:42:29 +0000914 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000915 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000916 }
917
918 // Link up the condition block with the code that follows the loop.
919 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000920 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000921
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000922 // There can be no more statements in the body block(s)
923 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000924 // lazy creation of another block.
925 Block = NULL;
926
927 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000928 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000929 return BodyBlock;
930}
931
932CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
933 // "continue" is a control-flow statement. Thus we stop processing the
934 // current block.
935 if (Block) FinishBlock(Block);
936
937 // Now create a new block that ends with the continue statement.
938 Block = createBlock(false);
939 Block->setTerminator(C);
940
941 // If there is no target for the continue, then we are looking at an
942 // incomplete AST. Handle this by not registering a successor.
943 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
944
945 return Block;
946}
947
948CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
949 // "break" is a control-flow statement. Thus we stop processing the
950 // current block.
951 if (Block) FinishBlock(Block);
952
953 // Now create a new block that ends with the continue statement.
954 Block = createBlock(false);
955 Block->setTerminator(B);
956
957 // If there is no target for the break, then we are looking at an
958 // incomplete AST. Handle this by not registering a successor.
959 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
960
961 return Block;
962}
963
Ted Kremenek79f0a632008-04-16 21:10:48 +0000964CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek73543912007-08-23 21:42:29 +0000965 // "switch" is a control-flow statement. Thus we stop processing the
966 // current block.
967 CFGBlock* SwitchSuccessor = NULL;
968
969 if (Block) {
970 FinishBlock(Block);
971 SwitchSuccessor = Block;
972 }
973 else SwitchSuccessor = Succ;
974
975 // Save the current "switch" context.
976 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000977 save_break(BreakTargetBlock),
978 save_default(DefaultCaseBlock);
979
980 // Set the "default" case to be the block after the switch statement.
981 // If the switch statement contains a "default:", this value will
982 // be overwritten with the block for that code.
983 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000984
Ted Kremenek73543912007-08-23 21:42:29 +0000985 // Create a new block that will contain the switch statement.
986 SwitchTerminatedBlock = createBlock(false);
987
Ted Kremenek73543912007-08-23 21:42:29 +0000988 // Now process the switch body. The code after the switch is the implicit
989 // successor.
990 Succ = SwitchSuccessor;
991 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000992
993 // When visiting the body, the case statements should automatically get
994 // linked up to the switch. We also don't keep a pointer to the body,
995 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000996 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000997 Block = NULL;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000998 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000999 if (Block) FinishBlock(BodyBlock);
1000
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001001 // If we have no "default:" case, the default transition is to the
1002 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +00001003 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001004
Ted Kremenekcfee50c2007-08-27 19:46:09 +00001005 // Add the terminator and condition in the switch block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001006 SwitchTerminatedBlock->setTerminator(Terminator);
1007 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +00001008 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001009
Ted Kremenek79f0a632008-04-16 21:10:48 +00001010 return addStmt(Terminator->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +00001011}
1012
Ted Kremenek79f0a632008-04-16 21:10:48 +00001013CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenek97bc3422008-02-13 22:05:39 +00001014 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +00001015 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +00001016
Ted Kremenek79f0a632008-04-16 21:10:48 +00001017 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek44659d82007-08-30 18:48:11 +00001018 CFGBlock* CaseBlock = Block;
1019 if (!CaseBlock) CaseBlock = createBlock();
1020
Ted Kremenek97bc3422008-02-13 22:05:39 +00001021 // Cases statements partition blocks, so this is the top of
1022 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001023 CaseBlock->setLabel(Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +00001024 FinishBlock(CaseBlock);
1025
1026 // Add this block to the list of successors for the block with the
1027 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +00001028 assert (SwitchTerminatedBlock);
1029 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +00001030
1031 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1032 Block = NULL;
1033
1034 // This block is now the implicit successor of other blocks.
1035 Succ = CaseBlock;
1036
Ted Kremenek82e8a192008-03-15 07:45:02 +00001037 return CaseBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001038}
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001039
Ted Kremenek79f0a632008-04-16 21:10:48 +00001040CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1041 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek97bc3422008-02-13 22:05:39 +00001042 DefaultCaseBlock = Block;
1043 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1044
1045 // Default statements partition blocks, so this is the top of
1046 // the basic block we were processing (the "default:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001047 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek97bc3422008-02-13 22:05:39 +00001048 FinishBlock(DefaultCaseBlock);
1049
1050 // Unlike case statements, we don't add the default block to the
1051 // successors for the switch statement immediately. This is done
1052 // when we finish processing the switch statement. This allows for
1053 // the default case (including a fall-through to the code after the
1054 // switch statement) to always be the last successor of a switch-terminated
1055 // block.
1056
1057 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1058 Block = NULL;
1059
1060 // This block is now the implicit successor of other blocks.
1061 Succ = DefaultCaseBlock;
1062
1063 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001064}
Ted Kremenek73543912007-08-23 21:42:29 +00001065
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001066CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1067 // Lazily create the indirect-goto dispatch block if there isn't one
1068 // already.
1069 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1070
1071 if (!IBlock) {
1072 IBlock = createBlock(false);
1073 cfg->setIndirectGotoBlock(IBlock);
1074 }
1075
1076 // IndirectGoto is a control-flow statement. Thus we stop processing the
1077 // current block and create a new one.
1078 if (Block) FinishBlock(Block);
1079 Block = createBlock(false);
1080 Block->setTerminator(I);
1081 Block->addSuccessor(IBlock);
1082 return addStmt(I->getTarget());
1083}
1084
Ted Kremenek73543912007-08-23 21:42:29 +00001085
Ted Kremenekd6e50602007-08-23 21:26:19 +00001086} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001087
1088/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1089/// block has no successors or predecessors. If this is the first block
1090/// created in the CFG, it is automatically set to be the Entry and Exit
1091/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001092CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001093 bool first_block = begin() == end();
1094
1095 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001096 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001097
1098 // If this is the first block, set it as the Entry and Exit.
1099 if (first_block) Entry = Exit = &front();
1100
1101 // Return the block.
1102 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001103}
1104
Ted Kremenek4db5b452007-08-23 16:51:22 +00001105/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1106/// CFG is returned to the caller.
1107CFG* CFG::buildCFG(Stmt* Statement) {
1108 CFGBuilder Builder;
1109 return Builder.buildCFG(Statement);
1110}
1111
1112/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001113void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1114
Ted Kremenek3a819822007-10-01 19:33:33 +00001115//===----------------------------------------------------------------------===//
1116// CFG: Queries for BlkExprs.
1117//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001118
Ted Kremenek3a819822007-10-01 19:33:33 +00001119namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001120 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001121}
1122
Ted Kremenek79f0a632008-04-16 21:10:48 +00001123static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1124 if (!Terminator)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001125 return;
1126
Ted Kremenek79f0a632008-04-16 21:10:48 +00001127 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001128 if (!*I) continue;
1129
1130 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1131 if (B->isAssignmentOp()) Set.insert(B);
1132
1133 FindSubExprAssignments(*I, Set);
1134 }
1135}
1136
Ted Kremenek3a819822007-10-01 19:33:33 +00001137static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1138 BlkExprMapTy* M = new BlkExprMapTy();
1139
Ted Kremenekc6fda602008-01-26 00:03:27 +00001140 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek79f0a632008-04-16 21:10:48 +00001141 // only assignments that we want to *possibly* register as a block-level
1142 // expression. Basically, if an assignment occurs both in a subexpression
1143 // and at the block-level, it is a block-level expression.
Ted Kremenekc6fda602008-01-26 00:03:27 +00001144 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1145
Ted Kremenek3a819822007-10-01 19:33:33 +00001146 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1147 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001148 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001149
Ted Kremenek79f0a632008-04-16 21:10:48 +00001150 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1151
1152 // Iterate over the statements again on identify the Expr* and Stmt* at
1153 // the block-level that are block-level expressions.
1154
Ted Kremenekc6fda602008-01-26 00:03:27 +00001155 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek79f0a632008-04-16 21:10:48 +00001156 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001157
Ted Kremenek79f0a632008-04-16 21:10:48 +00001158 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001159 // Assignment expressions that are not nested within another
1160 // expression are really "statements" whose value is never
1161 // used by another expression.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001162 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenekc6fda602008-01-26 00:03:27 +00001163 continue;
1164 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001165 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001166 // Special handling for statement expressions. The last statement
1167 // in the statement expression is also a block-level expr.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001168 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001169 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001170 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001171 (*M)[C->body_back()] = x;
1172 }
1173 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001174
Ted Kremenekc6fda602008-01-26 00:03:27 +00001175 unsigned x = M->size();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001176 (*M)[Exp] = x;
Ted Kremenekc6fda602008-01-26 00:03:27 +00001177 }
1178
Ted Kremenek79f0a632008-04-16 21:10:48 +00001179 // Look at terminators. The condition is a block-level expression.
1180
1181 Expr* Exp = I->getTerminatorCondition();
1182
1183 if (Exp && M->find(Exp) == M->end()) {
1184 unsigned x = M->size();
1185 (*M)[Exp] = x;
1186 }
1187 }
1188
Ted Kremenek3a819822007-10-01 19:33:33 +00001189 return M;
1190}
1191
Ted Kremenekab6c5902008-01-17 20:48:37 +00001192CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1193 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001194 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1195
1196 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001197 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001198
1199 if (I == M->end()) return CFG::BlkExprNumTy();
1200 else return CFG::BlkExprNumTy(I->second);
1201}
1202
1203unsigned CFG::getNumBlkExprs() {
1204 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1205 return M->size();
1206 else {
1207 // We assume callers interested in the number of BlkExprs will want
1208 // the map constructed if it doesn't already exist.
1209 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1210 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1211 }
1212}
1213
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001214//===----------------------------------------------------------------------===//
1215// Internal Block-Edge Set; used for modeling persistent <CFGBlock*,CFGBlock*>
1216// pairs for use with ProgramPoint.
1217//===----------------------------------------------------------------------===//
1218
1219typedef std::pair<CFGBlock*,CFGBlock*> BPairTy;
1220
1221namespace llvm {
1222 template<> struct FoldingSetTrait<BPairTy*> {
1223 static void Profile(const BPairTy* X, FoldingSetNodeID& profile) {
1224 profile.AddPointer(X->first);
1225 profile.AddPointer(X->second);
1226 }
1227 };
1228}
1229
1230typedef llvm::FoldingSetNodeWrapper<BPairTy*> PersistPairTy;
1231typedef llvm::FoldingSet<PersistPairTy> BlkEdgeSetTy;
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001232
1233const std::pair<CFGBlock*,CFGBlock*>*
1234CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1235
Ted Kremenekce668af2008-05-29 21:52:26 +00001236 if (!BlkEdgeSet)
1237 BlkEdgeSet = new BlkEdgeSetTy();
1238
1239 BlkEdgeSetTy* p = static_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001240
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001241 // Profile the edges.
1242 llvm::FoldingSetNodeID profile;
1243 void* InsertPos;
1244
1245 profile.AddPointer(B1);
1246 profile.AddPointer(B2);
1247
1248 PersistPairTy* V = p->FindNodeOrInsertPos(profile, InsertPos);
1249
1250 if (!V) {
1251 assert (llvm::AlignOf<BPairTy>::Alignment_LessEqual_8Bytes);
1252
1253 // Allocate the pair, forcing an 8-byte alignment.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001254 BPairTy* pair = (BPairTy*) Alloc.Allocate(sizeof(*pair), 8);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001255
1256 new (pair) BPairTy(const_cast<CFGBlock*>(B1),
1257 const_cast<CFGBlock*>(B2));
1258
1259 // Allocate the meta data to store the pair in the FoldingSet.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001260 PersistPairTy* ppair = (PersistPairTy*) Alloc.Allocate<PersistPairTy>();
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001261 new (ppair) PersistPairTy(pair);
1262
1263 p->InsertNode(ppair, InsertPos);
1264
1265 return pair;
1266 }
1267
1268 return V->getValue();
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001269}
1270
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001271//===----------------------------------------------------------------------===//
1272// Cleanup: CFG dstor.
1273//===----------------------------------------------------------------------===//
1274
Ted Kremenek3a819822007-10-01 19:33:33 +00001275CFG::~CFG() {
1276 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001277 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001278}
1279
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001280//===----------------------------------------------------------------------===//
1281// CFG pretty printing
1282//===----------------------------------------------------------------------===//
1283
Ted Kremenekd8313202007-08-22 18:22:34 +00001284namespace {
1285
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001286class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001287
Ted Kremenek08176a52007-08-31 21:30:12 +00001288 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1289 StmtMapTy StmtMap;
1290 signed CurrentBlock;
1291 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001292
Ted Kremenek73543912007-08-23 21:42:29 +00001293public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001294
Ted Kremenek08176a52007-08-31 21:30:12 +00001295 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1296 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1297 unsigned j = 1;
1298 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1299 BI != BEnd; ++BI, ++j )
1300 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1301 }
1302 }
1303
1304 virtual ~StmtPrinterHelper() {}
1305
1306 void setBlockID(signed i) { CurrentBlock = i; }
1307 void setStmtID(unsigned i) { CurrentStmt = i; }
1308
Ted Kremenek79f0a632008-04-16 21:10:48 +00001309 virtual bool handledStmt(Stmt* Terminator, std::ostream& OS) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001310
Ted Kremenek79f0a632008-04-16 21:10:48 +00001311 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek08176a52007-08-31 21:30:12 +00001312
1313 if (I == StmtMap.end())
1314 return false;
1315
1316 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1317 && I->second.second == CurrentStmt)
1318 return false;
1319
Ted Kremenek86afc042007-08-31 22:26:13 +00001320 OS << "[B" << I->second.first << "." << I->second.second << "]";
1321 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001322 }
1323};
1324
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001325class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1326 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1327
Ted Kremenek08176a52007-08-31 21:30:12 +00001328 std::ostream& OS;
1329 StmtPrinterHelper* Helper;
1330public:
1331 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1332 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001333
1334 void VisitIfStmt(IfStmt* I) {
1335 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001336 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001337 }
1338
1339 // Default case.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001340 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001341
1342 void VisitForStmt(ForStmt* F) {
1343 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001344 if (F->getInit()) OS << "...";
1345 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001346 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001347 OS << "; ";
1348 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001349 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001350 }
1351
1352 void VisitWhileStmt(WhileStmt* W) {
1353 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001354 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001355 }
1356
1357 void VisitDoStmt(DoStmt* D) {
1358 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001359 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001360 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001361
Ted Kremenek79f0a632008-04-16 21:10:48 +00001362 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +00001363 OS << "switch ";
Ted Kremenek79f0a632008-04-16 21:10:48 +00001364 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001365 }
1366
Ted Kremenek621e1592007-08-31 21:49:40 +00001367 void VisitConditionalOperator(ConditionalOperator* C) {
1368 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001369 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001370 }
1371
Ted Kremenek2025cc92007-08-31 22:29:13 +00001372 void VisitChooseExpr(ChooseExpr* C) {
1373 OS << "__builtin_choose_expr( ";
1374 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001375 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001376 }
1377
Ted Kremenek86afc042007-08-31 22:26:13 +00001378 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1379 OS << "goto *";
1380 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001381 }
1382
Ted Kremenek621e1592007-08-31 21:49:40 +00001383 void VisitBinaryOperator(BinaryOperator* B) {
1384 if (!B->isLogicalOp()) {
1385 VisitExpr(B);
1386 return;
1387 }
1388
1389 B->getLHS()->printPretty(OS,Helper);
1390
1391 switch (B->getOpcode()) {
1392 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001393 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001394 return;
1395 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001396 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001397 return;
1398 default:
1399 assert(false && "Invalid logical operator.");
1400 }
1401 }
1402
Ted Kremenekcfaae762007-08-27 21:54:41 +00001403 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001404 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001405 }
Ted Kremenek73543912007-08-23 21:42:29 +00001406};
Ted Kremenek08176a52007-08-31 21:30:12 +00001407
1408
Ted Kremenek79f0a632008-04-16 21:10:48 +00001409void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001410 if (Helper) {
1411 // special printing for statement-expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001412 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001413 CompoundStmt* Sub = SE->getSubStmt();
1414
1415 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001416 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001417 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001418 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001419 return;
1420 }
1421 }
1422
1423 // special printing for comma expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001424 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001425 if (B->getOpcode() == BinaryOperator::Comma) {
1426 OS << "... , ";
1427 Helper->handledStmt(B->getRHS(),OS);
1428 OS << '\n';
1429 return;
1430 }
1431 }
1432 }
1433
Ted Kremenek79f0a632008-04-16 21:10:48 +00001434 Terminator->printPretty(OS, Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001435
1436 // Expressions need a newline.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001437 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek86afc042007-08-31 22:26:13 +00001438}
1439
Ted Kremenek08176a52007-08-31 21:30:12 +00001440void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1441 StmtPrinterHelper* Helper, bool print_edges) {
1442
1443 if (Helper) Helper->setBlockID(B.getBlockID());
1444
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001445 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001446 OS << "\n [ B" << B.getBlockID();
1447
1448 if (&B == &cfg->getEntry())
1449 OS << " (ENTRY) ]\n";
1450 else if (&B == &cfg->getExit())
1451 OS << " (EXIT) ]\n";
1452 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001453 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001454 else
1455 OS << " ]\n";
1456
Ted Kremenekec055e12007-08-29 23:20:49 +00001457 // Print the label of this block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001458 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001459
1460 if (print_edges)
1461 OS << " ";
1462
Ted Kremenek79f0a632008-04-16 21:10:48 +00001463 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001464 OS << L->getName();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001465 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001466 OS << "case ";
1467 C->getLHS()->printPretty(OS);
1468 if (C->getRHS()) {
1469 OS << " ... ";
1470 C->getRHS()->printPretty(OS);
1471 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001472 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001473 else if (isa<DefaultStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001474 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001475 else
1476 assert(false && "Invalid label statement in CFGBlock.");
1477
Ted Kremenekec055e12007-08-29 23:20:49 +00001478 OS << ":\n";
1479 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001480
Ted Kremenek97f75312007-08-21 21:42:03 +00001481 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001482 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001483
1484 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1485 I != E ; ++I, ++j ) {
1486
Ted Kremenekec055e12007-08-29 23:20:49 +00001487 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001488 if (print_edges)
1489 OS << " ";
1490
1491 OS << std::setw(3) << j << ": ";
1492
1493 if (Helper)
1494 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001495
1496 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001497 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001498
Ted Kremenekec055e12007-08-29 23:20:49 +00001499 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001500 if (B.getTerminator()) {
1501 if (print_edges)
1502 OS << " ";
1503
Ted Kremenekec055e12007-08-29 23:20:49 +00001504 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001505
1506 if (Helper) Helper->setBlockID(-1);
1507
1508 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1509 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001510 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001511 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001512
Ted Kremenekec055e12007-08-29 23:20:49 +00001513 if (print_edges) {
1514 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001515 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001516 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001517
Ted Kremenek08176a52007-08-31 21:30:12 +00001518 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1519 I != E; ++I, ++i) {
1520
1521 if (i == 8 || (i-8) == 0)
1522 OS << "\n ";
1523
Ted Kremenekec055e12007-08-29 23:20:49 +00001524 OS << " B" << (*I)->getBlockID();
1525 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001526
1527 OS << '\n';
1528
1529 // Print the successors of this block.
1530 OS << " Successors (" << B.succ_size() << "):";
1531 i = 0;
1532
1533 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1534 I != E; ++I, ++i) {
1535
1536 if (i == 8 || (i-8) % 10 == 0)
1537 OS << "\n ";
1538
1539 OS << " B" << (*I)->getBlockID();
1540 }
1541
Ted Kremenekec055e12007-08-29 23:20:49 +00001542 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001543 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001544}
1545
1546} // end anonymous namespace
1547
1548/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001549void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001550
1551/// print - A simple pretty printer of a CFG that outputs to an ostream.
1552void CFG::print(std::ostream& OS) const {
1553
1554 StmtPrinterHelper Helper(this);
1555
1556 // Print the entry block.
1557 print_block(OS, this, getEntry(), &Helper, true);
1558
1559 // Iterate through the CFGBlocks and print them one by one.
1560 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1561 // Skip the entry block, because we already printed it.
1562 if (&(*I) == &getEntry() || &(*I) == &getExit())
1563 continue;
1564
1565 print_block(OS, this, *I, &Helper, true);
1566 }
1567
1568 // Print the exit block.
1569 print_block(OS, this, getExit(), &Helper, true);
1570}
1571
1572/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001573void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001574
1575/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1576/// Generally this will only be called from CFG::print.
1577void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1578 StmtPrinterHelper Helper(cfg);
1579 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001580}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001581
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001582/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1583void CFGBlock::printTerminator(std::ostream& OS) const {
1584 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1585 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1586}
1587
Ted Kremenek79f0a632008-04-16 21:10:48 +00001588Expr* CFGBlock::getTerminatorCondition() {
1589
1590 if (!Terminator)
1591 return NULL;
1592
1593 Expr* E = NULL;
1594
1595 switch (Terminator->getStmtClass()) {
1596 default:
1597 break;
1598
1599 case Stmt::ForStmtClass:
1600 E = cast<ForStmt>(Terminator)->getCond();
1601 break;
1602
1603 case Stmt::WhileStmtClass:
1604 E = cast<WhileStmt>(Terminator)->getCond();
1605 break;
1606
1607 case Stmt::DoStmtClass:
1608 E = cast<DoStmt>(Terminator)->getCond();
1609 break;
1610
1611 case Stmt::IfStmtClass:
1612 E = cast<IfStmt>(Terminator)->getCond();
1613 break;
1614
1615 case Stmt::ChooseExprClass:
1616 E = cast<ChooseExpr>(Terminator)->getCond();
1617 break;
1618
1619 case Stmt::IndirectGotoStmtClass:
1620 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1621 break;
1622
1623 case Stmt::SwitchStmtClass:
1624 E = cast<SwitchStmt>(Terminator)->getCond();
1625 break;
1626
1627 case Stmt::ConditionalOperatorClass:
1628 E = cast<ConditionalOperator>(Terminator)->getCond();
1629 break;
1630
1631 case Stmt::BinaryOperatorClass: // '&&' and '||'
1632 E = cast<BinaryOperator>(Terminator)->getLHS();
1633 break;
1634 }
1635
1636 return E ? E->IgnoreParens() : NULL;
1637}
1638
Ted Kremenekbdbd1b52008-05-16 16:06:00 +00001639bool CFGBlock::hasBinaryBranchTerminator() const {
1640
1641 if (!Terminator)
1642 return false;
1643
1644 Expr* E = NULL;
1645
1646 switch (Terminator->getStmtClass()) {
1647 default:
1648 return false;
1649
1650 case Stmt::ForStmtClass:
1651 case Stmt::WhileStmtClass:
1652 case Stmt::DoStmtClass:
1653 case Stmt::IfStmtClass:
1654 case Stmt::ChooseExprClass:
1655 case Stmt::ConditionalOperatorClass:
1656 case Stmt::BinaryOperatorClass:
1657 return true;
1658 }
1659
1660 return E ? E->IgnoreParens() : NULL;
1661}
1662
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001663
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001664//===----------------------------------------------------------------------===//
1665// CFG Graphviz Visualization
1666//===----------------------------------------------------------------------===//
1667
Ted Kremenek08176a52007-08-31 21:30:12 +00001668
1669#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001670static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001671#endif
1672
1673void CFG::viewCFG() const {
1674#ifndef NDEBUG
1675 StmtPrinterHelper H(this);
1676 GraphHelper = &H;
1677 llvm::ViewGraph(this,"CFG");
1678 GraphHelper = NULL;
Ted Kremenek08176a52007-08-31 21:30:12 +00001679#endif
1680}
1681
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001682namespace llvm {
1683template<>
1684struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1685 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1686
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001687#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001688 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001689 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001690 std::string OutStr = Out.str();
1691
1692 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1693
1694 // Process string output to make it nicer...
1695 for (unsigned i = 0; i != OutStr.length(); ++i)
1696 if (OutStr[i] == '\n') { // Left justify
1697 OutStr[i] = '\\';
1698 OutStr.insert(OutStr.begin()+i+1, 'l');
1699 }
1700
1701 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001702#else
1703 return "";
1704#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001705 }
1706};
1707} // end namespace llvm