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