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