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