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