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