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