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