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