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