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