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