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