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