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