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