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