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