CFG.cpp revision 556788e816cdb1e5dcf0f0e40c70a95003b2ecf5
1//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
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/Analysis/Support/SaveAndRestore.h"
16#include "clang/Analysis/CFG.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/PrettyPrinter.h"
20#include "llvm/Support/GraphWriter.h"
21#include "llvm/Support/Allocator.h"
22#include "llvm/Support/Format.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/OwningPtr.h"
26
27using namespace clang;
28
29namespace {
30
31static SourceLocation GetEndLoc(Decl* D) {
32  if (VarDecl* VD = dyn_cast<VarDecl>(D))
33    if (Expr* Ex = VD->getInit())
34      return Ex->getSourceRange().getEnd();
35
36  return D->getLocation();
37}
38
39class AddStmtChoice {
40public:
41  enum Kind { NotAlwaysAdd = 0,
42              AlwaysAdd = 1,
43              AsLValueNotAlwaysAdd = 2,
44              AlwaysAddAsLValue = 3 };
45
46  AddStmtChoice(Kind kind) : k(kind) {}
47
48  bool alwaysAdd() const { return (unsigned)k & 0x1; }
49  bool asLValue() const { return k >= AsLValueNotAlwaysAdd; }
50
51private:
52  Kind k;
53};
54
55/// CFGBuilder - This class implements CFG construction from an AST.
56///   The builder is stateful: an instance of the builder should be used to only
57///   construct a single CFG.
58///
59///   Example usage:
60///
61///     CFGBuilder builder;
62///     CFG* cfg = builder.BuildAST(stmt1);
63///
64///  CFG construction is done via a recursive walk of an AST.  We actually parse
65///  the AST in reverse order so that the successor of a basic block is
66///  constructed prior to its predecessor.  This allows us to nicely capture
67///  implicit fall-throughs without extra basic blocks.
68///
69class CFGBuilder {
70  ASTContext *Context;
71  llvm::OwningPtr<CFG> cfg;
72
73  CFGBlock* Block;
74  CFGBlock* Succ;
75  CFGBlock* ContinueTargetBlock;
76  CFGBlock* BreakTargetBlock;
77  CFGBlock* SwitchTerminatedBlock;
78  CFGBlock* DefaultCaseBlock;
79  CFGBlock* TryTerminatedBlock;
80
81  // LabelMap records the mapping from Label expressions to their blocks.
82  typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
83  LabelMapTy LabelMap;
84
85  // A list of blocks that end with a "goto" that must be backpatched to their
86  // resolved targets upon completion of CFG construction.
87  typedef std::vector<CFGBlock*> BackpatchBlocksTy;
88  BackpatchBlocksTy BackpatchBlocks;
89
90  // A list of labels whose address has been taken (for indirect gotos).
91  typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
92  LabelSetTy AddressTakenLabels;
93
94public:
95  explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
96                          Block(NULL), Succ(NULL),
97                          ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
98                          SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
99                          TryTerminatedBlock(NULL) {}
100
101  // buildCFG - Used by external clients to construct the CFG.
102  CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
103                bool pruneTriviallyFalseEdges, bool AddEHEdges,
104                bool AddScopes);
105
106private:
107  // Visitors to walk an AST and construct the CFG.
108  CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
109  CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
110  CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
111  CFGBlock *VisitBreakStmt(BreakStmt *B);
112  CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
113  CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
114  CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
115  CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc);
116  CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
117  CFGBlock *VisitCaseStmt(CaseStmt *C);
118  CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
119  CFGBlock *VisitCompoundStmt(CompoundStmt *C);
120  CFGBlock *VisitConditionalOperator(ConditionalOperator *C, AddStmtChoice asc);
121  CFGBlock *VisitContinueStmt(ContinueStmt *C);
122  CFGBlock *VisitDeclStmt(DeclStmt *DS);
123  CFGBlock *VisitDeclSubExpr(Decl* D);
124  CFGBlock *VisitDefaultStmt(DefaultStmt *D);
125  CFGBlock *VisitDoStmt(DoStmt *D);
126  CFGBlock *VisitForStmt(ForStmt *F);
127  CFGBlock *VisitGotoStmt(GotoStmt* G);
128  CFGBlock *VisitIfStmt(IfStmt *I);
129  CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
130  CFGBlock *VisitLabelStmt(LabelStmt *L);
131  CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
132  CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
133  CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
134  CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
135  CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
136  CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
137  CFGBlock *VisitReturnStmt(ReturnStmt* R);
138  CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
139  CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
140  CFGBlock *VisitSwitchStmt(SwitchStmt *S);
141  CFGBlock *VisitWhileStmt(WhileStmt *W);
142
143  CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
144  CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
145  CFGBlock *VisitChildren(Stmt* S);
146
147  // NYS == Not Yet Supported
148  CFGBlock* NYS() {
149    badCFG = true;
150    return Block;
151  }
152
153  CFGBlock *StartScope(Stmt *S, CFGBlock *B) {
154    if (!AddScopes)
155      return B;
156
157    if (B == 0)
158      B = createBlock();
159    B->StartScope(S, cfg->getBumpVectorContext());
160    return B;
161  }
162
163  void EndScope(Stmt *S) {
164    if (!AddScopes)
165      return;
166
167    if (Block == 0)
168      Block = createBlock();
169    Block->EndScope(S, cfg->getBumpVectorContext());
170  }
171
172  void autoCreateBlock() { if (!Block) Block = createBlock(); }
173  CFGBlock *createBlock(bool add_successor = true);
174  bool FinishBlock(CFGBlock* B);
175  CFGBlock *addStmt(Stmt *S) {
176    return Visit(S, AddStmtChoice::AlwaysAdd);
177  }
178
179  void AppendStmt(CFGBlock *B, Stmt *S,
180                  AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
181    B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue());
182  }
183
184  void AddSuccessor(CFGBlock *B, CFGBlock *S) {
185    B->addSuccessor(S, cfg->getBumpVectorContext());
186  }
187
188  /// TryResult - a class representing a variant over the values
189  ///  'true', 'false', or 'unknown'.  This is returned by TryEvaluateBool,
190  ///  and is used by the CFGBuilder to decide if a branch condition
191  ///  can be decided up front during CFG construction.
192  class TryResult {
193    int X;
194  public:
195    TryResult(bool b) : X(b ? 1 : 0) {}
196    TryResult() : X(-1) {}
197
198    bool isTrue() const { return X == 1; }
199    bool isFalse() const { return X == 0; }
200    bool isKnown() const { return X >= 0; }
201    void negate() {
202      assert(isKnown());
203      X ^= 0x1;
204    }
205  };
206
207  /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
208  /// if we can evaluate to a known value, otherwise return -1.
209  TryResult TryEvaluateBool(Expr *S) {
210    if (!PruneTriviallyFalseEdges)
211      return TryResult();
212
213    Expr::EvalResult Result;
214    if (!S->isTypeDependent() && !S->isValueDependent() &&
215        S->Evaluate(Result, *Context) && Result.Val.isInt())
216      return Result.Val.getInt().getBoolValue();
217
218    return TryResult();
219  }
220
221  bool badCFG;
222
223  // True iff trivially false edges should be pruned from the CFG.
224  bool PruneTriviallyFalseEdges;
225
226  // True iff EH edges on CallExprs should be added to the CFG.
227  bool AddEHEdges;
228
229  // True iff scope start and scope end notes should be added to the CFG.
230  bool AddScopes;
231};
232
233// FIXME: Add support for dependent-sized array types in C++?
234// Does it even make sense to build a CFG for an uninstantiated template?
235static VariableArrayType* FindVA(Type* t) {
236  while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
237    if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
238      if (vat->getSizeExpr())
239        return vat;
240
241    t = vt->getElementType().getTypePtr();
242  }
243
244  return 0;
245}
246
247/// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
248///  arbitrary statement.  Examples include a single expression or a function
249///  body (compound statement).  The ownership of the returned CFG is
250///  transferred to the caller.  If CFG construction fails, this method returns
251///  NULL.
252CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C,
253                          bool pruneTriviallyFalseEdges,
254                          bool addehedges, bool AddScopes) {
255
256  AddEHEdges = addehedges;
257  PruneTriviallyFalseEdges = pruneTriviallyFalseEdges;
258
259  Context = C;
260  assert(cfg.get());
261  if (!Statement)
262    return NULL;
263
264  this->AddScopes = AddScopes;
265  badCFG = false;
266
267  // Create an empty block that will serve as the exit block for the CFG.  Since
268  // this is the first block added to the CFG, it will be implicitly registered
269  // as the exit block.
270  Succ = createBlock();
271  assert(Succ == &cfg->getExit());
272  Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
273
274  // Visit the statements and create the CFG.
275  CFGBlock* B = addStmt(Statement);
276
277  if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
278    // FIXME: Add code for base initializers and member initializers.
279    (void)CD;
280  }
281  if (!B)
282    B = Succ;
283
284  if (B) {
285    // Finalize the last constructed block.  This usually involves reversing the
286    // order of the statements in the block.
287    if (Block) FinishBlock(B);
288
289    // Backpatch the gotos whose label -> block mappings we didn't know when we
290    // encountered them.
291    for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
292         E = BackpatchBlocks.end(); I != E; ++I ) {
293
294      CFGBlock* B = *I;
295      GotoStmt* G = cast<GotoStmt>(B->getTerminator());
296      LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
297
298      // If there is no target for the goto, then we are looking at an
299      // incomplete AST.  Handle this by not registering a successor.
300      if (LI == LabelMap.end()) continue;
301
302      AddSuccessor(B, LI->second);
303    }
304
305    // Add successors to the Indirect Goto Dispatch block (if we have one).
306    if (CFGBlock* B = cfg->getIndirectGotoBlock())
307      for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
308           E = AddressTakenLabels.end(); I != E; ++I ) {
309
310        // Lookup the target block.
311        LabelMapTy::iterator LI = LabelMap.find(*I);
312
313        // If there is no target block that contains label, then we are looking
314        // at an incomplete AST.  Handle this by not registering a successor.
315        if (LI == LabelMap.end()) continue;
316
317        AddSuccessor(B, LI->second);
318      }
319
320    Succ = B;
321  }
322
323  // Create an empty entry block that has no predecessors.
324  cfg->setEntry(createBlock());
325
326  return badCFG ? NULL : cfg.take();
327}
328
329/// createBlock - Used to lazily create blocks that are connected
330///  to the current (global) succcessor.
331CFGBlock* CFGBuilder::createBlock(bool add_successor) {
332  CFGBlock* B = cfg->createBlock();
333  if (add_successor && Succ)
334    AddSuccessor(B, Succ);
335  return B;
336}
337
338/// FinishBlock - "Finalize" the block by checking if we have a bad CFG.
339bool CFGBuilder::FinishBlock(CFGBlock* B) {
340  if (badCFG)
341    return false;
342
343  assert(B);
344  return true;
345}
346
347/// Visit - Walk the subtree of a statement and add extra
348///   blocks for ternary operators, &&, and ||.  We also process "," and
349///   DeclStmts (which may contain nested control-flow).
350CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
351tryAgain:
352  if (!S) {
353    badCFG = true;
354    return 0;
355  }
356  switch (S->getStmtClass()) {
357    default:
358      return VisitStmt(S, asc);
359
360    case Stmt::AddrLabelExprClass:
361      return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
362
363    case Stmt::BinaryOperatorClass:
364      return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
365
366    case Stmt::BlockExprClass:
367      return VisitBlockExpr(cast<BlockExpr>(S), asc);
368
369    case Stmt::BreakStmtClass:
370      return VisitBreakStmt(cast<BreakStmt>(S));
371
372    case Stmt::CallExprClass:
373      return VisitCallExpr(cast<CallExpr>(S), asc);
374
375    case Stmt::CaseStmtClass:
376      return VisitCaseStmt(cast<CaseStmt>(S));
377
378    case Stmt::ChooseExprClass:
379      return VisitChooseExpr(cast<ChooseExpr>(S), asc);
380
381    case Stmt::CompoundStmtClass:
382      return VisitCompoundStmt(cast<CompoundStmt>(S));
383
384    case Stmt::ConditionalOperatorClass:
385      return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
386
387    case Stmt::ContinueStmtClass:
388      return VisitContinueStmt(cast<ContinueStmt>(S));
389
390    case Stmt::CXXCatchStmtClass:
391      return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
392
393    case Stmt::CXXMemberCallExprClass:
394      return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc);
395
396    case Stmt::CXXThrowExprClass:
397      return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
398
399    case Stmt::CXXTryStmtClass:
400      return VisitCXXTryStmt(cast<CXXTryStmt>(S));
401
402    case Stmt::DeclStmtClass:
403      return VisitDeclStmt(cast<DeclStmt>(S));
404
405    case Stmt::DefaultStmtClass:
406      return VisitDefaultStmt(cast<DefaultStmt>(S));
407
408    case Stmt::DoStmtClass:
409      return VisitDoStmt(cast<DoStmt>(S));
410
411    case Stmt::ForStmtClass:
412      return VisitForStmt(cast<ForStmt>(S));
413
414    case Stmt::GotoStmtClass:
415      return VisitGotoStmt(cast<GotoStmt>(S));
416
417    case Stmt::IfStmtClass:
418      return VisitIfStmt(cast<IfStmt>(S));
419
420    case Stmt::IndirectGotoStmtClass:
421      return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
422
423    case Stmt::LabelStmtClass:
424      return VisitLabelStmt(cast<LabelStmt>(S));
425
426    case Stmt::MemberExprClass:
427      return VisitMemberExpr(cast<MemberExpr>(S), asc);
428
429    case Stmt::ObjCAtCatchStmtClass:
430      return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
431
432    case Stmt::ObjCAtSynchronizedStmtClass:
433      return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
434
435    case Stmt::ObjCAtThrowStmtClass:
436      return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
437
438    case Stmt::ObjCAtTryStmtClass:
439      return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
440
441    case Stmt::ObjCForCollectionStmtClass:
442      return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
443
444    case Stmt::ParenExprClass:
445      S = cast<ParenExpr>(S)->getSubExpr();
446      goto tryAgain;
447
448    case Stmt::NullStmtClass:
449      return Block;
450
451    case Stmt::ReturnStmtClass:
452      return VisitReturnStmt(cast<ReturnStmt>(S));
453
454    case Stmt::SizeOfAlignOfExprClass:
455      return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
456
457    case Stmt::StmtExprClass:
458      return VisitStmtExpr(cast<StmtExpr>(S), asc);
459
460    case Stmt::SwitchStmtClass:
461      return VisitSwitchStmt(cast<SwitchStmt>(S));
462
463    case Stmt::WhileStmtClass:
464      return VisitWhileStmt(cast<WhileStmt>(S));
465  }
466}
467
468CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
469  if (asc.alwaysAdd()) {
470    autoCreateBlock();
471    AppendStmt(Block, S, asc);
472  }
473
474  return VisitChildren(S);
475}
476
477/// VisitChildren - Visit the children of a Stmt.
478CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
479  CFGBlock *B = Block;
480  for (Stmt::child_iterator I = Terminator->child_begin(),
481         E = Terminator->child_end(); I != E; ++I) {
482    if (*I) B = Visit(*I);
483  }
484  return B;
485}
486
487CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
488                                         AddStmtChoice asc) {
489  AddressTakenLabels.insert(A->getLabel());
490
491  if (asc.alwaysAdd()) {
492    autoCreateBlock();
493    AppendStmt(Block, A, asc);
494  }
495
496  return Block;
497}
498
499CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
500                                          AddStmtChoice asc) {
501  if (B->isLogicalOp()) { // && or ||
502    CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
503    AppendStmt(ConfluenceBlock, B, asc);
504
505    if (!FinishBlock(ConfluenceBlock))
506      return 0;
507
508    // create the block evaluating the LHS
509    CFGBlock* LHSBlock = createBlock(false);
510    LHSBlock->setTerminator(B);
511
512    // create the block evaluating the RHS
513    Succ = ConfluenceBlock;
514    Block = NULL;
515    CFGBlock* RHSBlock = addStmt(B->getRHS());
516
517    if (RHSBlock) {
518      if (!FinishBlock(RHSBlock))
519        return 0;
520    }
521    else {
522      // Create an empty block for cases where the RHS doesn't require
523      // any explicit statements in the CFG.
524      RHSBlock = createBlock();
525    }
526
527    // See if this is a known constant.
528    TryResult KnownVal = TryEvaluateBool(B->getLHS());
529    if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr))
530      KnownVal.negate();
531
532    // Now link the LHSBlock with RHSBlock.
533    if (B->getOpcode() == BinaryOperator::LOr) {
534      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
535      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
536    } else {
537      assert(B->getOpcode() == BinaryOperator::LAnd);
538      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
539      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
540    }
541
542    // Generate the blocks for evaluating the LHS.
543    Block = LHSBlock;
544    return addStmt(B->getLHS());
545  }
546  else if (B->getOpcode() == BinaryOperator::Comma) { // ,
547    autoCreateBlock();
548    AppendStmt(Block, B, asc);
549    addStmt(B->getRHS());
550    return addStmt(B->getLHS());
551  }
552  else if (B->isAssignmentOp()) {
553    if (asc.alwaysAdd()) {
554      autoCreateBlock();
555      AppendStmt(Block, B, asc);
556    }
557
558    Visit(B->getRHS());
559    return Visit(B->getLHS(), AddStmtChoice::AsLValueNotAlwaysAdd);
560  }
561
562  return VisitStmt(B, asc);
563}
564
565CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
566  if (asc.alwaysAdd()) {
567    autoCreateBlock();
568    AppendStmt(Block, E, asc);
569  }
570  return Block;
571}
572
573CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
574  // "break" is a control-flow statement.  Thus we stop processing the current
575  // block.
576  if (Block && !FinishBlock(Block))
577      return 0;
578
579  // Now create a new block that ends with the break statement.
580  Block = createBlock(false);
581  Block->setTerminator(B);
582
583  // If there is no target for the break, then we are looking at an incomplete
584  // AST.  This means that the CFG cannot be constructed.
585  if (BreakTargetBlock)
586    AddSuccessor(Block, BreakTargetBlock);
587  else
588    badCFG = true;
589
590
591  return Block;
592}
593
594static bool CanThrow(Expr *E) {
595  QualType Ty = E->getType();
596  if (Ty->isFunctionPointerType())
597    Ty = Ty->getAs<PointerType>()->getPointeeType();
598  else if (Ty->isBlockPointerType())
599    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
600
601  const FunctionType *FT = Ty->getAs<FunctionType>();
602  if (FT) {
603    if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
604      if (Proto->hasEmptyExceptionSpec())
605        return false;
606  }
607  return true;
608}
609
610CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
611  // If this is a call to a no-return function, this stops the block here.
612  bool NoReturn = false;
613  if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) {
614    NoReturn = true;
615  }
616
617  bool AddEHEdge = false;
618
619  // Languages without exceptions are assumed to not throw.
620  if (Context->getLangOptions().Exceptions) {
621    if (AddEHEdges)
622      AddEHEdge = true;
623  }
624
625  if (FunctionDecl *FD = C->getDirectCallee()) {
626    if (FD->hasAttr<NoReturnAttr>())
627      NoReturn = true;
628    if (FD->hasAttr<NoThrowAttr>())
629      AddEHEdge = false;
630  }
631
632  if (!CanThrow(C->getCallee()))
633    AddEHEdge = false;
634
635  if (!NoReturn && !AddEHEdge) {
636    if (asc.asLValue())
637      return VisitStmt(C, AddStmtChoice::AlwaysAddAsLValue);
638    else
639      return VisitStmt(C, AddStmtChoice::AlwaysAdd);
640  }
641
642  if (Block) {
643    Succ = Block;
644    if (!FinishBlock(Block))
645      return 0;
646  }
647
648  Block = createBlock(!NoReturn);
649  AppendStmt(Block, C, asc);
650
651  if (NoReturn) {
652    // Wire this to the exit block directly.
653    AddSuccessor(Block, &cfg->getExit());
654  }
655  if (AddEHEdge) {
656    // Add exceptional edges.
657    if (TryTerminatedBlock)
658      AddSuccessor(Block, TryTerminatedBlock);
659    else
660      AddSuccessor(Block, &cfg->getExit());
661  }
662
663  return VisitChildren(C);
664}
665
666CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
667                                      AddStmtChoice asc) {
668  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
669  AppendStmt(ConfluenceBlock, C, asc);
670  if (!FinishBlock(ConfluenceBlock))
671    return 0;
672
673  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
674                       : AddStmtChoice::AlwaysAdd;
675
676  Succ = ConfluenceBlock;
677  Block = NULL;
678  CFGBlock* LHSBlock = Visit(C->getLHS(), asc);
679  if (!FinishBlock(LHSBlock))
680    return 0;
681
682  Succ = ConfluenceBlock;
683  Block = NULL;
684  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
685  if (!FinishBlock(RHSBlock))
686    return 0;
687
688  Block = createBlock(false);
689  // See if this is a known constant.
690  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
691  AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
692  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
693  Block->setTerminator(C);
694  return addStmt(C->getCond());
695}
696
697
698CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
699  EndScope(C);
700
701  CFGBlock* LastBlock = Block;
702
703  for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
704       I != E; ++I ) {
705    LastBlock = addStmt(*I);
706
707    if (badCFG)
708      return NULL;
709  }
710
711  LastBlock = StartScope(C, LastBlock);
712
713  return LastBlock;
714}
715
716CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C,
717                                               AddStmtChoice asc) {
718  // Create the confluence block that will "merge" the results of the ternary
719  // expression.
720  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
721  AppendStmt(ConfluenceBlock, C, asc);
722  if (!FinishBlock(ConfluenceBlock))
723    return 0;
724
725  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
726                       : AddStmtChoice::AlwaysAdd;
727
728  // Create a block for the LHS expression if there is an LHS expression.  A
729  // GCC extension allows LHS to be NULL, causing the condition to be the
730  // value that is returned instead.
731  //  e.g: x ?: y is shorthand for: x ? x : y;
732  Succ = ConfluenceBlock;
733  Block = NULL;
734  CFGBlock* LHSBlock = NULL;
735  if (C->getLHS()) {
736    LHSBlock = Visit(C->getLHS(), asc);
737    if (!FinishBlock(LHSBlock))
738      return 0;
739    Block = NULL;
740  }
741
742  // Create the block for the RHS expression.
743  Succ = ConfluenceBlock;
744  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
745  if (!FinishBlock(RHSBlock))
746    return 0;
747
748  // Create the block that will contain the condition.
749  Block = createBlock(false);
750
751  // See if this is a known constant.
752  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
753  if (LHSBlock) {
754    AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
755  } else {
756    if (KnownVal.isFalse()) {
757      // If we know the condition is false, add NULL as the successor for
758      // the block containing the condition.  In this case, the confluence
759      // block will have just one predecessor.
760      AddSuccessor(Block, 0);
761      assert(ConfluenceBlock->pred_size() == 1);
762    } else {
763      // If we have no LHS expression, add the ConfluenceBlock as a direct
764      // successor for the block containing the condition.  Moreover, we need to
765      // reverse the order of the predecessors in the ConfluenceBlock because
766      // the RHSBlock will have been added to the succcessors already, and we
767      // want the first predecessor to the the block containing the expression
768      // for the case when the ternary expression evaluates to true.
769      AddSuccessor(Block, ConfluenceBlock);
770      assert(ConfluenceBlock->pred_size() == 2);
771      std::reverse(ConfluenceBlock->pred_begin(),
772                   ConfluenceBlock->pred_end());
773    }
774  }
775
776  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
777  Block->setTerminator(C);
778  return addStmt(C->getCond());
779}
780
781CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
782  autoCreateBlock();
783
784  if (DS->isSingleDecl()) {
785    AppendStmt(Block, DS);
786    return VisitDeclSubExpr(DS->getSingleDecl());
787  }
788
789  CFGBlock *B = 0;
790
791  // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
792  typedef llvm::SmallVector<Decl*,10> BufTy;
793  BufTy Buf(DS->decl_begin(), DS->decl_end());
794
795  for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
796    // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
797    unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
798               ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
799
800    // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
801    // automatically freed with the CFG.
802    DeclGroupRef DG(*I);
803    Decl *D = *I;
804    void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
805    DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
806
807    // Append the fake DeclStmt to block.
808    AppendStmt(Block, DSNew);
809    B = VisitDeclSubExpr(D);
810  }
811
812  return B;
813}
814
815/// VisitDeclSubExpr - Utility method to add block-level expressions for
816///  initializers in Decls.
817CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
818  assert(Block);
819
820  VarDecl *VD = dyn_cast<VarDecl>(D);
821
822  if (!VD)
823    return Block;
824
825  Expr *Init = VD->getInit();
826
827  if (Init) {
828    AddStmtChoice::Kind k =
829      VD->getType()->isReferenceType() ? AddStmtChoice::AsLValueNotAlwaysAdd
830                                       : AddStmtChoice::NotAlwaysAdd;
831    Visit(Init, AddStmtChoice(k));
832  }
833
834  // If the type of VD is a VLA, then we must process its size expressions.
835  for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
836       VA = FindVA(VA->getElementType().getTypePtr()))
837    Block = addStmt(VA->getSizeExpr());
838
839  return Block;
840}
841
842CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
843  // We may see an if statement in the middle of a basic block, or it may be the
844  // first statement we are processing.  In either case, we create a new basic
845  // block.  First, we create the blocks for the then...else statements, and
846  // then we create the block containing the if statement.  If we were in the
847  // middle of a block, we stop processing that block.  That block is then the
848  // implicit successor for the "then" and "else" clauses.
849
850  // The block we were proccessing is now finished.  Make it the successor
851  // block.
852  if (Block) {
853    Succ = Block;
854    if (!FinishBlock(Block))
855      return 0;
856  }
857
858  // Process the false branch.
859  CFGBlock* ElseBlock = Succ;
860
861  if (Stmt* Else = I->getElse()) {
862    SaveAndRestore<CFGBlock*> sv(Succ);
863
864    // NULL out Block so that the recursive call to Visit will
865    // create a new basic block.
866    Block = NULL;
867    ElseBlock = addStmt(Else);
868
869    if (!ElseBlock) // Can occur when the Else body has all NullStmts.
870      ElseBlock = sv.get();
871    else if (Block) {
872      if (!FinishBlock(ElseBlock))
873        return 0;
874    }
875  }
876
877  // Process the true branch.
878  CFGBlock* ThenBlock;
879  {
880    Stmt* Then = I->getThen();
881    assert(Then);
882    SaveAndRestore<CFGBlock*> sv(Succ);
883    Block = NULL;
884    ThenBlock = addStmt(Then);
885
886    if (!ThenBlock) {
887      // We can reach here if the "then" body has all NullStmts.
888      // Create an empty block so we can distinguish between true and false
889      // branches in path-sensitive analyses.
890      ThenBlock = createBlock(false);
891      AddSuccessor(ThenBlock, sv.get());
892    } else if (Block) {
893      if (!FinishBlock(ThenBlock))
894        return 0;
895    }
896  }
897
898  // Now create a new block containing the if statement.
899  Block = createBlock(false);
900
901  // Set the terminator of the new block to the If statement.
902  Block->setTerminator(I);
903
904  // See if this is a known constant.
905  const TryResult &KnownVal = TryEvaluateBool(I->getCond());
906
907  // Now add the successors.
908  AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
909  AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
910
911  // Add the condition as the last statement in the new block.  This may create
912  // new blocks as the condition may contain control-flow.  Any newly created
913  // blocks will be pointed to be "Block".
914  Block = addStmt(I->getCond());
915
916  // Finally, if the IfStmt contains a condition variable, add both the IfStmt
917  // and the condition variable initialization to the CFG.
918  if (VarDecl *VD = I->getConditionVariable()) {
919    if (Expr *Init = VD->getInit()) {
920      autoCreateBlock();
921      AppendStmt(Block, I, AddStmtChoice::AlwaysAdd);
922      addStmt(Init);
923    }
924  }
925
926  return Block;
927}
928
929
930CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
931  // If we were in the middle of a block we stop processing that block.
932  //
933  // NOTE: If a "return" appears in the middle of a block, this means that the
934  //       code afterwards is DEAD (unreachable).  We still keep a basic block
935  //       for that code; a simple "mark-and-sweep" from the entry block will be
936  //       able to report such dead blocks.
937  if (Block)
938    FinishBlock(Block);
939
940  // Create the new block.
941  Block = createBlock(false);
942
943  // The Exit block is the only successor.
944  AddSuccessor(Block, &cfg->getExit());
945
946  // Add the return statement to the block.  This may create new blocks if R
947  // contains control-flow (short-circuit operations).
948  return VisitStmt(R, AddStmtChoice::AlwaysAdd);
949}
950
951CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
952  // Get the block of the labeled statement.  Add it to our map.
953  addStmt(L->getSubStmt());
954  CFGBlock* LabelBlock = Block;
955
956  if (!LabelBlock)              // This can happen when the body is empty, i.e.
957    LabelBlock = createBlock(); // scopes that only contains NullStmts.
958
959  assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
960  LabelMap[ L ] = LabelBlock;
961
962  // Labels partition blocks, so this is the end of the basic block we were
963  // processing (L is the block's label).  Because this is label (and we have
964  // already processed the substatement) there is no extra control-flow to worry
965  // about.
966  LabelBlock->setLabel(L);
967  if (!FinishBlock(LabelBlock))
968    return 0;
969
970  // We set Block to NULL to allow lazy creation of a new block (if necessary);
971  Block = NULL;
972
973  // This block is now the implicit successor of other blocks.
974  Succ = LabelBlock;
975
976  return LabelBlock;
977}
978
979CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
980  // Goto is a control-flow statement.  Thus we stop processing the current
981  // block and create a new one.
982  if (Block)
983    FinishBlock(Block);
984
985  Block = createBlock(false);
986  Block->setTerminator(G);
987
988  // If we already know the mapping to the label block add the successor now.
989  LabelMapTy::iterator I = LabelMap.find(G->getLabel());
990
991  if (I == LabelMap.end())
992    // We will need to backpatch this block later.
993    BackpatchBlocks.push_back(Block);
994  else
995    AddSuccessor(Block, I->second);
996
997  return Block;
998}
999
1000CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
1001  CFGBlock* LoopSuccessor = NULL;
1002
1003  // "for" is a control-flow statement.  Thus we stop processing the current
1004  // block.
1005  if (Block) {
1006    if (!FinishBlock(Block))
1007      return 0;
1008    LoopSuccessor = Block;
1009  } else
1010    LoopSuccessor = Succ;
1011
1012  // Save the current value for the break targets.
1013  // All breaks should go to the code following the loop.
1014  SaveAndRestore<CFGBlock*> save_break(BreakTargetBlock);
1015  BreakTargetBlock = LoopSuccessor;
1016
1017  // Because of short-circuit evaluation, the condition of the loop can span
1018  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1019  // evaluate the condition.
1020  CFGBlock* ExitConditionBlock = createBlock(false);
1021  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1022
1023  // Set the terminator for the "exit" condition block.
1024  ExitConditionBlock->setTerminator(F);
1025
1026  // Now add the actual condition to the condition block.  Because the condition
1027  // itself may contain control-flow, new blocks may be created.
1028  if (Stmt* C = F->getCond()) {
1029    Block = ExitConditionBlock;
1030    EntryConditionBlock = addStmt(C);
1031    assert(Block == EntryConditionBlock);
1032
1033    // If this block contains a condition variable, add both the condition
1034    // variable and initializer to the CFG.
1035    if (VarDecl *VD = F->getConditionVariable()) {
1036      if (Expr *Init = VD->getInit()) {
1037        autoCreateBlock();
1038        AppendStmt(Block, F, AddStmtChoice::AlwaysAdd);
1039        EntryConditionBlock = addStmt(Init);
1040        assert(Block == EntryConditionBlock);
1041      }
1042    }
1043
1044    if (Block) {
1045      if (!FinishBlock(EntryConditionBlock))
1046        return 0;
1047    }
1048  }
1049
1050  // The condition block is the implicit successor for the loop body as well as
1051  // any code above the loop.
1052  Succ = EntryConditionBlock;
1053
1054  // See if this is a known constant.
1055  TryResult KnownVal(true);
1056
1057  if (F->getCond())
1058    KnownVal = TryEvaluateBool(F->getCond());
1059
1060  // Now create the loop body.
1061  {
1062    assert(F->getBody());
1063
1064   // Save the current values for Block, Succ, and continue targets.
1065   SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1066      save_continue(ContinueTargetBlock);
1067
1068    // Create a new block to contain the (bottom) of the loop body.
1069    Block = NULL;
1070
1071    if (Stmt* I = F->getInc()) {
1072      // Generate increment code in its own basic block.  This is the target of
1073      // continue statements.
1074      Succ = addStmt(I);
1075    } else {
1076      // No increment code.  Create a special, empty, block that is used as the
1077      // target block for "looping back" to the start of the loop.
1078      assert(Succ == EntryConditionBlock);
1079      Succ = createBlock();
1080    }
1081
1082    // Finish up the increment (or empty) block if it hasn't been already.
1083    if (Block) {
1084      assert(Block == Succ);
1085      if (!FinishBlock(Block))
1086        return 0;
1087      Block = 0;
1088    }
1089
1090    ContinueTargetBlock = Succ;
1091
1092    // The starting block for the loop increment is the block that should
1093    // represent the 'loop target' for looping back to the start of the loop.
1094    ContinueTargetBlock->setLoopTarget(F);
1095
1096    // Now populate the body block, and in the process create new blocks as we
1097    // walk the body of the loop.
1098    CFGBlock* BodyBlock = addStmt(F->getBody());
1099
1100    if (!BodyBlock)
1101      BodyBlock = ContinueTargetBlock; // can happen for "for (...;...;...) ;"
1102    else if (Block && !FinishBlock(BodyBlock))
1103      return 0;
1104
1105    // This new body block is a successor to our "exit" condition block.
1106    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1107  }
1108
1109  // Link up the condition block with the code that follows the loop.  (the
1110  // false branch).
1111  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1112
1113  // If the loop contains initialization, create a new block for those
1114  // statements.  This block can also contain statements that precede the loop.
1115  if (Stmt* I = F->getInit()) {
1116    Block = createBlock();
1117    return addStmt(I);
1118  } else {
1119    // There is no loop initialization.  We are thus basically a while loop.
1120    // NULL out Block to force lazy block construction.
1121    Block = NULL;
1122    Succ = EntryConditionBlock;
1123    return EntryConditionBlock;
1124  }
1125}
1126
1127CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
1128  if (asc.alwaysAdd()) {
1129    autoCreateBlock();
1130    AppendStmt(Block, M, asc);
1131  }
1132  return Visit(M->getBase(),
1133               M->isArrow() ? AddStmtChoice::NotAlwaysAdd
1134                            : AddStmtChoice::AsLValueNotAlwaysAdd);
1135}
1136
1137CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1138  // Objective-C fast enumeration 'for' statements:
1139  //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1140  //
1141  //  for ( Type newVariable in collection_expression ) { statements }
1142  //
1143  //  becomes:
1144  //
1145  //   prologue:
1146  //     1. collection_expression
1147  //     T. jump to loop_entry
1148  //   loop_entry:
1149  //     1. side-effects of element expression
1150  //     1. ObjCForCollectionStmt [performs binding to newVariable]
1151  //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
1152  //   TB:
1153  //     statements
1154  //     T. jump to loop_entry
1155  //   FB:
1156  //     what comes after
1157  //
1158  //  and
1159  //
1160  //  Type existingItem;
1161  //  for ( existingItem in expression ) { statements }
1162  //
1163  //  becomes:
1164  //
1165  //   the same with newVariable replaced with existingItem; the binding works
1166  //   the same except that for one ObjCForCollectionStmt::getElement() returns
1167  //   a DeclStmt and the other returns a DeclRefExpr.
1168  //
1169
1170  CFGBlock* LoopSuccessor = 0;
1171
1172  if (Block) {
1173    if (!FinishBlock(Block))
1174      return 0;
1175    LoopSuccessor = Block;
1176    Block = 0;
1177  } else
1178    LoopSuccessor = Succ;
1179
1180  // Build the condition blocks.
1181  CFGBlock* ExitConditionBlock = createBlock(false);
1182  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1183
1184  // Set the terminator for the "exit" condition block.
1185  ExitConditionBlock->setTerminator(S);
1186
1187  // The last statement in the block should be the ObjCForCollectionStmt, which
1188  // performs the actual binding to 'element' and determines if there are any
1189  // more items in the collection.
1190  AppendStmt(ExitConditionBlock, S);
1191  Block = ExitConditionBlock;
1192
1193  // Walk the 'element' expression to see if there are any side-effects.  We
1194  // generate new blocks as necesary.  We DON'T add the statement by default to
1195  // the CFG unless it contains control-flow.
1196  EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1197  if (Block) {
1198    if (!FinishBlock(EntryConditionBlock))
1199      return 0;
1200    Block = 0;
1201  }
1202
1203  // The condition block is the implicit successor for the loop body as well as
1204  // any code above the loop.
1205  Succ = EntryConditionBlock;
1206
1207  // Now create the true branch.
1208  {
1209    // Save the current values for Succ, continue and break targets.
1210    SaveAndRestore<CFGBlock*> save_Succ(Succ),
1211      save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
1212
1213    BreakTargetBlock = LoopSuccessor;
1214    ContinueTargetBlock = EntryConditionBlock;
1215
1216    CFGBlock* BodyBlock = addStmt(S->getBody());
1217
1218    if (!BodyBlock)
1219      BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1220    else if (Block) {
1221      if (!FinishBlock(BodyBlock))
1222        return 0;
1223    }
1224
1225    // This new body block is a successor to our "exit" condition block.
1226    AddSuccessor(ExitConditionBlock, BodyBlock);
1227  }
1228
1229  // Link up the condition block with the code that follows the loop.
1230  // (the false branch).
1231  AddSuccessor(ExitConditionBlock, LoopSuccessor);
1232
1233  // Now create a prologue block to contain the collection expression.
1234  Block = createBlock();
1235  return addStmt(S->getCollection());
1236}
1237
1238CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1239  // FIXME: Add locking 'primitives' to CFG for @synchronized.
1240
1241  // Inline the body.
1242  CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1243
1244  // The sync body starts its own basic block.  This makes it a little easier
1245  // for diagnostic clients.
1246  if (SyncBlock) {
1247    if (!FinishBlock(SyncBlock))
1248      return 0;
1249
1250    Block = 0;
1251    Succ = SyncBlock;
1252  }
1253
1254  // Inline the sync expression.
1255  return addStmt(S->getSynchExpr());
1256}
1257
1258CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1259  // FIXME
1260  return NYS();
1261}
1262
1263CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1264  CFGBlock* LoopSuccessor = NULL;
1265
1266  // "while" is a control-flow statement.  Thus we stop processing the current
1267  // block.
1268  if (Block) {
1269    if (!FinishBlock(Block))
1270      return 0;
1271    LoopSuccessor = Block;
1272  } else
1273    LoopSuccessor = Succ;
1274
1275  // Because of short-circuit evaluation, the condition of the loop can span
1276  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1277  // evaluate the condition.
1278  CFGBlock* ExitConditionBlock = createBlock(false);
1279  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1280
1281  // Set the terminator for the "exit" condition block.
1282  ExitConditionBlock->setTerminator(W);
1283
1284  // Now add the actual condition to the condition block.  Because the condition
1285  // itself may contain control-flow, new blocks may be created.  Thus we update
1286  // "Succ" after adding the condition.
1287  if (Stmt* C = W->getCond()) {
1288    Block = ExitConditionBlock;
1289    EntryConditionBlock = addStmt(C);
1290    assert(Block == EntryConditionBlock);
1291
1292    // If this block contains a condition variable, add both the condition
1293    // variable and initializer to the CFG.
1294    if (VarDecl *VD = W->getConditionVariable()) {
1295      if (Expr *Init = VD->getInit()) {
1296        autoCreateBlock();
1297        AppendStmt(Block, W, AddStmtChoice::AlwaysAdd);
1298        EntryConditionBlock = addStmt(Init);
1299        assert(Block == EntryConditionBlock);
1300      }
1301    }
1302
1303    if (Block) {
1304      if (!FinishBlock(EntryConditionBlock))
1305        return 0;
1306    }
1307  }
1308
1309  // The condition block is the implicit successor for the loop body as well as
1310  // any code above the loop.
1311  Succ = EntryConditionBlock;
1312
1313  // See if this is a known constant.
1314  const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1315
1316  // Process the loop body.
1317  {
1318    assert(W->getBody());
1319
1320    // Save the current values for Block, Succ, and continue and break targets
1321    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1322                              save_continue(ContinueTargetBlock),
1323                              save_break(BreakTargetBlock);
1324
1325    // Create an empty block to represent the transition block for looping back
1326    // to the head of the loop.
1327    Block = 0;
1328    assert(Succ == EntryConditionBlock);
1329    Succ = createBlock();
1330    Succ->setLoopTarget(W);
1331    ContinueTargetBlock = Succ;
1332
1333    // All breaks should go to the code following the loop.
1334    BreakTargetBlock = LoopSuccessor;
1335
1336    // NULL out Block to force lazy instantiation of blocks for the body.
1337    Block = NULL;
1338
1339    // Create the body.  The returned block is the entry to the loop body.
1340    CFGBlock* BodyBlock = addStmt(W->getBody());
1341
1342    if (!BodyBlock)
1343      BodyBlock = ContinueTargetBlock; // can happen for "while(...) ;"
1344    else if (Block) {
1345      if (!FinishBlock(BodyBlock))
1346        return 0;
1347    }
1348
1349    // Add the loop body entry as a successor to the condition.
1350    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1351  }
1352
1353  // Link up the condition block with the code that follows the loop.  (the
1354  // false branch).
1355  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1356
1357  // There can be no more statements in the condition block since we loop back
1358  // to this block.  NULL out Block to force lazy creation of another block.
1359  Block = NULL;
1360
1361  // Return the condition block, which is the dominating block for the loop.
1362  Succ = EntryConditionBlock;
1363  return EntryConditionBlock;
1364}
1365
1366
1367CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1368  // FIXME: For now we pretend that @catch and the code it contains does not
1369  //  exit.
1370  return Block;
1371}
1372
1373CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1374  // FIXME: This isn't complete.  We basically treat @throw like a return
1375  //  statement.
1376
1377  // If we were in the middle of a block we stop processing that block.
1378  if (Block && !FinishBlock(Block))
1379    return 0;
1380
1381  // Create the new block.
1382  Block = createBlock(false);
1383
1384  // The Exit block is the only successor.
1385  AddSuccessor(Block, &cfg->getExit());
1386
1387  // Add the statement to the block.  This may create new blocks if S contains
1388  // control-flow (short-circuit operations).
1389  return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1390}
1391
1392CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1393  // If we were in the middle of a block we stop processing that block.
1394  if (Block && !FinishBlock(Block))
1395    return 0;
1396
1397  // Create the new block.
1398  Block = createBlock(false);
1399
1400  if (TryTerminatedBlock)
1401    // The current try statement is the only successor.
1402    AddSuccessor(Block, TryTerminatedBlock);
1403  else
1404    // otherwise the Exit block is the only successor.
1405    AddSuccessor(Block, &cfg->getExit());
1406
1407  // Add the statement to the block.  This may create new blocks if S contains
1408  // control-flow (short-circuit operations).
1409  return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1410}
1411
1412CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1413  CFGBlock* LoopSuccessor = NULL;
1414
1415  // "do...while" is a control-flow statement.  Thus we stop processing the
1416  // current block.
1417  if (Block) {
1418    if (!FinishBlock(Block))
1419      return 0;
1420    LoopSuccessor = Block;
1421  } else
1422    LoopSuccessor = Succ;
1423
1424  // Because of short-circuit evaluation, the condition of the loop can span
1425  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1426  // evaluate the condition.
1427  CFGBlock* ExitConditionBlock = createBlock(false);
1428  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1429
1430  // Set the terminator for the "exit" condition block.
1431  ExitConditionBlock->setTerminator(D);
1432
1433  // Now add the actual condition to the condition block.  Because the condition
1434  // itself may contain control-flow, new blocks may be created.
1435  if (Stmt* C = D->getCond()) {
1436    Block = ExitConditionBlock;
1437    EntryConditionBlock = addStmt(C);
1438    if (Block) {
1439      if (!FinishBlock(EntryConditionBlock))
1440        return 0;
1441    }
1442  }
1443
1444  // The condition block is the implicit successor for the loop body.
1445  Succ = EntryConditionBlock;
1446
1447  // See if this is a known constant.
1448  const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1449
1450  // Process the loop body.
1451  CFGBlock* BodyBlock = NULL;
1452  {
1453    assert(D->getBody());
1454
1455    // Save the current values for Block, Succ, and continue and break targets
1456    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1457      save_continue(ContinueTargetBlock),
1458      save_break(BreakTargetBlock);
1459
1460    // All continues within this loop should go to the condition block
1461    ContinueTargetBlock = EntryConditionBlock;
1462
1463    // All breaks should go to the code following the loop.
1464    BreakTargetBlock = LoopSuccessor;
1465
1466    // NULL out Block to force lazy instantiation of blocks for the body.
1467    Block = NULL;
1468
1469    // Create the body.  The returned block is the entry to the loop body.
1470    BodyBlock = addStmt(D->getBody());
1471
1472    if (!BodyBlock)
1473      BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1474    else if (Block) {
1475      if (!FinishBlock(BodyBlock))
1476        return 0;
1477    }
1478
1479    // Add an intermediate block between the BodyBlock and the
1480    // ExitConditionBlock to represent the "loop back" transition.  Create an
1481    // empty block to represent the transition block for looping back to the
1482    // head of the loop.
1483    // FIXME: Can we do this more efficiently without adding another block?
1484    Block = NULL;
1485    Succ = BodyBlock;
1486    CFGBlock *LoopBackBlock = createBlock();
1487    LoopBackBlock->setLoopTarget(D);
1488
1489    // Add the loop body entry as a successor to the condition.
1490    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : LoopBackBlock);
1491  }
1492
1493  // Link up the condition block with the code that follows the loop.
1494  // (the false branch).
1495  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1496
1497  // There can be no more statements in the body block(s) since we loop back to
1498  // the body.  NULL out Block to force lazy creation of another block.
1499  Block = NULL;
1500
1501  // Return the loop body, which is the dominating block for the loop.
1502  Succ = BodyBlock;
1503  return BodyBlock;
1504}
1505
1506CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1507  // "continue" is a control-flow statement.  Thus we stop processing the
1508  // current block.
1509  if (Block && !FinishBlock(Block))
1510      return 0;
1511
1512  // Now create a new block that ends with the continue statement.
1513  Block = createBlock(false);
1514  Block->setTerminator(C);
1515
1516  // If there is no target for the continue, then we are looking at an
1517  // incomplete AST.  This means the CFG cannot be constructed.
1518  if (ContinueTargetBlock)
1519    AddSuccessor(Block, ContinueTargetBlock);
1520  else
1521    badCFG = true;
1522
1523  return Block;
1524}
1525
1526CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1527                                             AddStmtChoice asc) {
1528
1529  if (asc.alwaysAdd()) {
1530    autoCreateBlock();
1531    AppendStmt(Block, E);
1532  }
1533
1534  // VLA types have expressions that must be evaluated.
1535  if (E->isArgumentType()) {
1536    for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1537         VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1538      addStmt(VA->getSizeExpr());
1539  }
1540
1541  return Block;
1542}
1543
1544/// VisitStmtExpr - Utility method to handle (nested) statement
1545///  expressions (a GCC extension).
1546CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
1547  if (asc.alwaysAdd()) {
1548    autoCreateBlock();
1549    AppendStmt(Block, SE);
1550  }
1551  return VisitCompoundStmt(SE->getSubStmt());
1552}
1553
1554CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1555  // "switch" is a control-flow statement.  Thus we stop processing the current
1556  // block.
1557  CFGBlock* SwitchSuccessor = NULL;
1558
1559  if (Block) {
1560    if (!FinishBlock(Block))
1561      return 0;
1562    SwitchSuccessor = Block;
1563  } else SwitchSuccessor = Succ;
1564
1565  // Save the current "switch" context.
1566  SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1567                            save_break(BreakTargetBlock),
1568                            save_default(DefaultCaseBlock);
1569
1570  // Set the "default" case to be the block after the switch statement.  If the
1571  // switch statement contains a "default:", this value will be overwritten with
1572  // the block for that code.
1573  DefaultCaseBlock = SwitchSuccessor;
1574
1575  // Create a new block that will contain the switch statement.
1576  SwitchTerminatedBlock = createBlock(false);
1577
1578  // Now process the switch body.  The code after the switch is the implicit
1579  // successor.
1580  Succ = SwitchSuccessor;
1581  BreakTargetBlock = SwitchSuccessor;
1582
1583  // When visiting the body, the case statements should automatically get linked
1584  // up to the switch.  We also don't keep a pointer to the body, since all
1585  // control-flow from the switch goes to case/default statements.
1586  assert(Terminator->getBody() && "switch must contain a non-NULL body");
1587  Block = NULL;
1588  CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1589  if (Block) {
1590    if (!FinishBlock(BodyBlock))
1591      return 0;
1592  }
1593
1594  // If we have no "default:" case, the default transition is to the code
1595  // following the switch body.
1596  AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
1597
1598  // Add the terminator and condition in the switch block.
1599  SwitchTerminatedBlock->setTerminator(Terminator);
1600  assert(Terminator->getCond() && "switch condition must be non-NULL");
1601  Block = SwitchTerminatedBlock;
1602  Block = addStmt(Terminator->getCond());
1603
1604  // Finally, if the SwitchStmt contains a condition variable, add both the
1605  // SwitchStmt and the condition variable initialization to the CFG.
1606  if (VarDecl *VD = Terminator->getConditionVariable()) {
1607    if (Expr *Init = VD->getInit()) {
1608      autoCreateBlock();
1609      AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd);
1610      addStmt(Init);
1611    }
1612  }
1613
1614  return Block;
1615}
1616
1617CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1618  // CaseStmts are essentially labels, so they are the first statement in a
1619  // block.
1620  CFGBlock *TopBlock = 0, *LastBlock = 0;
1621
1622  if (Stmt *Sub = CS->getSubStmt()) {
1623    // For deeply nested chains of CaseStmts, instead of doing a recursion
1624    // (which can blow out the stack), manually unroll and create blocks
1625    // along the way.
1626    while (isa<CaseStmt>(Sub)) {
1627      CFGBlock *CurrentBlock = createBlock(false);
1628      CurrentBlock->setLabel(CS);
1629
1630      if (TopBlock)
1631        AddSuccessor(LastBlock, CurrentBlock);
1632      else
1633        TopBlock = CurrentBlock;
1634
1635      AddSuccessor(SwitchTerminatedBlock, CurrentBlock);
1636      LastBlock = CurrentBlock;
1637
1638      CS = cast<CaseStmt>(Sub);
1639      Sub = CS->getSubStmt();
1640    }
1641
1642    addStmt(Sub);
1643  }
1644
1645  CFGBlock* CaseBlock = Block;
1646  if (!CaseBlock)
1647    CaseBlock = createBlock();
1648
1649  // Cases statements partition blocks, so this is the top of the basic block we
1650  // were processing (the "case XXX:" is the label).
1651  CaseBlock->setLabel(CS);
1652
1653  if (!FinishBlock(CaseBlock))
1654    return 0;
1655
1656  // Add this block to the list of successors for the block with the switch
1657  // statement.
1658  assert(SwitchTerminatedBlock);
1659  AddSuccessor(SwitchTerminatedBlock, CaseBlock);
1660
1661  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1662  Block = NULL;
1663
1664  if (TopBlock) {
1665    AddSuccessor(LastBlock, CaseBlock);
1666    Succ = TopBlock;
1667  }
1668  else {
1669    // This block is now the implicit successor of other blocks.
1670    Succ = CaseBlock;
1671  }
1672
1673  return Succ;
1674}
1675
1676CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1677  if (Terminator->getSubStmt())
1678    addStmt(Terminator->getSubStmt());
1679
1680  DefaultCaseBlock = Block;
1681
1682  if (!DefaultCaseBlock)
1683    DefaultCaseBlock = createBlock();
1684
1685  // Default statements partition blocks, so this is the top of the basic block
1686  // we were processing (the "default:" is the label).
1687  DefaultCaseBlock->setLabel(Terminator);
1688
1689  if (!FinishBlock(DefaultCaseBlock))
1690    return 0;
1691
1692  // Unlike case statements, we don't add the default block to the successors
1693  // for the switch statement immediately.  This is done when we finish
1694  // processing the switch statement.  This allows for the default case
1695  // (including a fall-through to the code after the switch statement) to always
1696  // be the last successor of a switch-terminated block.
1697
1698  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1699  Block = NULL;
1700
1701  // This block is now the implicit successor of other blocks.
1702  Succ = DefaultCaseBlock;
1703
1704  return DefaultCaseBlock;
1705}
1706
1707CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
1708  // "try"/"catch" is a control-flow statement.  Thus we stop processing the
1709  // current block.
1710  CFGBlock* TrySuccessor = NULL;
1711
1712  if (Block) {
1713    if (!FinishBlock(Block))
1714      return 0;
1715    TrySuccessor = Block;
1716  } else TrySuccessor = Succ;
1717
1718  CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
1719
1720  // Create a new block that will contain the try statement.
1721  CFGBlock *NewTryTerminatedBlock = createBlock(false);
1722  // Add the terminator in the try block.
1723  NewTryTerminatedBlock->setTerminator(Terminator);
1724
1725  bool HasCatchAll = false;
1726  for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
1727    // The code after the try is the implicit successor.
1728    Succ = TrySuccessor;
1729    CXXCatchStmt *CS = Terminator->getHandler(h);
1730    if (CS->getExceptionDecl() == 0) {
1731      HasCatchAll = true;
1732    }
1733    Block = NULL;
1734    CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
1735    if (CatchBlock == 0)
1736      return 0;
1737    // Add this block to the list of successors for the block with the try
1738    // statement.
1739    AddSuccessor(NewTryTerminatedBlock, CatchBlock);
1740  }
1741  if (!HasCatchAll) {
1742    if (PrevTryTerminatedBlock)
1743      AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
1744    else
1745      AddSuccessor(NewTryTerminatedBlock, &cfg->getExit());
1746  }
1747
1748  // The code after the try is the implicit successor.
1749  Succ = TrySuccessor;
1750
1751  // Save the current "try" context.
1752  SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
1753  TryTerminatedBlock = NewTryTerminatedBlock;
1754
1755  assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
1756  Block = NULL;
1757  Block = addStmt(Terminator->getTryBlock());
1758  return Block;
1759}
1760
1761CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
1762  // CXXCatchStmt are treated like labels, so they are the first statement in a
1763  // block.
1764
1765  if (CS->getHandlerBlock())
1766    addStmt(CS->getHandlerBlock());
1767
1768  CFGBlock* CatchBlock = Block;
1769  if (!CatchBlock)
1770    CatchBlock = createBlock();
1771
1772  CatchBlock->setLabel(CS);
1773
1774  if (!FinishBlock(CatchBlock))
1775    return 0;
1776
1777  // We set Block to NULL to allow lazy creation of a new block (if necessary)
1778  Block = NULL;
1779
1780  return CatchBlock;
1781}
1782
1783CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C,
1784                                             AddStmtChoice asc) {
1785  AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1786                                         : AddStmtChoice::AlwaysAdd;
1787  autoCreateBlock();
1788  AppendStmt(Block, C, AddStmtChoice(K));
1789  return VisitChildren(C);
1790}
1791
1792CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1793  // Lazily create the indirect-goto dispatch block if there isn't one already.
1794  CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1795
1796  if (!IBlock) {
1797    IBlock = createBlock(false);
1798    cfg->setIndirectGotoBlock(IBlock);
1799  }
1800
1801  // IndirectGoto is a control-flow statement.  Thus we stop processing the
1802  // current block and create a new one.
1803  if (Block && !FinishBlock(Block))
1804    return 0;
1805
1806  Block = createBlock(false);
1807  Block->setTerminator(I);
1808  AddSuccessor(Block, IBlock);
1809  return addStmt(I->getTarget());
1810}
1811
1812} // end anonymous namespace
1813
1814/// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
1815///  no successors or predecessors.  If this is the first block created in the
1816///  CFG, it is automatically set to be the Entry and Exit of the CFG.
1817CFGBlock* CFG::createBlock() {
1818  bool first_block = begin() == end();
1819
1820  // Create the block.
1821  CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
1822  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
1823  Blocks.push_back(Mem, BlkBVC);
1824
1825  // If this is the first block, set it as the Entry and Exit.
1826  if (first_block)
1827    Entry = Exit = &back();
1828
1829  // Return the block.
1830  return &back();
1831}
1832
1833/// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
1834///  CFG is returned to the caller.
1835CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
1836                   bool PruneTriviallyFalse,
1837                   bool AddEHEdges, bool AddScopes) {
1838  CFGBuilder Builder;
1839  return Builder.buildCFG(D, Statement, C, PruneTriviallyFalse,
1840                          AddEHEdges, AddScopes);
1841}
1842
1843//===----------------------------------------------------------------------===//
1844// CFG: Queries for BlkExprs.
1845//===----------------------------------------------------------------------===//
1846
1847namespace {
1848  typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1849}
1850
1851static void FindSubExprAssignments(Stmt *S,
1852                                   llvm::SmallPtrSet<Expr*,50>& Set) {
1853  if (!S)
1854    return;
1855
1856  for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1857    Stmt *child = *I;
1858    if (!child)
1859      continue;
1860
1861    if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
1862      if (B->isAssignmentOp()) Set.insert(B);
1863
1864    FindSubExprAssignments(child, Set);
1865  }
1866}
1867
1868static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1869  BlkExprMapTy* M = new BlkExprMapTy();
1870
1871  // Look for assignments that are used as subexpressions.  These are the only
1872  // assignments that we want to *possibly* register as a block-level
1873  // expression.  Basically, if an assignment occurs both in a subexpression and
1874  // at the block-level, it is a block-level expression.
1875  llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1876
1877  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1878    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1879      FindSubExprAssignments(*BI, SubExprAssignments);
1880
1881  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1882
1883    // Iterate over the statements again on identify the Expr* and Stmt* at the
1884    // block-level that are block-level expressions.
1885
1886    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1887      if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1888
1889        if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1890          // Assignment expressions that are not nested within another
1891          // expression are really "statements" whose value is never used by
1892          // another expression.
1893          if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1894            continue;
1895        } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1896          // Special handling for statement expressions.  The last statement in
1897          // the statement expression is also a block-level expr.
1898          const CompoundStmt* C = Terminator->getSubStmt();
1899          if (!C->body_empty()) {
1900            unsigned x = M->size();
1901            (*M)[C->body_back()] = x;
1902          }
1903        }
1904
1905        unsigned x = M->size();
1906        (*M)[Exp] = x;
1907      }
1908
1909    // Look at terminators.  The condition is a block-level expression.
1910
1911    Stmt* S = (*I)->getTerminatorCondition();
1912
1913    if (S && M->find(S) == M->end()) {
1914        unsigned x = M->size();
1915        (*M)[S] = x;
1916    }
1917  }
1918
1919  return M;
1920}
1921
1922CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1923  assert(S != NULL);
1924  if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1925
1926  BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1927  BlkExprMapTy::iterator I = M->find(S);
1928  return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
1929}
1930
1931unsigned CFG::getNumBlkExprs() {
1932  if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1933    return M->size();
1934  else {
1935    // We assume callers interested in the number of BlkExprs will want
1936    // the map constructed if it doesn't already exist.
1937    BlkExprMap = (void*) PopulateBlkExprMap(*this);
1938    return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1939  }
1940}
1941
1942//===----------------------------------------------------------------------===//
1943// Cleanup: CFG dstor.
1944//===----------------------------------------------------------------------===//
1945
1946CFG::~CFG() {
1947  delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1948}
1949
1950//===----------------------------------------------------------------------===//
1951// CFG pretty printing
1952//===----------------------------------------------------------------------===//
1953
1954namespace {
1955
1956class StmtPrinterHelper : public PrinterHelper  {
1957  typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1958  StmtMapTy StmtMap;
1959  signed CurrentBlock;
1960  unsigned CurrentStmt;
1961  const LangOptions &LangOpts;
1962public:
1963
1964  StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1965    : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1966    for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1967      unsigned j = 1;
1968      for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
1969           BI != BEnd; ++BI, ++j )
1970        StmtMap[*BI] = std::make_pair((*I)->getBlockID(),j);
1971      }
1972  }
1973
1974  virtual ~StmtPrinterHelper() {}
1975
1976  const LangOptions &getLangOpts() const { return LangOpts; }
1977  void setBlockID(signed i) { CurrentBlock = i; }
1978  void setStmtID(unsigned i) { CurrentStmt = i; }
1979
1980  virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1981
1982    StmtMapTy::iterator I = StmtMap.find(Terminator);
1983
1984    if (I == StmtMap.end())
1985      return false;
1986
1987    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1988                          && I->second.second == CurrentStmt) {
1989      return false;
1990    }
1991
1992    OS << "[B" << I->second.first << "." << I->second.second << "]";
1993    return true;
1994  }
1995};
1996} // end anonymous namespace
1997
1998
1999namespace {
2000class CFGBlockTerminatorPrint
2001  : public StmtVisitor<CFGBlockTerminatorPrint,void> {
2002
2003  llvm::raw_ostream& OS;
2004  StmtPrinterHelper* Helper;
2005  PrintingPolicy Policy;
2006public:
2007  CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
2008                          const PrintingPolicy &Policy)
2009    : OS(os), Helper(helper), Policy(Policy) {}
2010
2011  void VisitIfStmt(IfStmt* I) {
2012    OS << "if ";
2013    I->getCond()->printPretty(OS,Helper,Policy);
2014  }
2015
2016  // Default case.
2017  void VisitStmt(Stmt* Terminator) {
2018    Terminator->printPretty(OS, Helper, Policy);
2019  }
2020
2021  void VisitForStmt(ForStmt* F) {
2022    OS << "for (" ;
2023    if (F->getInit())
2024      OS << "...";
2025    OS << "; ";
2026    if (Stmt* C = F->getCond())
2027      C->printPretty(OS, Helper, Policy);
2028    OS << "; ";
2029    if (F->getInc())
2030      OS << "...";
2031    OS << ")";
2032  }
2033
2034  void VisitWhileStmt(WhileStmt* W) {
2035    OS << "while " ;
2036    if (Stmt* C = W->getCond())
2037      C->printPretty(OS, Helper, Policy);
2038  }
2039
2040  void VisitDoStmt(DoStmt* D) {
2041    OS << "do ... while ";
2042    if (Stmt* C = D->getCond())
2043      C->printPretty(OS, Helper, Policy);
2044  }
2045
2046  void VisitSwitchStmt(SwitchStmt* Terminator) {
2047    OS << "switch ";
2048    Terminator->getCond()->printPretty(OS, Helper, Policy);
2049  }
2050
2051  void VisitCXXTryStmt(CXXTryStmt* CS) {
2052    OS << "try ...";
2053  }
2054
2055  void VisitConditionalOperator(ConditionalOperator* C) {
2056    C->getCond()->printPretty(OS, Helper, Policy);
2057    OS << " ? ... : ...";
2058  }
2059
2060  void VisitChooseExpr(ChooseExpr* C) {
2061    OS << "__builtin_choose_expr( ";
2062    C->getCond()->printPretty(OS, Helper, Policy);
2063    OS << " )";
2064  }
2065
2066  void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2067    OS << "goto *";
2068    I->getTarget()->printPretty(OS, Helper, Policy);
2069  }
2070
2071  void VisitBinaryOperator(BinaryOperator* B) {
2072    if (!B->isLogicalOp()) {
2073      VisitExpr(B);
2074      return;
2075    }
2076
2077    B->getLHS()->printPretty(OS, Helper, Policy);
2078
2079    switch (B->getOpcode()) {
2080      case BinaryOperator::LOr:
2081        OS << " || ...";
2082        return;
2083      case BinaryOperator::LAnd:
2084        OS << " && ...";
2085        return;
2086      default:
2087        assert(false && "Invalid logical operator.");
2088    }
2089  }
2090
2091  void VisitExpr(Expr* E) {
2092    E->printPretty(OS, Helper, Policy);
2093  }
2094};
2095} // end anonymous namespace
2096
2097
2098static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
2099                       const CFGElement &E) {
2100  Stmt *Terminator = E;
2101
2102  if (E.asStartScope()) {
2103    OS << "start scope\n";
2104    return;
2105  }
2106  if (E.asEndScope()) {
2107    OS << "end scope\n";
2108    return;
2109  }
2110
2111  if (Helper) {
2112    // special printing for statement-expressions.
2113    if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
2114      CompoundStmt* Sub = SE->getSubStmt();
2115
2116      if (Sub->child_begin() != Sub->child_end()) {
2117        OS << "({ ... ; ";
2118        Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
2119        OS << " })\n";
2120        return;
2121      }
2122    }
2123
2124    // special printing for comma expressions.
2125    if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
2126      if (B->getOpcode() == BinaryOperator::Comma) {
2127        OS << "... , ";
2128        Helper->handledStmt(B->getRHS(),OS);
2129        OS << '\n';
2130        return;
2131      }
2132    }
2133  }
2134
2135  Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2136
2137  // Expressions need a newline.
2138  if (isa<Expr>(Terminator)) OS << '\n';
2139}
2140
2141static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
2142                        const CFGBlock& B,
2143                        StmtPrinterHelper* Helper, bool print_edges) {
2144
2145  if (Helper) Helper->setBlockID(B.getBlockID());
2146
2147  // Print the header.
2148  OS << "\n [ B" << B.getBlockID();
2149
2150  if (&B == &cfg->getEntry())
2151    OS << " (ENTRY) ]\n";
2152  else if (&B == &cfg->getExit())
2153    OS << " (EXIT) ]\n";
2154  else if (&B == cfg->getIndirectGotoBlock())
2155    OS << " (INDIRECT GOTO DISPATCH) ]\n";
2156  else
2157    OS << " ]\n";
2158
2159  // Print the label of this block.
2160  if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
2161
2162    if (print_edges)
2163      OS << "    ";
2164
2165    if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
2166      OS << L->getName();
2167    else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
2168      OS << "case ";
2169      C->getLHS()->printPretty(OS, Helper,
2170                               PrintingPolicy(Helper->getLangOpts()));
2171      if (C->getRHS()) {
2172        OS << " ... ";
2173        C->getRHS()->printPretty(OS, Helper,
2174                                 PrintingPolicy(Helper->getLangOpts()));
2175      }
2176    } else if (isa<DefaultStmt>(Label))
2177      OS << "default";
2178    else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
2179      OS << "catch (";
2180      if (CS->getExceptionDecl())
2181        CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
2182                                      0);
2183      else
2184        OS << "...";
2185      OS << ")";
2186
2187    } else
2188      assert(false && "Invalid label statement in CFGBlock.");
2189
2190    OS << ":\n";
2191  }
2192
2193  // Iterate through the statements in the block and print them.
2194  unsigned j = 1;
2195
2196  for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
2197       I != E ; ++I, ++j ) {
2198
2199    // Print the statement # in the basic block and the statement itself.
2200    if (print_edges)
2201      OS << "    ";
2202
2203    OS << llvm::format("%3d", j) << ": ";
2204
2205    if (Helper)
2206      Helper->setStmtID(j);
2207
2208    print_stmt(OS,Helper,*I);
2209  }
2210
2211  // Print the terminator of this block.
2212  if (B.getTerminator()) {
2213    if (print_edges)
2214      OS << "    ";
2215
2216    OS << "  T: ";
2217
2218    if (Helper) Helper->setBlockID(-1);
2219
2220    CFGBlockTerminatorPrint TPrinter(OS, Helper,
2221                                     PrintingPolicy(Helper->getLangOpts()));
2222    TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
2223    OS << '\n';
2224  }
2225
2226  if (print_edges) {
2227    // Print the predecessors of this block.
2228    OS << "    Predecessors (" << B.pred_size() << "):";
2229    unsigned i = 0;
2230
2231    for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
2232         I != E; ++I, ++i) {
2233
2234      if (i == 8 || (i-8) == 0)
2235        OS << "\n     ";
2236
2237      OS << " B" << (*I)->getBlockID();
2238    }
2239
2240    OS << '\n';
2241
2242    // Print the successors of this block.
2243    OS << "    Successors (" << B.succ_size() << "):";
2244    i = 0;
2245
2246    for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
2247         I != E; ++I, ++i) {
2248
2249      if (i == 8 || (i-8) % 10 == 0)
2250        OS << "\n    ";
2251
2252      if (*I)
2253        OS << " B" << (*I)->getBlockID();
2254      else
2255        OS  << " NULL";
2256    }
2257
2258    OS << '\n';
2259  }
2260}
2261
2262
2263/// dump - A simple pretty printer of a CFG that outputs to stderr.
2264void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
2265
2266/// print - A simple pretty printer of a CFG that outputs to an ostream.
2267void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
2268  StmtPrinterHelper Helper(this, LO);
2269
2270  // Print the entry block.
2271  print_block(OS, this, getEntry(), &Helper, true);
2272
2273  // Iterate through the CFGBlocks and print them one by one.
2274  for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
2275    // Skip the entry block, because we already printed it.
2276    if (&(**I) == &getEntry() || &(**I) == &getExit())
2277      continue;
2278
2279    print_block(OS, this, **I, &Helper, true);
2280  }
2281
2282  // Print the exit block.
2283  print_block(OS, this, getExit(), &Helper, true);
2284  OS.flush();
2285}
2286
2287/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
2288void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
2289  print(llvm::errs(), cfg, LO);
2290}
2291
2292/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
2293///   Generally this will only be called from CFG::print.
2294void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
2295                     const LangOptions &LO) const {
2296  StmtPrinterHelper Helper(cfg, LO);
2297  print_block(OS, cfg, *this, &Helper, true);
2298}
2299
2300/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
2301void CFGBlock::printTerminator(llvm::raw_ostream &OS,
2302                               const LangOptions &LO) const {
2303  CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
2304  TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
2305}
2306
2307Stmt* CFGBlock::getTerminatorCondition() {
2308
2309  if (!Terminator)
2310    return NULL;
2311
2312  Expr* E = NULL;
2313
2314  switch (Terminator->getStmtClass()) {
2315    default:
2316      break;
2317
2318    case Stmt::ForStmtClass:
2319      E = cast<ForStmt>(Terminator)->getCond();
2320      break;
2321
2322    case Stmt::WhileStmtClass:
2323      E = cast<WhileStmt>(Terminator)->getCond();
2324      break;
2325
2326    case Stmt::DoStmtClass:
2327      E = cast<DoStmt>(Terminator)->getCond();
2328      break;
2329
2330    case Stmt::IfStmtClass:
2331      E = cast<IfStmt>(Terminator)->getCond();
2332      break;
2333
2334    case Stmt::ChooseExprClass:
2335      E = cast<ChooseExpr>(Terminator)->getCond();
2336      break;
2337
2338    case Stmt::IndirectGotoStmtClass:
2339      E = cast<IndirectGotoStmt>(Terminator)->getTarget();
2340      break;
2341
2342    case Stmt::SwitchStmtClass:
2343      E = cast<SwitchStmt>(Terminator)->getCond();
2344      break;
2345
2346    case Stmt::ConditionalOperatorClass:
2347      E = cast<ConditionalOperator>(Terminator)->getCond();
2348      break;
2349
2350    case Stmt::BinaryOperatorClass: // '&&' and '||'
2351      E = cast<BinaryOperator>(Terminator)->getLHS();
2352      break;
2353
2354    case Stmt::ObjCForCollectionStmtClass:
2355      return Terminator;
2356  }
2357
2358  return E ? E->IgnoreParens() : NULL;
2359}
2360
2361bool CFGBlock::hasBinaryBranchTerminator() const {
2362
2363  if (!Terminator)
2364    return false;
2365
2366  Expr* E = NULL;
2367
2368  switch (Terminator->getStmtClass()) {
2369    default:
2370      return false;
2371
2372    case Stmt::ForStmtClass:
2373    case Stmt::WhileStmtClass:
2374    case Stmt::DoStmtClass:
2375    case Stmt::IfStmtClass:
2376    case Stmt::ChooseExprClass:
2377    case Stmt::ConditionalOperatorClass:
2378    case Stmt::BinaryOperatorClass:
2379      return true;
2380  }
2381
2382  return E ? E->IgnoreParens() : NULL;
2383}
2384
2385
2386//===----------------------------------------------------------------------===//
2387// CFG Graphviz Visualization
2388//===----------------------------------------------------------------------===//
2389
2390
2391#ifndef NDEBUG
2392static StmtPrinterHelper* GraphHelper;
2393#endif
2394
2395void CFG::viewCFG(const LangOptions &LO) const {
2396#ifndef NDEBUG
2397  StmtPrinterHelper H(this, LO);
2398  GraphHelper = &H;
2399  llvm::ViewGraph(this,"CFG");
2400  GraphHelper = NULL;
2401#endif
2402}
2403
2404namespace llvm {
2405template<>
2406struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2407
2408  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2409
2410  static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
2411
2412#ifndef NDEBUG
2413    std::string OutSStr;
2414    llvm::raw_string_ostream Out(OutSStr);
2415    print_block(Out,Graph, *Node, GraphHelper, false);
2416    std::string& OutStr = Out.str();
2417
2418    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
2419
2420    // Process string output to make it nicer...
2421    for (unsigned i = 0; i != OutStr.length(); ++i)
2422      if (OutStr[i] == '\n') {                            // Left justify
2423        OutStr[i] = '\\';
2424        OutStr.insert(OutStr.begin()+i+1, 'l');
2425      }
2426
2427    return OutStr;
2428#else
2429    return "";
2430#endif
2431  }
2432};
2433} // end namespace llvm
2434