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