CFG.cpp revision 9106582d6afd4e33bd39f3e7173acdbb4e9b7849
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/// LocalScope - Node in tree of local scopes created for C++ implicit
56/// destructor calls generation. It contains list of automatic variables
57/// declared in the scope and link to position in previous scope this scope
58/// began in.
59///
60/// The process of creating local scopes is as follows:
61/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
62/// - Before processing statements in scope (e.g. CompoundStmt) create
63///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
64///   and set CFGBuilder::ScopePos to the end of new scope,
65/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
66///   at this VarDecl,
67/// - For every normal (without jump) end of scope add to CFGBlock destructors
68///   for objects in the current scope,
69/// - For every jump add to CFGBlock destructors for objects
70///   between CFGBuilder::ScopePos and local scope position saved for jump
71///   target. Thanks to C++ restrictions on goto jumps we can be sure that
72///   jump target position will be on the path to root from CFGBuilder::ScopePos
73///   (adding any variable that doesn't need constructor to be called to
74///   LocalScope can break this assumption),
75///
76class LocalScope {
77public:
78  typedef llvm::SmallVector<VarDecl*, 4> AutomaticVarsTy;
79
80  /// const_iterator - Iterates local scope backwards and jumps to previous
81  /// scope on reaching the beginning of currently iterated scope.
82  class const_iterator {
83    const LocalScope* Scope;
84
85    /// VarIter is guaranteed to be greater then 0 for every valid iterator.
86    /// Invalid iterator (with null Scope) has VarIter equal to 0.
87    unsigned VarIter;
88
89  public:
90    /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
91    /// Incrementing invalid iterator is allowed and will result in invalid
92    /// iterator.
93    const_iterator()
94        : Scope(NULL), VarIter(0) {}
95
96    /// Create valid iterator. In case when S.Prev is an invalid iterator and
97    /// I is equal to 0, this will create invalid iterator.
98    const_iterator(const LocalScope& S, unsigned I)
99        : Scope(&S), VarIter(I) {
100      // Iterator to "end" of scope is not allowed. Handle it by going up
101      // in scopes tree possibly up to invalid iterator in the root.
102      if (VarIter == 0 && Scope)
103        *this = Scope->Prev;
104    }
105
106    VarDecl* const* operator->() const {
107      assert (Scope && "Dereferencing invalid iterator is not allowed");
108      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
109      return &Scope->Vars[VarIter - 1];
110    }
111    VarDecl* operator*() const {
112      return *this->operator->();
113    }
114
115    const_iterator& operator++() {
116      if (!Scope)
117        return *this;
118
119      assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
120      --VarIter;
121      if (VarIter == 0)
122        *this = Scope->Prev;
123      return *this;
124    }
125    const_iterator operator++(int) {
126      const_iterator P = *this;
127      ++*this;
128      return P;
129    }
130
131    bool operator==(const const_iterator& rhs) const {
132      return Scope == rhs.Scope && VarIter == rhs.VarIter;
133    }
134    bool operator!=(const const_iterator& rhs) const {
135      return !(*this == rhs);
136    }
137
138    operator bool() const {
139      return *this != const_iterator();
140    }
141
142    int distance(const_iterator L);
143  };
144
145  friend class const_iterator;
146
147private:
148  /// Automatic variables in order of declaration.
149  AutomaticVarsTy Vars;
150  /// Iterator to variable in previous scope that was declared just before
151  /// begin of this scope.
152  const_iterator Prev;
153
154public:
155  /// Constructs empty scope linked to previous scope in specified place.
156  LocalScope(const_iterator P)
157      : Vars()
158      , Prev(P) {}
159
160  /// Begin of scope in direction of CFG building (backwards).
161  const_iterator begin() const { return const_iterator(*this, Vars.size()); }
162
163  void addVar(VarDecl* VD) {
164    Vars.push_back(VD);
165  }
166};
167
168/// distance - Calculates distance from this to L. L must be reachable from this
169/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
170/// number of scopes between this and L.
171int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
172  int D = 0;
173  const_iterator F = *this;
174  while (F.Scope != L.Scope) {
175    assert (F != const_iterator()
176        && "L iterator is not reachable from F iterator.");
177    D += F.VarIter;
178    F = F.Scope->Prev;
179  }
180  D += F.VarIter - L.VarIter;
181  return D;
182}
183
184/// BlockScopePosPair - Structure for specifying position in CFG during its
185/// build process. It consists of CFGBlock that specifies position in CFG graph
186/// and  LocalScope::const_iterator that specifies position in LocalScope graph.
187struct BlockScopePosPair {
188  BlockScopePosPair() {}
189  BlockScopePosPair(CFGBlock* B, LocalScope::const_iterator S)
190      : Block(B), ScopePos(S) {}
191
192  CFGBlock*                   Block;
193  LocalScope::const_iterator  ScopePos;
194};
195
196/// CFGBuilder - This class implements CFG construction from an AST.
197///   The builder is stateful: an instance of the builder should be used to only
198///   construct a single CFG.
199///
200///   Example usage:
201///
202///     CFGBuilder builder;
203///     CFG* cfg = builder.BuildAST(stmt1);
204///
205///  CFG construction is done via a recursive walk of an AST.  We actually parse
206///  the AST in reverse order so that the successor of a basic block is
207///  constructed prior to its predecessor.  This allows us to nicely capture
208///  implicit fall-throughs without extra basic blocks.
209///
210class CFGBuilder {
211  typedef BlockScopePosPair JumpTarget;
212  typedef BlockScopePosPair JumpSource;
213
214  ASTContext *Context;
215  llvm::OwningPtr<CFG> cfg;
216
217  CFGBlock* Block;
218  CFGBlock* Succ;
219  JumpTarget ContinueJumpTarget;
220  JumpTarget BreakJumpTarget;
221  CFGBlock* SwitchTerminatedBlock;
222  CFGBlock* DefaultCaseBlock;
223  CFGBlock* TryTerminatedBlock;
224
225  // Current position in local scope.
226  LocalScope::const_iterator ScopePos;
227
228  // LabelMap records the mapping from Label expressions to their jump targets.
229  typedef llvm::DenseMap<LabelStmt*, JumpTarget> LabelMapTy;
230  LabelMapTy LabelMap;
231
232  // A list of blocks that end with a "goto" that must be backpatched to their
233  // resolved targets upon completion of CFG construction.
234  typedef std::vector<JumpSource> BackpatchBlocksTy;
235  BackpatchBlocksTy BackpatchBlocks;
236
237  // A list of labels whose address has been taken (for indirect gotos).
238  typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
239  LabelSetTy AddressTakenLabels;
240
241  bool badCFG;
242  CFG::BuildOptions BuildOpts;
243
244public:
245  explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
246                          Block(NULL), Succ(NULL),
247                          SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
248                          TryTerminatedBlock(NULL), badCFG(false) {}
249
250  // buildCFG - Used by external clients to construct the CFG.
251  CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
252      CFG::BuildOptions BO);
253
254private:
255  // Visitors to walk an AST and construct the CFG.
256  CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
257  CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
258  CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
259  CFGBlock *VisitBreakStmt(BreakStmt *B);
260  CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
261  CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
262  CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
263  CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc);
264  CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
265  CFGBlock *VisitCaseStmt(CaseStmt *C);
266  CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
267  CFGBlock *VisitCompoundStmt(CompoundStmt *C);
268  CFGBlock *VisitConditionalOperator(ConditionalOperator *C, AddStmtChoice asc);
269  CFGBlock *VisitContinueStmt(ContinueStmt *C);
270  CFGBlock *VisitDeclStmt(DeclStmt *DS);
271  CFGBlock *VisitDeclSubExpr(Decl* D);
272  CFGBlock *VisitDefaultStmt(DefaultStmt *D);
273  CFGBlock *VisitDoStmt(DoStmt *D);
274  CFGBlock *VisitForStmt(ForStmt *F);
275  CFGBlock *VisitGotoStmt(GotoStmt* G);
276  CFGBlock *VisitIfStmt(IfStmt *I);
277  CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
278  CFGBlock *VisitLabelStmt(LabelStmt *L);
279  CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
280  CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
281  CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
282  CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
283  CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
284  CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
285  CFGBlock *VisitReturnStmt(ReturnStmt* R);
286  CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
287  CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
288  CFGBlock *VisitSwitchStmt(SwitchStmt *S);
289  CFGBlock *VisitWhileStmt(WhileStmt *W);
290
291  CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
292  CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
293  CFGBlock *VisitChildren(Stmt* S);
294
295  // NYS == Not Yet Supported
296  CFGBlock* NYS() {
297    badCFG = true;
298    return Block;
299  }
300
301  void autoCreateBlock() { if (!Block) Block = createBlock(); }
302  CFGBlock *createBlock(bool add_successor = true);
303
304  CFGBlock *addStmt(Stmt *S) {
305    return Visit(S, AddStmtChoice::AlwaysAdd);
306  }
307  CFGBlock *addInitializer(CXXBaseOrMemberInitializer *I);
308  void addAutomaticObjDtors(LocalScope::const_iterator B,
309                            LocalScope::const_iterator E, Stmt* S);
310  void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
311
312  // Local scopes creation.
313  LocalScope* createOrReuseLocalScope(LocalScope* Scope);
314
315  void addLocalScopeForStmt(Stmt* S);
316  LocalScope* addLocalScopeForDeclStmt(DeclStmt* DS, LocalScope* Scope = NULL);
317  LocalScope* addLocalScopeForVarDecl(VarDecl* VD, LocalScope* Scope = NULL);
318
319  void addLocalScopeAndDtors(Stmt* S);
320
321  // Interface to CFGBlock - adding CFGElements.
322  void AppendStmt(CFGBlock *B, Stmt *S,
323                  AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
324    B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue());
325  }
326  void appendInitializer(CFGBlock *B, CXXBaseOrMemberInitializer *I) {
327    B->appendInitializer(I, cfg->getBumpVectorContext());
328  }
329  void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
330    B->appendBaseDtor(BS, cfg->getBumpVectorContext());
331  }
332  void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
333    B->appendMemberDtor(FD, cfg->getBumpVectorContext());
334  }
335
336  void insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
337    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S);
338  void appendAutomaticObjDtors(CFGBlock* Blk, LocalScope::const_iterator B,
339      LocalScope::const_iterator E, Stmt* S);
340  void prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
341      LocalScope::const_iterator B, LocalScope::const_iterator E);
342
343  void AddSuccessor(CFGBlock *B, CFGBlock *S) {
344    B->addSuccessor(S, cfg->getBumpVectorContext());
345  }
346
347  /// TryResult - a class representing a variant over the values
348  ///  'true', 'false', or 'unknown'.  This is returned by TryEvaluateBool,
349  ///  and is used by the CFGBuilder to decide if a branch condition
350  ///  can be decided up front during CFG construction.
351  class TryResult {
352    int X;
353  public:
354    TryResult(bool b) : X(b ? 1 : 0) {}
355    TryResult() : X(-1) {}
356
357    bool isTrue() const { return X == 1; }
358    bool isFalse() const { return X == 0; }
359    bool isKnown() const { return X >= 0; }
360    void negate() {
361      assert(isKnown());
362      X ^= 0x1;
363    }
364  };
365
366  /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
367  /// if we can evaluate to a known value, otherwise return -1.
368  TryResult TryEvaluateBool(Expr *S) {
369    if (!BuildOpts.PruneTriviallyFalseEdges)
370      return TryResult();
371
372    Expr::EvalResult Result;
373    if (!S->isTypeDependent() && !S->isValueDependent() &&
374        S->Evaluate(Result, *Context) && Result.Val.isInt())
375      return Result.Val.getInt().getBoolValue();
376
377    return TryResult();
378  }
379};
380
381// FIXME: Add support for dependent-sized array types in C++?
382// Does it even make sense to build a CFG for an uninstantiated template?
383static VariableArrayType* FindVA(Type* t) {
384  while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
385    if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
386      if (vat->getSizeExpr())
387        return vat;
388
389    t = vt->getElementType().getTypePtr();
390  }
391
392  return 0;
393}
394
395/// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
396///  arbitrary statement.  Examples include a single expression or a function
397///  body (compound statement).  The ownership of the returned CFG is
398///  transferred to the caller.  If CFG construction fails, this method returns
399///  NULL.
400CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C,
401    CFG::BuildOptions BO) {
402
403  Context = C;
404  assert(cfg.get());
405  if (!Statement)
406    return NULL;
407
408  BuildOpts = BO;
409
410  // Create an empty block that will serve as the exit block for the CFG.  Since
411  // this is the first block added to the CFG, it will be implicitly registered
412  // as the exit block.
413  Succ = createBlock();
414  assert(Succ == &cfg->getExit());
415  Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
416
417  if (BuildOpts.AddImplicitDtors)
418    if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
419      addImplicitDtorsForDestructor(DD);
420
421  // Visit the statements and create the CFG.
422  CFGBlock *B = addStmt(Statement);
423
424  if (badCFG)
425    return NULL;
426
427  // For C++ constructor add initializers to CFG.
428  if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
429    for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
430        E = CD->init_rend(); I != E; ++I) {
431      B = addInitializer(*I);
432      if (badCFG)
433        return NULL;
434    }
435  }
436
437  if (B)
438    Succ = B;
439
440  // Backpatch the gotos whose label -> block mappings we didn't know when we
441  // encountered them.
442  for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
443                                   E = BackpatchBlocks.end(); I != E; ++I ) {
444
445    CFGBlock* B = I->Block;
446    GotoStmt* G = cast<GotoStmt>(B->getTerminator());
447    LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
448
449    // If there is no target for the goto, then we are looking at an
450    // incomplete AST.  Handle this by not registering a successor.
451    if (LI == LabelMap.end()) continue;
452
453    JumpTarget JT = LI->second;
454    prependAutomaticObjDtorsWithTerminator(B, I->ScopePos, JT.ScopePos);
455    AddSuccessor(B, JT.Block);
456  }
457
458  // Add successors to the Indirect Goto Dispatch block (if we have one).
459  if (CFGBlock* B = cfg->getIndirectGotoBlock())
460    for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
461                              E = AddressTakenLabels.end(); I != E; ++I ) {
462
463      // Lookup the target block.
464      LabelMapTy::iterator LI = LabelMap.find(*I);
465
466      // If there is no target block that contains label, then we are looking
467      // at an incomplete AST.  Handle this by not registering a successor.
468      if (LI == LabelMap.end()) continue;
469
470      AddSuccessor(B, LI->second.Block);
471    }
472
473  // Create an empty entry block that has no predecessors.
474  cfg->setEntry(createBlock());
475
476  return cfg.take();
477}
478
479/// createBlock - Used to lazily create blocks that are connected
480///  to the current (global) succcessor.
481CFGBlock* CFGBuilder::createBlock(bool add_successor) {
482  CFGBlock* B = cfg->createBlock();
483  if (add_successor && Succ)
484    AddSuccessor(B, Succ);
485  return B;
486}
487
488/// addInitializer - Add C++ base or member initializer element to CFG.
489CFGBlock *CFGBuilder::addInitializer(CXXBaseOrMemberInitializer *I) {
490  if (!BuildOpts.AddInitializers)
491    return Block;
492
493  autoCreateBlock();
494  appendInitializer(Block, I);
495
496  if (Expr *Init = I->getInit()) {
497    AddStmtChoice::Kind K = AddStmtChoice::NotAlwaysAdd;
498    if (FieldDecl *FD = I->getMember())
499      if (FD->getType()->isReferenceType())
500        K = AddStmtChoice::AsLValueNotAlwaysAdd;
501
502    return Visit(Init, AddStmtChoice(K));
503  }
504
505  return Block;
506}
507
508/// addAutomaticObjDtors - Add to current block automatic objects destructors
509/// for objects in range of local scope positions. Use S as trigger statement
510/// for destructors.
511void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
512                                      LocalScope::const_iterator E, Stmt* S) {
513  if (!BuildOpts.AddImplicitDtors)
514    return;
515
516  if (B == E)
517    return;
518
519  autoCreateBlock();
520  appendAutomaticObjDtors(Block, B, E, S);
521}
522
523/// addImplicitDtorsForDestructor - Add implicit destructors generated for
524/// base and member objects in destructor.
525void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
526  assert (BuildOpts.AddImplicitDtors
527      && "Can be called only when dtors should be added");
528  const CXXRecordDecl *RD = DD->getParent();
529
530  // At the end destroy virtual base objects.
531  for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
532      VE = RD->vbases_end(); VI != VE; ++VI) {
533    const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
534    if (!CD->hasTrivialDestructor()) {
535      autoCreateBlock();
536      appendBaseDtor(Block, VI);
537    }
538  }
539
540  // Before virtual bases destroy direct base objects.
541  for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
542      BE = RD->bases_end(); BI != BE; ++BI) {
543    if (!BI->isVirtual()) {
544      const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
545      if (!CD->hasTrivialDestructor()) {
546        autoCreateBlock();
547        appendBaseDtor(Block, BI);
548      }
549    }
550  }
551
552  // First destroy member objects.
553  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
554      FE = RD->field_end(); FI != FE; ++FI) {
555    if (const CXXRecordDecl *CD = FI->getType()->getAsCXXRecordDecl())
556      if (!CD->hasTrivialDestructor()) {
557        autoCreateBlock();
558        appendMemberDtor(Block, *FI);
559      }
560  }
561}
562
563/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
564/// way return valid LocalScope object.
565LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
566  if (!Scope) {
567    Scope = cfg->getAllocator().Allocate<LocalScope>();
568    new (Scope) LocalScope(ScopePos);
569  }
570  return Scope;
571}
572
573/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
574/// that should create implicit scope (e.g. if/else substatements).
575void CFGBuilder::addLocalScopeForStmt(Stmt* S) {
576  if (!BuildOpts.AddImplicitDtors)
577    return;
578
579  LocalScope *Scope = 0;
580
581  // For compound statement we will be creating explicit scope.
582  if (CompoundStmt* CS = dyn_cast<CompoundStmt>(S)) {
583    for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
584        ; BI != BE; ++BI) {
585      Stmt* SI = *BI;
586      if (LabelStmt* LS = dyn_cast<LabelStmt>(SI))
587        SI = LS->getSubStmt();
588      if (DeclStmt* DS = dyn_cast<DeclStmt>(SI))
589        Scope = addLocalScopeForDeclStmt(DS, Scope);
590    }
591    return;
592  }
593
594  // For any other statement scope will be implicit and as such will be
595  // interesting only for DeclStmt.
596  if (LabelStmt* LS = dyn_cast<LabelStmt>(S))
597    S = LS->getSubStmt();
598  if (DeclStmt* DS = dyn_cast<DeclStmt>(S))
599    addLocalScopeForDeclStmt(DS);
600}
601
602/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
603/// reuse Scope if not NULL.
604LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt* DS,
605                                                 LocalScope* Scope) {
606  if (!BuildOpts.AddImplicitDtors)
607    return Scope;
608
609  for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
610      ; DI != DE; ++DI) {
611    if (VarDecl* VD = dyn_cast<VarDecl>(*DI))
612      Scope = addLocalScopeForVarDecl(VD, Scope);
613  }
614  return Scope;
615}
616
617/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
618/// create add scope for automatic objects and temporary objects bound to
619/// const reference. Will reuse Scope if not NULL.
620LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl* VD,
621                                                LocalScope* Scope) {
622  if (!BuildOpts.AddImplicitDtors)
623    return Scope;
624
625  // Check if variable is local.
626  switch (VD->getStorageClass()) {
627  case SC_None:
628  case SC_Auto:
629  case SC_Register:
630    break;
631  default: return Scope;
632  }
633
634  // Check for const references bound to temporary. Set type to pointee.
635  QualType QT = VD->getType();
636  if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) {
637    QT = RT->getPointeeType();
638    if (!QT.isConstQualified())
639      return Scope;
640    if (!VD->getInit() || !VD->getInit()->Classify(*Context).isRValue())
641      return Scope;
642  }
643
644  // Check if type is a C++ class with non-trivial destructor.
645
646  if (const CXXRecordDecl* CD = QT->getAsCXXRecordDecl())
647    if (!CD->hasTrivialDestructor()) {
648      // Add the variable to scope
649      Scope = createOrReuseLocalScope(Scope);
650      Scope->addVar(VD);
651      ScopePos = Scope->begin();
652    }
653  return Scope;
654}
655
656/// addLocalScopeAndDtors - For given statement add local scope for it and
657/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
658void CFGBuilder::addLocalScopeAndDtors(Stmt* S) {
659  if (!BuildOpts.AddImplicitDtors)
660    return;
661
662  LocalScope::const_iterator scopeBeginPos = ScopePos;
663  addLocalScopeForStmt(S);
664  addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
665}
666
667/// insertAutomaticObjDtors - Insert destructor CFGElements for variables with
668/// automatic storage duration to CFGBlock's elements vector. Insertion will be
669/// performed in place specified with iterator.
670void CFGBuilder::insertAutomaticObjDtors(CFGBlock* Blk, CFGBlock::iterator I,
671    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
672  BumpVectorContext& C = cfg->getBumpVectorContext();
673  I = Blk->beginAutomaticObjDtorsInsert(I, B.distance(E), C);
674  while (B != E)
675    I = Blk->insertAutomaticObjDtor(I, *B++, S);
676}
677
678/// appendAutomaticObjDtors - Append destructor CFGElements for variables with
679/// automatic storage duration to CFGBlock's elements vector. Elements will be
680/// appended to physical end of the vector which happens to be logical
681/// beginning.
682void CFGBuilder::appendAutomaticObjDtors(CFGBlock* Blk,
683    LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt* S) {
684  insertAutomaticObjDtors(Blk, Blk->begin(), B, E, S);
685}
686
687/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
688/// variables with automatic storage duration to CFGBlock's elements vector.
689/// Elements will be prepended to physical beginning of the vector which
690/// happens to be logical end. Use blocks terminator as statement that specifies
691/// destructors call site.
692void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock* Blk,
693    LocalScope::const_iterator B, LocalScope::const_iterator E) {
694  insertAutomaticObjDtors(Blk, Blk->end(), B, E, Blk->getTerminator());
695}
696
697/// Visit - Walk the subtree of a statement and add extra
698///   blocks for ternary operators, &&, and ||.  We also process "," and
699///   DeclStmts (which may contain nested control-flow).
700CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
701tryAgain:
702  if (!S) {
703    badCFG = true;
704    return 0;
705  }
706  switch (S->getStmtClass()) {
707    default:
708      return VisitStmt(S, asc);
709
710    case Stmt::AddrLabelExprClass:
711      return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
712
713    case Stmt::BinaryOperatorClass:
714      return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
715
716    case Stmt::BlockExprClass:
717      return VisitBlockExpr(cast<BlockExpr>(S), asc);
718
719    case Stmt::BreakStmtClass:
720      return VisitBreakStmt(cast<BreakStmt>(S));
721
722    case Stmt::CallExprClass:
723    case Stmt::CXXOperatorCallExprClass:
724      return VisitCallExpr(cast<CallExpr>(S), asc);
725
726    case Stmt::CaseStmtClass:
727      return VisitCaseStmt(cast<CaseStmt>(S));
728
729    case Stmt::ChooseExprClass:
730      return VisitChooseExpr(cast<ChooseExpr>(S), asc);
731
732    case Stmt::CompoundStmtClass:
733      return VisitCompoundStmt(cast<CompoundStmt>(S));
734
735    case Stmt::ConditionalOperatorClass:
736      return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
737
738    case Stmt::ContinueStmtClass:
739      return VisitContinueStmt(cast<ContinueStmt>(S));
740
741    case Stmt::CXXCatchStmtClass:
742      return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
743
744    case Stmt::CXXExprWithTemporariesClass: {
745      // FIXME: Handle temporaries.  For now, just visit the subexpression
746      // so we don't artificially create extra blocks.
747      return Visit(cast<CXXExprWithTemporaries>(S)->getSubExpr(), asc);
748    }
749
750    case Stmt::CXXMemberCallExprClass:
751      return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc);
752
753    case Stmt::CXXThrowExprClass:
754      return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
755
756    case Stmt::CXXTryStmtClass:
757      return VisitCXXTryStmt(cast<CXXTryStmt>(S));
758
759    case Stmt::DeclStmtClass:
760      return VisitDeclStmt(cast<DeclStmt>(S));
761
762    case Stmt::DefaultStmtClass:
763      return VisitDefaultStmt(cast<DefaultStmt>(S));
764
765    case Stmt::DoStmtClass:
766      return VisitDoStmt(cast<DoStmt>(S));
767
768    case Stmt::ForStmtClass:
769      return VisitForStmt(cast<ForStmt>(S));
770
771    case Stmt::GotoStmtClass:
772      return VisitGotoStmt(cast<GotoStmt>(S));
773
774    case Stmt::IfStmtClass:
775      return VisitIfStmt(cast<IfStmt>(S));
776
777    case Stmt::IndirectGotoStmtClass:
778      return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
779
780    case Stmt::LabelStmtClass:
781      return VisitLabelStmt(cast<LabelStmt>(S));
782
783    case Stmt::MemberExprClass:
784      return VisitMemberExpr(cast<MemberExpr>(S), asc);
785
786    case Stmt::ObjCAtCatchStmtClass:
787      return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
788
789    case Stmt::ObjCAtSynchronizedStmtClass:
790      return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
791
792    case Stmt::ObjCAtThrowStmtClass:
793      return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
794
795    case Stmt::ObjCAtTryStmtClass:
796      return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
797
798    case Stmt::ObjCForCollectionStmtClass:
799      return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
800
801    case Stmt::ParenExprClass:
802      S = cast<ParenExpr>(S)->getSubExpr();
803      goto tryAgain;
804
805    case Stmt::NullStmtClass:
806      return Block;
807
808    case Stmt::ReturnStmtClass:
809      return VisitReturnStmt(cast<ReturnStmt>(S));
810
811    case Stmt::SizeOfAlignOfExprClass:
812      return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
813
814    case Stmt::StmtExprClass:
815      return VisitStmtExpr(cast<StmtExpr>(S), asc);
816
817    case Stmt::SwitchStmtClass:
818      return VisitSwitchStmt(cast<SwitchStmt>(S));
819
820    case Stmt::WhileStmtClass:
821      return VisitWhileStmt(cast<WhileStmt>(S));
822  }
823}
824
825CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
826  if (asc.alwaysAdd()) {
827    autoCreateBlock();
828    AppendStmt(Block, S, asc);
829  }
830
831  return VisitChildren(S);
832}
833
834/// VisitChildren - Visit the children of a Stmt.
835CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
836  CFGBlock *B = Block;
837  for (Stmt::child_iterator I = Terminator->child_begin(),
838         E = Terminator->child_end(); I != E; ++I) {
839    if (*I) B = Visit(*I);
840  }
841  return B;
842}
843
844CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
845                                         AddStmtChoice asc) {
846  AddressTakenLabels.insert(A->getLabel());
847
848  if (asc.alwaysAdd()) {
849    autoCreateBlock();
850    AppendStmt(Block, A, asc);
851  }
852
853  return Block;
854}
855
856CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
857                                          AddStmtChoice asc) {
858  if (B->isLogicalOp()) { // && or ||
859    CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
860    AppendStmt(ConfluenceBlock, B, asc);
861
862    if (badCFG)
863      return 0;
864
865    // create the block evaluating the LHS
866    CFGBlock* LHSBlock = createBlock(false);
867    LHSBlock->setTerminator(B);
868
869    // create the block evaluating the RHS
870    Succ = ConfluenceBlock;
871    Block = NULL;
872    CFGBlock* RHSBlock = addStmt(B->getRHS());
873
874    if (RHSBlock) {
875      if (badCFG)
876        return 0;
877    }
878    else {
879      // Create an empty block for cases where the RHS doesn't require
880      // any explicit statements in the CFG.
881      RHSBlock = createBlock();
882    }
883
884    // See if this is a known constant.
885    TryResult KnownVal = TryEvaluateBool(B->getLHS());
886    if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr))
887      KnownVal.negate();
888
889    // Now link the LHSBlock with RHSBlock.
890    if (B->getOpcode() == BO_LOr) {
891      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
892      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
893    } else {
894      assert(B->getOpcode() == BO_LAnd);
895      AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
896      AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
897    }
898
899    // Generate the blocks for evaluating the LHS.
900    Block = LHSBlock;
901    return addStmt(B->getLHS());
902  }
903  else if (B->getOpcode() == BO_Comma) { // ,
904    autoCreateBlock();
905    AppendStmt(Block, B, asc);
906    addStmt(B->getRHS());
907    return addStmt(B->getLHS());
908  }
909  else if (B->isAssignmentOp()) {
910    if (asc.alwaysAdd()) {
911      autoCreateBlock();
912      AppendStmt(Block, B, asc);
913    }
914
915    Visit(B->getLHS(), AddStmtChoice::AsLValueNotAlwaysAdd);
916    return Visit(B->getRHS());
917  }
918
919  if (asc.alwaysAdd()) {
920    autoCreateBlock();
921    AppendStmt(Block, B, asc);
922  }
923
924  Visit(B->getRHS());
925  return Visit(B->getLHS());
926}
927
928CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
929  if (asc.alwaysAdd()) {
930    autoCreateBlock();
931    AppendStmt(Block, E, asc);
932  }
933  return Block;
934}
935
936CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
937  // "break" is a control-flow statement.  Thus we stop processing the current
938  // block.
939  if (badCFG)
940    return 0;
941
942  // Now create a new block that ends with the break statement.
943  Block = createBlock(false);
944  Block->setTerminator(B);
945
946  // If there is no target for the break, then we are looking at an incomplete
947  // AST.  This means that the CFG cannot be constructed.
948  if (BreakJumpTarget.Block) {
949    addAutomaticObjDtors(ScopePos, BreakJumpTarget.ScopePos, B);
950    AddSuccessor(Block, BreakJumpTarget.Block);
951  } else
952    badCFG = true;
953
954
955  return Block;
956}
957
958static bool CanThrow(Expr *E) {
959  QualType Ty = E->getType();
960  if (Ty->isFunctionPointerType())
961    Ty = Ty->getAs<PointerType>()->getPointeeType();
962  else if (Ty->isBlockPointerType())
963    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
964
965  const FunctionType *FT = Ty->getAs<FunctionType>();
966  if (FT) {
967    if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
968      if (Proto->hasEmptyExceptionSpec())
969        return false;
970  }
971  return true;
972}
973
974CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
975  // If this is a call to a no-return function, this stops the block here.
976  bool NoReturn = false;
977  if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) {
978    NoReturn = true;
979  }
980
981  bool AddEHEdge = false;
982
983  // Languages without exceptions are assumed to not throw.
984  if (Context->getLangOptions().Exceptions) {
985    if (BuildOpts.AddEHEdges)
986      AddEHEdge = true;
987  }
988
989  if (FunctionDecl *FD = C->getDirectCallee()) {
990    if (FD->hasAttr<NoReturnAttr>())
991      NoReturn = true;
992    if (FD->hasAttr<NoThrowAttr>())
993      AddEHEdge = false;
994  }
995
996  if (!CanThrow(C->getCallee()))
997    AddEHEdge = false;
998
999  if (!NoReturn && !AddEHEdge) {
1000    if (asc.asLValue())
1001      return VisitStmt(C, AddStmtChoice::AlwaysAddAsLValue);
1002    else
1003      return VisitStmt(C, AddStmtChoice::AlwaysAdd);
1004  }
1005
1006  if (Block) {
1007    Succ = Block;
1008    if (badCFG)
1009      return 0;
1010  }
1011
1012  Block = createBlock(!NoReturn);
1013  AppendStmt(Block, C, asc);
1014
1015  if (NoReturn) {
1016    // Wire this to the exit block directly.
1017    AddSuccessor(Block, &cfg->getExit());
1018  }
1019  if (AddEHEdge) {
1020    // Add exceptional edges.
1021    if (TryTerminatedBlock)
1022      AddSuccessor(Block, TryTerminatedBlock);
1023    else
1024      AddSuccessor(Block, &cfg->getExit());
1025  }
1026
1027  return VisitChildren(C);
1028}
1029
1030CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1031                                      AddStmtChoice asc) {
1032  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1033  AppendStmt(ConfluenceBlock, C, asc);
1034  if (badCFG)
1035    return 0;
1036
1037  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1038                       : AddStmtChoice::AlwaysAdd;
1039
1040  Succ = ConfluenceBlock;
1041  Block = NULL;
1042  CFGBlock* LHSBlock = Visit(C->getLHS(), asc);
1043  if (badCFG)
1044    return 0;
1045
1046  Succ = ConfluenceBlock;
1047  Block = NULL;
1048  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
1049  if (badCFG)
1050    return 0;
1051
1052  Block = createBlock(false);
1053  // See if this is a known constant.
1054  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
1055  AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1056  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1057  Block->setTerminator(C);
1058  return addStmt(C->getCond());
1059}
1060
1061
1062CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
1063  addLocalScopeAndDtors(C);
1064  CFGBlock* LastBlock = Block;
1065
1066  for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1067       I != E; ++I ) {
1068    // If we hit a segment of code just containing ';' (NullStmts), we can
1069    // get a null block back.  In such cases, just use the LastBlock
1070    if (CFGBlock *newBlock = addStmt(*I))
1071      LastBlock = newBlock;
1072
1073    if (badCFG)
1074      return NULL;
1075  }
1076
1077  return LastBlock;
1078}
1079
1080CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C,
1081                                               AddStmtChoice asc) {
1082  // Create the confluence block that will "merge" the results of the ternary
1083  // expression.
1084  CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
1085  AppendStmt(ConfluenceBlock, C, asc);
1086  if (badCFG)
1087    return 0;
1088
1089  asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1090                       : AddStmtChoice::AlwaysAdd;
1091
1092  // Create a block for the LHS expression if there is an LHS expression.  A
1093  // GCC extension allows LHS to be NULL, causing the condition to be the
1094  // value that is returned instead.
1095  //  e.g: x ?: y is shorthand for: x ? x : y;
1096  Succ = ConfluenceBlock;
1097  Block = NULL;
1098  CFGBlock* LHSBlock = NULL;
1099  if (C->getLHS()) {
1100    LHSBlock = Visit(C->getLHS(), asc);
1101    if (badCFG)
1102      return 0;
1103    Block = NULL;
1104  }
1105
1106  // Create the block for the RHS expression.
1107  Succ = ConfluenceBlock;
1108  CFGBlock* RHSBlock = Visit(C->getRHS(), asc);
1109  if (badCFG)
1110    return 0;
1111
1112  // Create the block that will contain the condition.
1113  Block = createBlock(false);
1114
1115  // See if this is a known constant.
1116  const TryResult& KnownVal = TryEvaluateBool(C->getCond());
1117  if (LHSBlock) {
1118    AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1119  } else {
1120    if (KnownVal.isFalse()) {
1121      // If we know the condition is false, add NULL as the successor for
1122      // the block containing the condition.  In this case, the confluence
1123      // block will have just one predecessor.
1124      AddSuccessor(Block, 0);
1125      assert(ConfluenceBlock->pred_size() == 1);
1126    } else {
1127      // If we have no LHS expression, add the ConfluenceBlock as a direct
1128      // successor for the block containing the condition.  Moreover, we need to
1129      // reverse the order of the predecessors in the ConfluenceBlock because
1130      // the RHSBlock will have been added to the succcessors already, and we
1131      // want the first predecessor to the the block containing the expression
1132      // for the case when the ternary expression evaluates to true.
1133      AddSuccessor(Block, ConfluenceBlock);
1134      assert(ConfluenceBlock->pred_size() == 2);
1135      std::reverse(ConfluenceBlock->pred_begin(),
1136                   ConfluenceBlock->pred_end());
1137    }
1138  }
1139
1140  AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1141  Block->setTerminator(C);
1142  return addStmt(C->getCond());
1143}
1144
1145CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1146  autoCreateBlock();
1147
1148  if (DS->isSingleDecl()) {
1149    AppendStmt(Block, DS);
1150    return VisitDeclSubExpr(DS->getSingleDecl());
1151  }
1152
1153  CFGBlock *B = 0;
1154
1155  // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
1156  typedef llvm::SmallVector<Decl*,10> BufTy;
1157  BufTy Buf(DS->decl_begin(), DS->decl_end());
1158
1159  for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
1160    // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1161    unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1162               ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1163
1164    // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
1165    // automatically freed with the CFG.
1166    DeclGroupRef DG(*I);
1167    Decl *D = *I;
1168    void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1169    DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1170
1171    // Append the fake DeclStmt to block.
1172    AppendStmt(Block, DSNew);
1173    B = VisitDeclSubExpr(D);
1174  }
1175
1176  return B;
1177}
1178
1179/// VisitDeclSubExpr - Utility method to add block-level expressions for
1180///  initializers in Decls.
1181CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
1182  assert(Block);
1183
1184  VarDecl *VD = dyn_cast<VarDecl>(D);
1185
1186  if (!VD)
1187    return Block;
1188
1189  Expr *Init = VD->getInit();
1190
1191  if (Init) {
1192    AddStmtChoice::Kind k =
1193      VD->getType()->isReferenceType() ? AddStmtChoice::AsLValueNotAlwaysAdd
1194                                       : AddStmtChoice::NotAlwaysAdd;
1195    Visit(Init, AddStmtChoice(k));
1196  }
1197
1198  // If the type of VD is a VLA, then we must process its size expressions.
1199  for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
1200       VA = FindVA(VA->getElementType().getTypePtr()))
1201    Block = addStmt(VA->getSizeExpr());
1202
1203  // Remove variable from local scope.
1204  if (ScopePos && VD == *ScopePos)
1205    ++ScopePos;
1206
1207  return Block;
1208}
1209
1210CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
1211  // We may see an if statement in the middle of a basic block, or it may be the
1212  // first statement we are processing.  In either case, we create a new basic
1213  // block.  First, we create the blocks for the then...else statements, and
1214  // then we create the block containing the if statement.  If we were in the
1215  // middle of a block, we stop processing that block.  That block is then the
1216  // implicit successor for the "then" and "else" clauses.
1217
1218  // Save local scope position because in case of condition variable ScopePos
1219  // won't be restored when traversing AST.
1220  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1221
1222  // Create local scope for possible condition variable.
1223  // Store scope position. Add implicit destructor.
1224  if (VarDecl* VD = I->getConditionVariable()) {
1225    LocalScope::const_iterator BeginScopePos = ScopePos;
1226    addLocalScopeForVarDecl(VD);
1227    addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1228  }
1229
1230  // The block we were proccessing is now finished.  Make it the successor
1231  // block.
1232  if (Block) {
1233    Succ = Block;
1234    if (badCFG)
1235      return 0;
1236  }
1237
1238  // Process the false branch.
1239  CFGBlock* ElseBlock = Succ;
1240
1241  if (Stmt* Else = I->getElse()) {
1242    SaveAndRestore<CFGBlock*> sv(Succ);
1243
1244    // NULL out Block so that the recursive call to Visit will
1245    // create a new basic block.
1246    Block = NULL;
1247
1248    // If branch is not a compound statement create implicit scope
1249    // and add destructors.
1250    if (!isa<CompoundStmt>(Else))
1251      addLocalScopeAndDtors(Else);
1252
1253    ElseBlock = addStmt(Else);
1254
1255    if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1256      ElseBlock = sv.get();
1257    else if (Block) {
1258      if (badCFG)
1259        return 0;
1260    }
1261  }
1262
1263  // Process the true branch.
1264  CFGBlock* ThenBlock;
1265  {
1266    Stmt* Then = I->getThen();
1267    assert(Then);
1268    SaveAndRestore<CFGBlock*> sv(Succ);
1269    Block = NULL;
1270
1271    // If branch is not a compound statement create implicit scope
1272    // and add destructors.
1273    if (!isa<CompoundStmt>(Then))
1274      addLocalScopeAndDtors(Then);
1275
1276    ThenBlock = addStmt(Then);
1277
1278    if (!ThenBlock) {
1279      // We can reach here if the "then" body has all NullStmts.
1280      // Create an empty block so we can distinguish between true and false
1281      // branches in path-sensitive analyses.
1282      ThenBlock = createBlock(false);
1283      AddSuccessor(ThenBlock, sv.get());
1284    } else if (Block) {
1285      if (badCFG)
1286        return 0;
1287    }
1288  }
1289
1290  // Now create a new block containing the if statement.
1291  Block = createBlock(false);
1292
1293  // Set the terminator of the new block to the If statement.
1294  Block->setTerminator(I);
1295
1296  // See if this is a known constant.
1297  const TryResult &KnownVal = TryEvaluateBool(I->getCond());
1298
1299  // Now add the successors.
1300  AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1301  AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1302
1303  // Add the condition as the last statement in the new block.  This may create
1304  // new blocks as the condition may contain control-flow.  Any newly created
1305  // blocks will be pointed to be "Block".
1306  Block = addStmt(I->getCond());
1307
1308  // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1309  // and the condition variable initialization to the CFG.
1310  if (VarDecl *VD = I->getConditionVariable()) {
1311    if (Expr *Init = VD->getInit()) {
1312      autoCreateBlock();
1313      AppendStmt(Block, I, AddStmtChoice::AlwaysAdd);
1314      addStmt(Init);
1315    }
1316  }
1317
1318  return Block;
1319}
1320
1321
1322CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
1323  // If we were in the middle of a block we stop processing that block.
1324  //
1325  // NOTE: If a "return" appears in the middle of a block, this means that the
1326  //       code afterwards is DEAD (unreachable).  We still keep a basic block
1327  //       for that code; a simple "mark-and-sweep" from the entry block will be
1328  //       able to report such dead blocks.
1329
1330  // Create the new block.
1331  Block = createBlock(false);
1332
1333  // The Exit block is the only successor.
1334  addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1335  AddSuccessor(Block, &cfg->getExit());
1336
1337  // Add the return statement to the block.  This may create new blocks if R
1338  // contains control-flow (short-circuit operations).
1339  return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1340}
1341
1342CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
1343  // Get the block of the labeled statement.  Add it to our map.
1344  addStmt(L->getSubStmt());
1345  CFGBlock* LabelBlock = Block;
1346
1347  if (!LabelBlock)              // This can happen when the body is empty, i.e.
1348    LabelBlock = createBlock(); // scopes that only contains NullStmts.
1349
1350  assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
1351  LabelMap[ L ] = JumpTarget(LabelBlock, ScopePos);
1352
1353  // Labels partition blocks, so this is the end of the basic block we were
1354  // processing (L is the block's label).  Because this is label (and we have
1355  // already processed the substatement) there is no extra control-flow to worry
1356  // about.
1357  LabelBlock->setLabel(L);
1358  if (badCFG)
1359    return 0;
1360
1361  // We set Block to NULL to allow lazy creation of a new block (if necessary);
1362  Block = NULL;
1363
1364  // This block is now the implicit successor of other blocks.
1365  Succ = LabelBlock;
1366
1367  return LabelBlock;
1368}
1369
1370CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
1371  // Goto is a control-flow statement.  Thus we stop processing the current
1372  // block and create a new one.
1373
1374  Block = createBlock(false);
1375  Block->setTerminator(G);
1376
1377  // If we already know the mapping to the label block add the successor now.
1378  LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1379
1380  if (I == LabelMap.end())
1381    // We will need to backpatch this block later.
1382    BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1383  else {
1384    JumpTarget JT = I->second;
1385    addAutomaticObjDtors(ScopePos, JT.ScopePos, G);
1386    AddSuccessor(Block, JT.Block);
1387  }
1388
1389  return Block;
1390}
1391
1392CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
1393  CFGBlock* LoopSuccessor = NULL;
1394
1395  // Save local scope position because in case of condition variable ScopePos
1396  // won't be restored when traversing AST.
1397  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1398
1399  // Create local scope for init statement and possible condition variable.
1400  // Add destructor for init statement and condition variable.
1401  // Store scope position for continue statement.
1402  if (Stmt* Init = F->getInit())
1403    addLocalScopeForStmt(Init);
1404  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1405
1406  if (VarDecl* VD = F->getConditionVariable())
1407    addLocalScopeForVarDecl(VD);
1408  LocalScope::const_iterator ContinueScopePos = ScopePos;
1409
1410  addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
1411
1412  // "for" is a control-flow statement.  Thus we stop processing the current
1413  // block.
1414  if (Block) {
1415    if (badCFG)
1416      return 0;
1417    LoopSuccessor = Block;
1418  } else
1419    LoopSuccessor = Succ;
1420
1421  // Save the current value for the break targets.
1422  // All breaks should go to the code following the loop.
1423  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
1424  BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1425
1426  // Because of short-circuit evaluation, the condition of the loop can span
1427  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1428  // evaluate the condition.
1429  CFGBlock* ExitConditionBlock = createBlock(false);
1430  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1431
1432  // Set the terminator for the "exit" condition block.
1433  ExitConditionBlock->setTerminator(F);
1434
1435  // Now add the actual condition to the condition block.  Because the condition
1436  // itself may contain control-flow, new blocks may be created.
1437  if (Stmt* C = F->getCond()) {
1438    Block = ExitConditionBlock;
1439    EntryConditionBlock = addStmt(C);
1440    assert(Block == EntryConditionBlock ||
1441           (Block == 0 && EntryConditionBlock == Succ));
1442
1443    // If this block contains a condition variable, add both the condition
1444    // variable and initializer to the CFG.
1445    if (VarDecl *VD = F->getConditionVariable()) {
1446      if (Expr *Init = VD->getInit()) {
1447        autoCreateBlock();
1448        AppendStmt(Block, F, AddStmtChoice::AlwaysAdd);
1449        EntryConditionBlock = addStmt(Init);
1450        assert(Block == EntryConditionBlock);
1451      }
1452    }
1453
1454    if (Block) {
1455      if (badCFG)
1456        return 0;
1457    }
1458  }
1459
1460  // The condition block is the implicit successor for the loop body as well as
1461  // any code above the loop.
1462  Succ = EntryConditionBlock;
1463
1464  // See if this is a known constant.
1465  TryResult KnownVal(true);
1466
1467  if (F->getCond())
1468    KnownVal = TryEvaluateBool(F->getCond());
1469
1470  // Now create the loop body.
1471  {
1472    assert(F->getBody());
1473
1474   // Save the current values for Block, Succ, and continue targets.
1475   SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1476   SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
1477
1478    // Create a new block to contain the (bottom) of the loop body.
1479    Block = NULL;
1480
1481    // Loop body should end with destructor of Condition variable (if any).
1482    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
1483
1484    if (Stmt* I = F->getInc()) {
1485      // Generate increment code in its own basic block.  This is the target of
1486      // continue statements.
1487      Succ = addStmt(I);
1488    } else {
1489      // No increment code.  Create a special, empty, block that is used as the
1490      // target block for "looping back" to the start of the loop.
1491      assert(Succ == EntryConditionBlock);
1492      Succ = Block ? Block : createBlock();
1493    }
1494
1495    // Finish up the increment (or empty) block if it hasn't been already.
1496    if (Block) {
1497      assert(Block == Succ);
1498      if (badCFG)
1499        return 0;
1500      Block = 0;
1501    }
1502
1503    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
1504
1505    // The starting block for the loop increment is the block that should
1506    // represent the 'loop target' for looping back to the start of the loop.
1507    ContinueJumpTarget.Block->setLoopTarget(F);
1508
1509    // If body is not a compound statement create implicit scope
1510    // and add destructors.
1511    if (!isa<CompoundStmt>(F->getBody()))
1512      addLocalScopeAndDtors(F->getBody());
1513
1514    // Now populate the body block, and in the process create new blocks as we
1515    // walk the body of the loop.
1516    CFGBlock* BodyBlock = addStmt(F->getBody());
1517
1518    if (!BodyBlock)
1519      BodyBlock = ContinueJumpTarget.Block;//can happen for "for (...;...;...);"
1520    else if (badCFG)
1521      return 0;
1522
1523    // This new body block is a successor to our "exit" condition block.
1524    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1525  }
1526
1527  // Link up the condition block with the code that follows the loop.  (the
1528  // false branch).
1529  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1530
1531  // If the loop contains initialization, create a new block for those
1532  // statements.  This block can also contain statements that precede the loop.
1533  if (Stmt* I = F->getInit()) {
1534    Block = createBlock();
1535    return addStmt(I);
1536  } else {
1537    // There is no loop initialization.  We are thus basically a while loop.
1538    // NULL out Block to force lazy block construction.
1539    Block = NULL;
1540    Succ = EntryConditionBlock;
1541    return EntryConditionBlock;
1542  }
1543}
1544
1545CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
1546  if (asc.alwaysAdd()) {
1547    autoCreateBlock();
1548    AppendStmt(Block, M, asc);
1549  }
1550  return Visit(M->getBase(),
1551               M->isArrow() ? AddStmtChoice::NotAlwaysAdd
1552                            : AddStmtChoice::AsLValueNotAlwaysAdd);
1553}
1554
1555CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1556  // Objective-C fast enumeration 'for' statements:
1557  //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1558  //
1559  //  for ( Type newVariable in collection_expression ) { statements }
1560  //
1561  //  becomes:
1562  //
1563  //   prologue:
1564  //     1. collection_expression
1565  //     T. jump to loop_entry
1566  //   loop_entry:
1567  //     1. side-effects of element expression
1568  //     1. ObjCForCollectionStmt [performs binding to newVariable]
1569  //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
1570  //   TB:
1571  //     statements
1572  //     T. jump to loop_entry
1573  //   FB:
1574  //     what comes after
1575  //
1576  //  and
1577  //
1578  //  Type existingItem;
1579  //  for ( existingItem in expression ) { statements }
1580  //
1581  //  becomes:
1582  //
1583  //   the same with newVariable replaced with existingItem; the binding works
1584  //   the same except that for one ObjCForCollectionStmt::getElement() returns
1585  //   a DeclStmt and the other returns a DeclRefExpr.
1586  //
1587
1588  CFGBlock* LoopSuccessor = 0;
1589
1590  if (Block) {
1591    if (badCFG)
1592      return 0;
1593    LoopSuccessor = Block;
1594    Block = 0;
1595  } else
1596    LoopSuccessor = Succ;
1597
1598  // Build the condition blocks.
1599  CFGBlock* ExitConditionBlock = createBlock(false);
1600  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1601
1602  // Set the terminator for the "exit" condition block.
1603  ExitConditionBlock->setTerminator(S);
1604
1605  // The last statement in the block should be the ObjCForCollectionStmt, which
1606  // performs the actual binding to 'element' and determines if there are any
1607  // more items in the collection.
1608  AppendStmt(ExitConditionBlock, S);
1609  Block = ExitConditionBlock;
1610
1611  // Walk the 'element' expression to see if there are any side-effects.  We
1612  // generate new blocks as necesary.  We DON'T add the statement by default to
1613  // the CFG unless it contains control-flow.
1614  EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1615  if (Block) {
1616    if (badCFG)
1617      return 0;
1618    Block = 0;
1619  }
1620
1621  // The condition block is the implicit successor for the loop body as well as
1622  // any code above the loop.
1623  Succ = EntryConditionBlock;
1624
1625  // Now create the true branch.
1626  {
1627    // Save the current values for Succ, continue and break targets.
1628    SaveAndRestore<CFGBlock*> save_Succ(Succ);
1629    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1630        save_break(BreakJumpTarget);
1631
1632    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1633    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
1634
1635    CFGBlock* BodyBlock = addStmt(S->getBody());
1636
1637    if (!BodyBlock)
1638      BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1639    else if (Block) {
1640      if (badCFG)
1641        return 0;
1642    }
1643
1644    // This new body block is a successor to our "exit" condition block.
1645    AddSuccessor(ExitConditionBlock, BodyBlock);
1646  }
1647
1648  // Link up the condition block with the code that follows the loop.
1649  // (the false branch).
1650  AddSuccessor(ExitConditionBlock, LoopSuccessor);
1651
1652  // Now create a prologue block to contain the collection expression.
1653  Block = createBlock();
1654  return addStmt(S->getCollection());
1655}
1656
1657CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1658  // FIXME: Add locking 'primitives' to CFG for @synchronized.
1659
1660  // Inline the body.
1661  CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1662
1663  // The sync body starts its own basic block.  This makes it a little easier
1664  // for diagnostic clients.
1665  if (SyncBlock) {
1666    if (badCFG)
1667      return 0;
1668
1669    Block = 0;
1670    Succ = SyncBlock;
1671  }
1672
1673  // Add the @synchronized to the CFG.
1674  autoCreateBlock();
1675  AppendStmt(Block, S, AddStmtChoice::AlwaysAdd);
1676
1677  // Inline the sync expression.
1678  return addStmt(S->getSynchExpr());
1679}
1680
1681CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1682  // FIXME
1683  return NYS();
1684}
1685
1686CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1687  CFGBlock* LoopSuccessor = NULL;
1688
1689  // Save local scope position because in case of condition variable ScopePos
1690  // won't be restored when traversing AST.
1691  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1692
1693  // Create local scope for possible condition variable.
1694  // Store scope position for continue statement.
1695  LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1696  if (VarDecl* VD = W->getConditionVariable()) {
1697    addLocalScopeForVarDecl(VD);
1698    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1699  }
1700
1701  // "while" is a control-flow statement.  Thus we stop processing the current
1702  // block.
1703  if (Block) {
1704    if (badCFG)
1705      return 0;
1706    LoopSuccessor = Block;
1707  } else
1708    LoopSuccessor = Succ;
1709
1710  // Because of short-circuit evaluation, the condition of the loop can span
1711  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1712  // evaluate the condition.
1713  CFGBlock* ExitConditionBlock = createBlock(false);
1714  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1715
1716  // Set the terminator for the "exit" condition block.
1717  ExitConditionBlock->setTerminator(W);
1718
1719  // Now add the actual condition to the condition block.  Because the condition
1720  // itself may contain control-flow, new blocks may be created.  Thus we update
1721  // "Succ" after adding the condition.
1722  if (Stmt* C = W->getCond()) {
1723    Block = ExitConditionBlock;
1724    EntryConditionBlock = addStmt(C);
1725    assert(Block == EntryConditionBlock);
1726
1727    // If this block contains a condition variable, add both the condition
1728    // variable and initializer to the CFG.
1729    if (VarDecl *VD = W->getConditionVariable()) {
1730      if (Expr *Init = VD->getInit()) {
1731        autoCreateBlock();
1732        AppendStmt(Block, W, AddStmtChoice::AlwaysAdd);
1733        EntryConditionBlock = addStmt(Init);
1734        assert(Block == EntryConditionBlock);
1735      }
1736    }
1737
1738    if (Block) {
1739      if (badCFG)
1740        return 0;
1741    }
1742  }
1743
1744  // The condition block is the implicit successor for the loop body as well as
1745  // any code above the loop.
1746  Succ = EntryConditionBlock;
1747
1748  // See if this is a known constant.
1749  const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1750
1751  // Process the loop body.
1752  {
1753    assert(W->getBody());
1754
1755    // Save the current values for Block, Succ, and continue and break targets
1756    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1757    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1758        save_break(BreakJumpTarget);
1759
1760    // Create an empty block to represent the transition block for looping back
1761    // to the head of the loop.
1762    Block = 0;
1763    assert(Succ == EntryConditionBlock);
1764    Succ = createBlock();
1765    Succ->setLoopTarget(W);
1766    ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
1767
1768    // All breaks should go to the code following the loop.
1769    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1770
1771    // NULL out Block to force lazy instantiation of blocks for the body.
1772    Block = NULL;
1773
1774    // Loop body should end with destructor of Condition variable (if any).
1775    addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
1776
1777    // If body is not a compound statement create implicit scope
1778    // and add destructors.
1779    if (!isa<CompoundStmt>(W->getBody()))
1780      addLocalScopeAndDtors(W->getBody());
1781
1782    // Create the body.  The returned block is the entry to the loop body.
1783    CFGBlock* BodyBlock = addStmt(W->getBody());
1784
1785    if (!BodyBlock)
1786      BodyBlock = ContinueJumpTarget.Block; // can happen for "while(...) ;"
1787    else if (Block) {
1788      if (badCFG)
1789        return 0;
1790    }
1791
1792    // Add the loop body entry as a successor to the condition.
1793    AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1794  }
1795
1796  // Link up the condition block with the code that follows the loop.  (the
1797  // false branch).
1798  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1799
1800  // There can be no more statements in the condition block since we loop back
1801  // to this block.  NULL out Block to force lazy creation of another block.
1802  Block = NULL;
1803
1804  // Return the condition block, which is the dominating block for the loop.
1805  Succ = EntryConditionBlock;
1806  return EntryConditionBlock;
1807}
1808
1809
1810CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1811  // FIXME: For now we pretend that @catch and the code it contains does not
1812  //  exit.
1813  return Block;
1814}
1815
1816CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1817  // FIXME: This isn't complete.  We basically treat @throw like a return
1818  //  statement.
1819
1820  // If we were in the middle of a block we stop processing that block.
1821  if (badCFG)
1822    return 0;
1823
1824  // Create the new block.
1825  Block = createBlock(false);
1826
1827  // The Exit block is the only successor.
1828  AddSuccessor(Block, &cfg->getExit());
1829
1830  // Add the statement to the block.  This may create new blocks if S contains
1831  // control-flow (short-circuit operations).
1832  return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1833}
1834
1835CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1836  // If we were in the middle of a block we stop processing that block.
1837  if (badCFG)
1838    return 0;
1839
1840  // Create the new block.
1841  Block = createBlock(false);
1842
1843  if (TryTerminatedBlock)
1844    // The current try statement is the only successor.
1845    AddSuccessor(Block, TryTerminatedBlock);
1846  else
1847    // otherwise the Exit block is the only successor.
1848    AddSuccessor(Block, &cfg->getExit());
1849
1850  // Add the statement to the block.  This may create new blocks if S contains
1851  // control-flow (short-circuit operations).
1852  return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1853}
1854
1855CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1856  CFGBlock* LoopSuccessor = NULL;
1857
1858  // "do...while" is a control-flow statement.  Thus we stop processing the
1859  // current block.
1860  if (Block) {
1861    if (badCFG)
1862      return 0;
1863    LoopSuccessor = Block;
1864  } else
1865    LoopSuccessor = Succ;
1866
1867  // Because of short-circuit evaluation, the condition of the loop can span
1868  // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
1869  // evaluate the condition.
1870  CFGBlock* ExitConditionBlock = createBlock(false);
1871  CFGBlock* EntryConditionBlock = ExitConditionBlock;
1872
1873  // Set the terminator for the "exit" condition block.
1874  ExitConditionBlock->setTerminator(D);
1875
1876  // Now add the actual condition to the condition block.  Because the condition
1877  // itself may contain control-flow, new blocks may be created.
1878  if (Stmt* C = D->getCond()) {
1879    Block = ExitConditionBlock;
1880    EntryConditionBlock = addStmt(C);
1881    if (Block) {
1882      if (badCFG)
1883        return 0;
1884    }
1885  }
1886
1887  // The condition block is the implicit successor for the loop body.
1888  Succ = EntryConditionBlock;
1889
1890  // See if this is a known constant.
1891  const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1892
1893  // Process the loop body.
1894  CFGBlock* BodyBlock = NULL;
1895  {
1896    assert(D->getBody());
1897
1898    // Save the current values for Block, Succ, and continue and break targets
1899    SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
1900    SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
1901        save_break(BreakJumpTarget);
1902
1903    // All continues within this loop should go to the condition block
1904    ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
1905
1906    // All breaks should go to the code following the loop.
1907    BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
1908
1909    // NULL out Block to force lazy instantiation of blocks for the body.
1910    Block = NULL;
1911
1912    // If body is not a compound statement create implicit scope
1913    // and add destructors.
1914    if (!isa<CompoundStmt>(D->getBody()))
1915      addLocalScopeAndDtors(D->getBody());
1916
1917    // Create the body.  The returned block is the entry to the loop body.
1918    BodyBlock = addStmt(D->getBody());
1919
1920    if (!BodyBlock)
1921      BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1922    else if (Block) {
1923      if (badCFG)
1924        return 0;
1925    }
1926
1927    if (!KnownVal.isFalse()) {
1928      // Add an intermediate block between the BodyBlock and the
1929      // ExitConditionBlock to represent the "loop back" transition.  Create an
1930      // empty block to represent the transition block for looping back to the
1931      // head of the loop.
1932      // FIXME: Can we do this more efficiently without adding another block?
1933      Block = NULL;
1934      Succ = BodyBlock;
1935      CFGBlock *LoopBackBlock = createBlock();
1936      LoopBackBlock->setLoopTarget(D);
1937
1938      // Add the loop body entry as a successor to the condition.
1939      AddSuccessor(ExitConditionBlock, LoopBackBlock);
1940    }
1941    else
1942      AddSuccessor(ExitConditionBlock, NULL);
1943  }
1944
1945  // Link up the condition block with the code that follows the loop.
1946  // (the false branch).
1947  AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1948
1949  // There can be no more statements in the body block(s) since we loop back to
1950  // the body.  NULL out Block to force lazy creation of another block.
1951  Block = NULL;
1952
1953  // Return the loop body, which is the dominating block for the loop.
1954  Succ = BodyBlock;
1955  return BodyBlock;
1956}
1957
1958CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1959  // "continue" is a control-flow statement.  Thus we stop processing the
1960  // current block.
1961  if (badCFG)
1962    return 0;
1963
1964  // Now create a new block that ends with the continue statement.
1965  Block = createBlock(false);
1966  Block->setTerminator(C);
1967
1968  // If there is no target for the continue, then we are looking at an
1969  // incomplete AST.  This means the CFG cannot be constructed.
1970  if (ContinueJumpTarget.Block) {
1971    addAutomaticObjDtors(ScopePos, ContinueJumpTarget.ScopePos, C);
1972    AddSuccessor(Block, ContinueJumpTarget.Block);
1973  } else
1974    badCFG = true;
1975
1976  return Block;
1977}
1978
1979CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1980                                             AddStmtChoice asc) {
1981
1982  if (asc.alwaysAdd()) {
1983    autoCreateBlock();
1984    AppendStmt(Block, E);
1985  }
1986
1987  // VLA types have expressions that must be evaluated.
1988  if (E->isArgumentType()) {
1989    for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1990         VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1991      addStmt(VA->getSizeExpr());
1992  }
1993
1994  return Block;
1995}
1996
1997/// VisitStmtExpr - Utility method to handle (nested) statement
1998///  expressions (a GCC extension).
1999CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2000  if (asc.alwaysAdd()) {
2001    autoCreateBlock();
2002    AppendStmt(Block, SE);
2003  }
2004  return VisitCompoundStmt(SE->getSubStmt());
2005}
2006
2007CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
2008  // "switch" is a control-flow statement.  Thus we stop processing the current
2009  // block.
2010  CFGBlock* SwitchSuccessor = NULL;
2011
2012  // Save local scope position because in case of condition variable ScopePos
2013  // won't be restored when traversing AST.
2014  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2015
2016  // Create local scope for possible condition variable.
2017  // Store scope position. Add implicit destructor.
2018  if (VarDecl* VD = Terminator->getConditionVariable()) {
2019    LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2020    addLocalScopeForVarDecl(VD);
2021    addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2022  }
2023
2024  if (Block) {
2025    if (badCFG)
2026      return 0;
2027    SwitchSuccessor = Block;
2028  } else SwitchSuccessor = Succ;
2029
2030  // Save the current "switch" context.
2031  SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2032                            save_default(DefaultCaseBlock);
2033  SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2034
2035  // Set the "default" case to be the block after the switch statement.  If the
2036  // switch statement contains a "default:", this value will be overwritten with
2037  // the block for that code.
2038  DefaultCaseBlock = SwitchSuccessor;
2039
2040  // Create a new block that will contain the switch statement.
2041  SwitchTerminatedBlock = createBlock(false);
2042
2043  // Now process the switch body.  The code after the switch is the implicit
2044  // successor.
2045  Succ = SwitchSuccessor;
2046  BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2047
2048  // When visiting the body, the case statements should automatically get linked
2049  // up to the switch.  We also don't keep a pointer to the body, since all
2050  // control-flow from the switch goes to case/default statements.
2051  assert(Terminator->getBody() && "switch must contain a non-NULL body");
2052  Block = NULL;
2053
2054  // If body is not a compound statement create implicit scope
2055  // and add destructors.
2056  if (!isa<CompoundStmt>(Terminator->getBody()))
2057    addLocalScopeAndDtors(Terminator->getBody());
2058
2059  addStmt(Terminator->getBody());
2060  if (Block) {
2061    if (badCFG)
2062      return 0;
2063  }
2064
2065  // If we have no "default:" case, the default transition is to the code
2066  // following the switch body.
2067  AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
2068
2069  // Add the terminator and condition in the switch block.
2070  SwitchTerminatedBlock->setTerminator(Terminator);
2071  assert(Terminator->getCond() && "switch condition must be non-NULL");
2072  Block = SwitchTerminatedBlock;
2073  Block = addStmt(Terminator->getCond());
2074
2075  // Finally, if the SwitchStmt contains a condition variable, add both the
2076  // SwitchStmt and the condition variable initialization to the CFG.
2077  if (VarDecl *VD = Terminator->getConditionVariable()) {
2078    if (Expr *Init = VD->getInit()) {
2079      autoCreateBlock();
2080      AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd);
2081      addStmt(Init);
2082    }
2083  }
2084
2085  return Block;
2086}
2087
2088CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
2089  // CaseStmts are essentially labels, so they are the first statement in a
2090  // block.
2091  CFGBlock *TopBlock = 0, *LastBlock = 0;
2092
2093  if (Stmt *Sub = CS->getSubStmt()) {
2094    // For deeply nested chains of CaseStmts, instead of doing a recursion
2095    // (which can blow out the stack), manually unroll and create blocks
2096    // along the way.
2097    while (isa<CaseStmt>(Sub)) {
2098      CFGBlock *CurrentBlock = createBlock(false);
2099      CurrentBlock->setLabel(CS);
2100
2101      if (TopBlock)
2102        AddSuccessor(LastBlock, CurrentBlock);
2103      else
2104        TopBlock = CurrentBlock;
2105
2106      AddSuccessor(SwitchTerminatedBlock, CurrentBlock);
2107      LastBlock = CurrentBlock;
2108
2109      CS = cast<CaseStmt>(Sub);
2110      Sub = CS->getSubStmt();
2111    }
2112
2113    addStmt(Sub);
2114  }
2115
2116  CFGBlock* CaseBlock = Block;
2117  if (!CaseBlock)
2118    CaseBlock = createBlock();
2119
2120  // Cases statements partition blocks, so this is the top of the basic block we
2121  // were processing (the "case XXX:" is the label).
2122  CaseBlock->setLabel(CS);
2123
2124  if (badCFG)
2125    return 0;
2126
2127  // Add this block to the list of successors for the block with the switch
2128  // statement.
2129  assert(SwitchTerminatedBlock);
2130  AddSuccessor(SwitchTerminatedBlock, CaseBlock);
2131
2132  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2133  Block = NULL;
2134
2135  if (TopBlock) {
2136    AddSuccessor(LastBlock, CaseBlock);
2137    Succ = TopBlock;
2138  }
2139  else {
2140    // This block is now the implicit successor of other blocks.
2141    Succ = CaseBlock;
2142  }
2143
2144  return Succ;
2145}
2146
2147CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
2148  if (Terminator->getSubStmt())
2149    addStmt(Terminator->getSubStmt());
2150
2151  DefaultCaseBlock = Block;
2152
2153  if (!DefaultCaseBlock)
2154    DefaultCaseBlock = createBlock();
2155
2156  // Default statements partition blocks, so this is the top of the basic block
2157  // we were processing (the "default:" is the label).
2158  DefaultCaseBlock->setLabel(Terminator);
2159
2160  if (badCFG)
2161    return 0;
2162
2163  // Unlike case statements, we don't add the default block to the successors
2164  // for the switch statement immediately.  This is done when we finish
2165  // processing the switch statement.  This allows for the default case
2166  // (including a fall-through to the code after the switch statement) to always
2167  // be the last successor of a switch-terminated block.
2168
2169  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2170  Block = NULL;
2171
2172  // This block is now the implicit successor of other blocks.
2173  Succ = DefaultCaseBlock;
2174
2175  return DefaultCaseBlock;
2176}
2177
2178CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2179  // "try"/"catch" is a control-flow statement.  Thus we stop processing the
2180  // current block.
2181  CFGBlock* TrySuccessor = NULL;
2182
2183  if (Block) {
2184    if (badCFG)
2185      return 0;
2186    TrySuccessor = Block;
2187  } else TrySuccessor = Succ;
2188
2189  CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2190
2191  // Create a new block that will contain the try statement.
2192  CFGBlock *NewTryTerminatedBlock = createBlock(false);
2193  // Add the terminator in the try block.
2194  NewTryTerminatedBlock->setTerminator(Terminator);
2195
2196  bool HasCatchAll = false;
2197  for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2198    // The code after the try is the implicit successor.
2199    Succ = TrySuccessor;
2200    CXXCatchStmt *CS = Terminator->getHandler(h);
2201    if (CS->getExceptionDecl() == 0) {
2202      HasCatchAll = true;
2203    }
2204    Block = NULL;
2205    CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2206    if (CatchBlock == 0)
2207      return 0;
2208    // Add this block to the list of successors for the block with the try
2209    // statement.
2210    AddSuccessor(NewTryTerminatedBlock, CatchBlock);
2211  }
2212  if (!HasCatchAll) {
2213    if (PrevTryTerminatedBlock)
2214      AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2215    else
2216      AddSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2217  }
2218
2219  // The code after the try is the implicit successor.
2220  Succ = TrySuccessor;
2221
2222  // Save the current "try" context.
2223  SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
2224  TryTerminatedBlock = NewTryTerminatedBlock;
2225
2226  assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2227  Block = NULL;
2228  Block = addStmt(Terminator->getTryBlock());
2229  return Block;
2230}
2231
2232CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
2233  // CXXCatchStmt are treated like labels, so they are the first statement in a
2234  // block.
2235
2236  // Save local scope position because in case of exception variable ScopePos
2237  // won't be restored when traversing AST.
2238  SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2239
2240  // Create local scope for possible exception variable.
2241  // Store scope position. Add implicit destructor.
2242  if (VarDecl* VD = CS->getExceptionDecl()) {
2243    LocalScope::const_iterator BeginScopePos = ScopePos;
2244    addLocalScopeForVarDecl(VD);
2245    addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2246  }
2247
2248  if (CS->getHandlerBlock())
2249    addStmt(CS->getHandlerBlock());
2250
2251  CFGBlock* CatchBlock = Block;
2252  if (!CatchBlock)
2253    CatchBlock = createBlock();
2254
2255  CatchBlock->setLabel(CS);
2256
2257  if (badCFG)
2258    return 0;
2259
2260  // We set Block to NULL to allow lazy creation of a new block (if necessary)
2261  Block = NULL;
2262
2263  return CatchBlock;
2264}
2265
2266CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C,
2267                                             AddStmtChoice asc) {
2268  AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
2269                                         : AddStmtChoice::AlwaysAdd;
2270  autoCreateBlock();
2271  AppendStmt(Block, C, AddStmtChoice(K));
2272  return VisitChildren(C);
2273}
2274
2275CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2276  // Lazily create the indirect-goto dispatch block if there isn't one already.
2277  CFGBlock* IBlock = cfg->getIndirectGotoBlock();
2278
2279  if (!IBlock) {
2280    IBlock = createBlock(false);
2281    cfg->setIndirectGotoBlock(IBlock);
2282  }
2283
2284  // IndirectGoto is a control-flow statement.  Thus we stop processing the
2285  // current block and create a new one.
2286  if (badCFG)
2287    return 0;
2288
2289  Block = createBlock(false);
2290  Block->setTerminator(I);
2291  AddSuccessor(Block, IBlock);
2292  return addStmt(I->getTarget());
2293}
2294
2295} // end anonymous namespace
2296
2297/// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
2298///  no successors or predecessors.  If this is the first block created in the
2299///  CFG, it is automatically set to be the Entry and Exit of the CFG.
2300CFGBlock* CFG::createBlock() {
2301  bool first_block = begin() == end();
2302
2303  // Create the block.
2304  CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
2305  new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
2306  Blocks.push_back(Mem, BlkBVC);
2307
2308  // If this is the first block, set it as the Entry and Exit.
2309  if (first_block)
2310    Entry = Exit = &back();
2311
2312  // Return the block.
2313  return &back();
2314}
2315
2316/// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
2317///  CFG is returned to the caller.
2318CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
2319    BuildOptions BO) {
2320  CFGBuilder Builder;
2321  return Builder.buildCFG(D, Statement, C, BO);
2322}
2323
2324//===----------------------------------------------------------------------===//
2325// CFG: Queries for BlkExprs.
2326//===----------------------------------------------------------------------===//
2327
2328namespace {
2329  typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
2330}
2331
2332static void FindSubExprAssignments(Stmt *S,
2333                                   llvm::SmallPtrSet<Expr*,50>& Set) {
2334  if (!S)
2335    return;
2336
2337  for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
2338    Stmt *child = *I;
2339    if (!child)
2340      continue;
2341
2342    if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
2343      if (B->isAssignmentOp()) Set.insert(B);
2344
2345    FindSubExprAssignments(child, Set);
2346  }
2347}
2348
2349static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
2350  BlkExprMapTy* M = new BlkExprMapTy();
2351
2352  // Look for assignments that are used as subexpressions.  These are the only
2353  // assignments that we want to *possibly* register as a block-level
2354  // expression.  Basically, if an assignment occurs both in a subexpression and
2355  // at the block-level, it is a block-level expression.
2356  llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
2357
2358  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
2359    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
2360      if (CFGStmt S = BI->getAs<CFGStmt>())
2361        FindSubExprAssignments(S, SubExprAssignments);
2362
2363  for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
2364
2365    // Iterate over the statements again on identify the Expr* and Stmt* at the
2366    // block-level that are block-level expressions.
2367
2368    for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) {
2369      CFGStmt CS = BI->getAs<CFGStmt>();
2370      if (!CS.isValid())
2371        continue;
2372      if (Expr* Exp = dyn_cast<Expr>(CS.getStmt())) {
2373
2374        if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
2375          // Assignment expressions that are not nested within another
2376          // expression are really "statements" whose value is never used by
2377          // another expression.
2378          if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
2379            continue;
2380        } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
2381          // Special handling for statement expressions.  The last statement in
2382          // the statement expression is also a block-level expr.
2383          const CompoundStmt* C = Terminator->getSubStmt();
2384          if (!C->body_empty()) {
2385            unsigned x = M->size();
2386            (*M)[C->body_back()] = x;
2387          }
2388        }
2389
2390        unsigned x = M->size();
2391        (*M)[Exp] = x;
2392      }
2393    }
2394
2395    // Look at terminators.  The condition is a block-level expression.
2396
2397    Stmt* S = (*I)->getTerminatorCondition();
2398
2399    if (S && M->find(S) == M->end()) {
2400        unsigned x = M->size();
2401        (*M)[S] = x;
2402    }
2403  }
2404
2405  return M;
2406}
2407
2408CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
2409  assert(S != NULL);
2410  if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
2411
2412  BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
2413  BlkExprMapTy::iterator I = M->find(S);
2414  return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
2415}
2416
2417unsigned CFG::getNumBlkExprs() {
2418  if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
2419    return M->size();
2420  else {
2421    // We assume callers interested in the number of BlkExprs will want
2422    // the map constructed if it doesn't already exist.
2423    BlkExprMap = (void*) PopulateBlkExprMap(*this);
2424    return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
2425  }
2426}
2427
2428//===----------------------------------------------------------------------===//
2429// Filtered walking of the CFG.
2430//===----------------------------------------------------------------------===//
2431
2432bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
2433        const CFGBlock *From, const CFGBlock *To) {
2434
2435  if (F.IgnoreDefaultsWithCoveredEnums) {
2436    // If the 'To' has no label or is labeled but the label isn't a
2437    // CaseStmt then filter this edge.
2438    if (const SwitchStmt *S =
2439  dyn_cast_or_null<SwitchStmt>(From->getTerminator())) {
2440      if (S->isAllEnumCasesCovered()) {
2441  const Stmt *L = To->getLabel();
2442  if (!L || !isa<CaseStmt>(L))
2443    return true;
2444      }
2445    }
2446  }
2447
2448  return false;
2449}
2450
2451//===----------------------------------------------------------------------===//
2452// Cleanup: CFG dstor.
2453//===----------------------------------------------------------------------===//
2454
2455CFG::~CFG() {
2456  delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
2457}
2458
2459//===----------------------------------------------------------------------===//
2460// CFG pretty printing
2461//===----------------------------------------------------------------------===//
2462
2463namespace {
2464
2465class StmtPrinterHelper : public PrinterHelper  {
2466  typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
2467  typedef llvm::DenseMap<Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
2468  StmtMapTy StmtMap;
2469  DeclMapTy DeclMap;
2470  signed CurrentBlock;
2471  unsigned CurrentStmt;
2472  const LangOptions &LangOpts;
2473public:
2474
2475  StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
2476    : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
2477    for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
2478      unsigned j = 1;
2479      for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
2480           BI != BEnd; ++BI, ++j ) {
2481        if (CFGStmt SE = BI->getAs<CFGStmt>()) {
2482          std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
2483          StmtMap[SE] = P;
2484
2485          if (DeclStmt* DS = dyn_cast<DeclStmt>(SE.getStmt())) {
2486              DeclMap[DS->getSingleDecl()] = P;
2487
2488          } else if (IfStmt* IS = dyn_cast<IfStmt>(SE.getStmt())) {
2489            if (VarDecl* VD = IS->getConditionVariable())
2490              DeclMap[VD] = P;
2491
2492          } else if (ForStmt* FS = dyn_cast<ForStmt>(SE.getStmt())) {
2493            if (VarDecl* VD = FS->getConditionVariable())
2494              DeclMap[VD] = P;
2495
2496          } else if (WhileStmt* WS = dyn_cast<WhileStmt>(SE.getStmt())) {
2497            if (VarDecl* VD = WS->getConditionVariable())
2498              DeclMap[VD] = P;
2499
2500          } else if (SwitchStmt* SS = dyn_cast<SwitchStmt>(SE.getStmt())) {
2501            if (VarDecl* VD = SS->getConditionVariable())
2502              DeclMap[VD] = P;
2503
2504          } else if (CXXCatchStmt* CS = dyn_cast<CXXCatchStmt>(SE.getStmt())) {
2505            if (VarDecl* VD = CS->getExceptionDecl())
2506              DeclMap[VD] = P;
2507          }
2508        }
2509      }
2510    }
2511  }
2512
2513  virtual ~StmtPrinterHelper() {}
2514
2515  const LangOptions &getLangOpts() const { return LangOpts; }
2516  void setBlockID(signed i) { CurrentBlock = i; }
2517  void setStmtID(unsigned i) { CurrentStmt = i; }
2518
2519  virtual bool handledStmt(Stmt* S, llvm::raw_ostream& OS) {
2520    StmtMapTy::iterator I = StmtMap.find(S);
2521
2522    if (I == StmtMap.end())
2523      return false;
2524
2525    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
2526                          && I->second.second == CurrentStmt) {
2527      return false;
2528    }
2529
2530    OS << "[B" << I->second.first << "." << I->second.second << "]";
2531    return true;
2532  }
2533
2534  bool handleDecl(Decl* D, llvm::raw_ostream& OS) {
2535    DeclMapTy::iterator I = DeclMap.find(D);
2536
2537    if (I == DeclMap.end())
2538      return false;
2539
2540    if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
2541                          && I->second.second == CurrentStmt) {
2542      return false;
2543    }
2544
2545    OS << "[B" << I->second.first << "." << I->second.second << "]";
2546    return true;
2547  }
2548};
2549} // end anonymous namespace
2550
2551
2552namespace {
2553class CFGBlockTerminatorPrint
2554  : public StmtVisitor<CFGBlockTerminatorPrint,void> {
2555
2556  llvm::raw_ostream& OS;
2557  StmtPrinterHelper* Helper;
2558  PrintingPolicy Policy;
2559public:
2560  CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
2561                          const PrintingPolicy &Policy)
2562    : OS(os), Helper(helper), Policy(Policy) {}
2563
2564  void VisitIfStmt(IfStmt* I) {
2565    OS << "if ";
2566    I->getCond()->printPretty(OS,Helper,Policy);
2567  }
2568
2569  // Default case.
2570  void VisitStmt(Stmt* Terminator) {
2571    Terminator->printPretty(OS, Helper, Policy);
2572  }
2573
2574  void VisitForStmt(ForStmt* F) {
2575    OS << "for (" ;
2576    if (F->getInit())
2577      OS << "...";
2578    OS << "; ";
2579    if (Stmt* C = F->getCond())
2580      C->printPretty(OS, Helper, Policy);
2581    OS << "; ";
2582    if (F->getInc())
2583      OS << "...";
2584    OS << ")";
2585  }
2586
2587  void VisitWhileStmt(WhileStmt* W) {
2588    OS << "while " ;
2589    if (Stmt* C = W->getCond())
2590      C->printPretty(OS, Helper, Policy);
2591  }
2592
2593  void VisitDoStmt(DoStmt* D) {
2594    OS << "do ... while ";
2595    if (Stmt* C = D->getCond())
2596      C->printPretty(OS, Helper, Policy);
2597  }
2598
2599  void VisitSwitchStmt(SwitchStmt* Terminator) {
2600    OS << "switch ";
2601    Terminator->getCond()->printPretty(OS, Helper, Policy);
2602  }
2603
2604  void VisitCXXTryStmt(CXXTryStmt* CS) {
2605    OS << "try ...";
2606  }
2607
2608  void VisitConditionalOperator(ConditionalOperator* C) {
2609    C->getCond()->printPretty(OS, Helper, Policy);
2610    OS << " ? ... : ...";
2611  }
2612
2613  void VisitChooseExpr(ChooseExpr* C) {
2614    OS << "__builtin_choose_expr( ";
2615    C->getCond()->printPretty(OS, Helper, Policy);
2616    OS << " )";
2617  }
2618
2619  void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2620    OS << "goto *";
2621    I->getTarget()->printPretty(OS, Helper, Policy);
2622  }
2623
2624  void VisitBinaryOperator(BinaryOperator* B) {
2625    if (!B->isLogicalOp()) {
2626      VisitExpr(B);
2627      return;
2628    }
2629
2630    B->getLHS()->printPretty(OS, Helper, Policy);
2631
2632    switch (B->getOpcode()) {
2633      case BO_LOr:
2634        OS << " || ...";
2635        return;
2636      case BO_LAnd:
2637        OS << " && ...";
2638        return;
2639      default:
2640        assert(false && "Invalid logical operator.");
2641    }
2642  }
2643
2644  void VisitExpr(Expr* E) {
2645    E->printPretty(OS, Helper, Policy);
2646  }
2647};
2648} // end anonymous namespace
2649
2650static void print_elem(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
2651                       const CFGElement &E) {
2652  if (CFGStmt CS = E.getAs<CFGStmt>()) {
2653    Stmt *S = CS;
2654
2655    if (Helper) {
2656
2657      // special printing for statement-expressions.
2658      if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
2659        CompoundStmt* Sub = SE->getSubStmt();
2660
2661        if (Sub->child_begin() != Sub->child_end()) {
2662          OS << "({ ... ; ";
2663          Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
2664          OS << " })\n";
2665          return;
2666        }
2667      }
2668      // special printing for comma expressions.
2669      if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
2670        if (B->getOpcode() == BO_Comma) {
2671          OS << "... , ";
2672          Helper->handledStmt(B->getRHS(),OS);
2673          OS << '\n';
2674          return;
2675        }
2676      }
2677    }
2678    S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2679
2680    if (isa<CXXOperatorCallExpr>(S)) {
2681      OS << " (OperatorCall)";
2682    }
2683    else if (isa<CXXBindTemporaryExpr>(S)) {
2684      OS << " (BindTemporary)";
2685    }
2686
2687    // Expressions need a newline.
2688    if (isa<Expr>(S))
2689      OS << '\n';
2690
2691  } else if (CFGInitializer IE = E.getAs<CFGInitializer>()) {
2692    CXXBaseOrMemberInitializer* I = IE;
2693    if (I->isBaseInitializer())
2694      OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
2695    else OS << I->getMember()->getName();
2696
2697    OS << "(";
2698    if (Expr* IE = I->getInit())
2699      IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2700    OS << ")";
2701
2702    if (I->isBaseInitializer())
2703      OS << " (Base initializer)\n";
2704    else OS << " (Member initializer)\n";
2705
2706  } else if (CFGAutomaticObjDtor DE = E.getAs<CFGAutomaticObjDtor>()){
2707    VarDecl* VD = DE.getVarDecl();
2708    Helper->handleDecl(VD, OS);
2709
2710    Type* T = VD->getType().getTypePtr();
2711    if (const ReferenceType* RT = T->getAs<ReferenceType>())
2712      T = RT->getPointeeType().getTypePtr();
2713
2714    OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
2715    OS << " (Implicit destructor)\n";
2716
2717  } else if (CFGBaseDtor BE = E.getAs<CFGBaseDtor>()) {
2718    const CXXBaseSpecifier *BS = BE.getBaseSpecifier();
2719    OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
2720    OS << " (Base object destructor)\n";
2721
2722  } else if (CFGMemberDtor ME = E.getAs<CFGMemberDtor>()) {
2723    FieldDecl *FD = ME.getFieldDecl();
2724    OS << "this->" << FD->getName();
2725    OS << ".~" << FD->getType()->getAsCXXRecordDecl()->getName() << "()";
2726    OS << " (Member object destructor)\n";
2727  }
2728 }
2729
2730static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
2731                        const CFGBlock& B,
2732                        StmtPrinterHelper* Helper, bool print_edges) {
2733
2734  if (Helper) Helper->setBlockID(B.getBlockID());
2735
2736  // Print the header.
2737  OS << "\n [ B" << B.getBlockID();
2738
2739  if (&B == &cfg->getEntry())
2740    OS << " (ENTRY) ]\n";
2741  else if (&B == &cfg->getExit())
2742    OS << " (EXIT) ]\n";
2743  else if (&B == cfg->getIndirectGotoBlock())
2744    OS << " (INDIRECT GOTO DISPATCH) ]\n";
2745  else
2746    OS << " ]\n";
2747
2748  // Print the label of this block.
2749  if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
2750
2751    if (print_edges)
2752      OS << "    ";
2753
2754    if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
2755      OS << L->getName();
2756    else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
2757      OS << "case ";
2758      C->getLHS()->printPretty(OS, Helper,
2759                               PrintingPolicy(Helper->getLangOpts()));
2760      if (C->getRHS()) {
2761        OS << " ... ";
2762        C->getRHS()->printPretty(OS, Helper,
2763                                 PrintingPolicy(Helper->getLangOpts()));
2764      }
2765    } else if (isa<DefaultStmt>(Label))
2766      OS << "default";
2767    else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
2768      OS << "catch (";
2769      if (CS->getExceptionDecl())
2770        CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
2771                                      0);
2772      else
2773        OS << "...";
2774      OS << ")";
2775
2776    } else
2777      assert(false && "Invalid label statement in CFGBlock.");
2778
2779    OS << ":\n";
2780  }
2781
2782  // Iterate through the statements in the block and print them.
2783  unsigned j = 1;
2784
2785  for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
2786       I != E ; ++I, ++j ) {
2787
2788    // Print the statement # in the basic block and the statement itself.
2789    if (print_edges)
2790      OS << "    ";
2791
2792    OS << llvm::format("%3d", j) << ": ";
2793
2794    if (Helper)
2795      Helper->setStmtID(j);
2796
2797    print_elem(OS,Helper,*I);
2798  }
2799
2800  // Print the terminator of this block.
2801  if (B.getTerminator()) {
2802    if (print_edges)
2803      OS << "    ";
2804
2805    OS << "  T: ";
2806
2807    if (Helper) Helper->setBlockID(-1);
2808
2809    CFGBlockTerminatorPrint TPrinter(OS, Helper,
2810                                     PrintingPolicy(Helper->getLangOpts()));
2811    TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
2812    OS << '\n';
2813  }
2814
2815  if (print_edges) {
2816    // Print the predecessors of this block.
2817    OS << "    Predecessors (" << B.pred_size() << "):";
2818    unsigned i = 0;
2819
2820    for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
2821         I != E; ++I, ++i) {
2822
2823      if (i == 8 || (i-8) == 0)
2824        OS << "\n     ";
2825
2826      OS << " B" << (*I)->getBlockID();
2827    }
2828
2829    OS << '\n';
2830
2831    // Print the successors of this block.
2832    OS << "    Successors (" << B.succ_size() << "):";
2833    i = 0;
2834
2835    for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
2836         I != E; ++I, ++i) {
2837
2838      if (i == 8 || (i-8) % 10 == 0)
2839        OS << "\n    ";
2840
2841      if (*I)
2842        OS << " B" << (*I)->getBlockID();
2843      else
2844        OS  << " NULL";
2845    }
2846
2847    OS << '\n';
2848  }
2849}
2850
2851
2852/// dump - A simple pretty printer of a CFG that outputs to stderr.
2853void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
2854
2855/// print - A simple pretty printer of a CFG that outputs to an ostream.
2856void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
2857  StmtPrinterHelper Helper(this, LO);
2858
2859  // Print the entry block.
2860  print_block(OS, this, getEntry(), &Helper, true);
2861
2862  // Iterate through the CFGBlocks and print them one by one.
2863  for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
2864    // Skip the entry block, because we already printed it.
2865    if (&(**I) == &getEntry() || &(**I) == &getExit())
2866      continue;
2867
2868    print_block(OS, this, **I, &Helper, true);
2869  }
2870
2871  // Print the exit block.
2872  print_block(OS, this, getExit(), &Helper, true);
2873  OS.flush();
2874}
2875
2876/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
2877void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
2878  print(llvm::errs(), cfg, LO);
2879}
2880
2881/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
2882///   Generally this will only be called from CFG::print.
2883void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
2884                     const LangOptions &LO) const {
2885  StmtPrinterHelper Helper(cfg, LO);
2886  print_block(OS, cfg, *this, &Helper, true);
2887}
2888
2889/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
2890void CFGBlock::printTerminator(llvm::raw_ostream &OS,
2891                               const LangOptions &LO) const {
2892  CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
2893  TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
2894}
2895
2896Stmt* CFGBlock::getTerminatorCondition() {
2897
2898  if (!Terminator)
2899    return NULL;
2900
2901  Expr* E = NULL;
2902
2903  switch (Terminator->getStmtClass()) {
2904    default:
2905      break;
2906
2907    case Stmt::ForStmtClass:
2908      E = cast<ForStmt>(Terminator)->getCond();
2909      break;
2910
2911    case Stmt::WhileStmtClass:
2912      E = cast<WhileStmt>(Terminator)->getCond();
2913      break;
2914
2915    case Stmt::DoStmtClass:
2916      E = cast<DoStmt>(Terminator)->getCond();
2917      break;
2918
2919    case Stmt::IfStmtClass:
2920      E = cast<IfStmt>(Terminator)->getCond();
2921      break;
2922
2923    case Stmt::ChooseExprClass:
2924      E = cast<ChooseExpr>(Terminator)->getCond();
2925      break;
2926
2927    case Stmt::IndirectGotoStmtClass:
2928      E = cast<IndirectGotoStmt>(Terminator)->getTarget();
2929      break;
2930
2931    case Stmt::SwitchStmtClass:
2932      E = cast<SwitchStmt>(Terminator)->getCond();
2933      break;
2934
2935    case Stmt::ConditionalOperatorClass:
2936      E = cast<ConditionalOperator>(Terminator)->getCond();
2937      break;
2938
2939    case Stmt::BinaryOperatorClass: // '&&' and '||'
2940      E = cast<BinaryOperator>(Terminator)->getLHS();
2941      break;
2942
2943    case Stmt::ObjCForCollectionStmtClass:
2944      return Terminator;
2945  }
2946
2947  return E ? E->IgnoreParens() : NULL;
2948}
2949
2950bool CFGBlock::hasBinaryBranchTerminator() const {
2951
2952  if (!Terminator)
2953    return false;
2954
2955  Expr* E = NULL;
2956
2957  switch (Terminator->getStmtClass()) {
2958    default:
2959      return false;
2960
2961    case Stmt::ForStmtClass:
2962    case Stmt::WhileStmtClass:
2963    case Stmt::DoStmtClass:
2964    case Stmt::IfStmtClass:
2965    case Stmt::ChooseExprClass:
2966    case Stmt::ConditionalOperatorClass:
2967    case Stmt::BinaryOperatorClass:
2968      return true;
2969  }
2970
2971  return E ? E->IgnoreParens() : NULL;
2972}
2973
2974
2975//===----------------------------------------------------------------------===//
2976// CFG Graphviz Visualization
2977//===----------------------------------------------------------------------===//
2978
2979
2980#ifndef NDEBUG
2981static StmtPrinterHelper* GraphHelper;
2982#endif
2983
2984void CFG::viewCFG(const LangOptions &LO) const {
2985#ifndef NDEBUG
2986  StmtPrinterHelper H(this, LO);
2987  GraphHelper = &H;
2988  llvm::ViewGraph(this,"CFG");
2989  GraphHelper = NULL;
2990#endif
2991}
2992
2993namespace llvm {
2994template<>
2995struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2996
2997  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2998
2999  static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
3000
3001#ifndef NDEBUG
3002    std::string OutSStr;
3003    llvm::raw_string_ostream Out(OutSStr);
3004    print_block(Out,Graph, *Node, GraphHelper, false);
3005    std::string& OutStr = Out.str();
3006
3007    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
3008
3009    // Process string output to make it nicer...
3010    for (unsigned i = 0; i != OutStr.length(); ++i)
3011      if (OutStr[i] == '\n') {                            // Left justify
3012        OutStr[i] = '\\';
3013        OutStr.insert(OutStr.begin()+i+1, 'l');
3014      }
3015
3016    return OutStr;
3017#else
3018    return "";
3019#endif
3020  }
3021};
3022} // end namespace llvm
3023