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/CFG.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/GraphWriter.h"
29 #include "llvm/Support/SaveAndRestore.h"
30 
31 using namespace clang;
32 
33 namespace {
34 
35 static SourceLocation GetEndLoc(Decl *D) {
36   if (VarDecl *VD = dyn_cast<VarDecl>(D))
37     if (Expr *Ex = VD->getInit())
38       return Ex->getSourceRange().getEnd();
39   return D->getLocation();
40 }
41 
42 class CFGBuilder;
43 
44 /// The CFG builder uses a recursive algorithm to build the CFG.  When
45 ///  we process an expression, sometimes we know that we must add the
46 ///  subexpressions as block-level expressions.  For example:
47 ///
48 ///    exp1 || exp2
49 ///
50 ///  When processing the '||' expression, we know that exp1 and exp2
51 ///  need to be added as block-level expressions, even though they
52 ///  might not normally need to be.  AddStmtChoice records this
53 ///  contextual information.  If AddStmtChoice is 'NotAlwaysAdd', then
54 ///  the builder has an option not to add a subexpression as a
55 ///  block-level expression.
56 ///
57 class AddStmtChoice {
58 public:
59   enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
60 
61   AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
62 
63   bool alwaysAdd(CFGBuilder &builder,
64                  const Stmt *stmt) const;
65 
66   /// Return a copy of this object, except with the 'always-add' bit
67   ///  set as specified.
68   AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
69     return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
70   }
71 
72 private:
73   Kind kind;
74 };
75 
76 /// LocalScope - Node in tree of local scopes created for C++ implicit
77 /// destructor calls generation. It contains list of automatic variables
78 /// declared in the scope and link to position in previous scope this scope
79 /// began in.
80 ///
81 /// The process of creating local scopes is as follows:
82 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
83 /// - Before processing statements in scope (e.g. CompoundStmt) create
84 ///   LocalScope object using CFGBuilder::ScopePos as link to previous scope
85 ///   and set CFGBuilder::ScopePos to the end of new scope,
86 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
87 ///   at this VarDecl,
88 /// - For every normal (without jump) end of scope add to CFGBlock destructors
89 ///   for objects in the current scope,
90 /// - For every jump add to CFGBlock destructors for objects
91 ///   between CFGBuilder::ScopePos and local scope position saved for jump
92 ///   target. Thanks to C++ restrictions on goto jumps we can be sure that
93 ///   jump target position will be on the path to root from CFGBuilder::ScopePos
94 ///   (adding any variable that doesn't need constructor to be called to
95 ///   LocalScope can break this assumption),
96 ///
97 class LocalScope {
98 public:
99   typedef BumpVector<VarDecl*> AutomaticVarsTy;
100 
101   /// const_iterator - Iterates local scope backwards and jumps to previous
102   /// scope on reaching the beginning of currently iterated scope.
103   class const_iterator {
104     const LocalScope* Scope;
105 
106     /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107     /// Invalid iterator (with null Scope) has VarIter equal to 0.
108     unsigned VarIter;
109 
110   public:
111     /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112     /// Incrementing invalid iterator is allowed and will result in invalid
113     /// iterator.
114     const_iterator()
115         : Scope(NULL), VarIter(0) {}
116 
117     /// Create valid iterator. In case when S.Prev is an invalid iterator and
118     /// I is equal to 0, this will create invalid iterator.
119     const_iterator(const LocalScope& S, unsigned I)
120         : Scope(&S), VarIter(I) {
121       // Iterator to "end" of scope is not allowed. Handle it by going up
122       // in scopes tree possibly up to invalid iterator in the root.
123       if (VarIter == 0 && Scope)
124         *this = Scope->Prev;
125     }
126 
127     VarDecl *const* operator->() const {
128       assert (Scope && "Dereferencing invalid iterator is not allowed");
129       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
130       return &Scope->Vars[VarIter - 1];
131     }
132     VarDecl *operator*() const {
133       return *this->operator->();
134     }
135 
136     const_iterator &operator++() {
137       if (!Scope)
138         return *this;
139 
140       assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
141       --VarIter;
142       if (VarIter == 0)
143         *this = Scope->Prev;
144       return *this;
145     }
146     const_iterator operator++(int) {
147       const_iterator P = *this;
148       ++*this;
149       return P;
150     }
151 
152     bool operator==(const const_iterator &rhs) const {
153       return Scope == rhs.Scope && VarIter == rhs.VarIter;
154     }
155     bool operator!=(const const_iterator &rhs) const {
156       return !(*this == rhs);
157     }
158 
159     LLVM_EXPLICIT operator bool() const {
160       return *this != const_iterator();
161     }
162 
163     int distance(const_iterator L);
164   };
165 
166   friend class const_iterator;
167 
168 private:
169   BumpVectorContext ctx;
170 
171   /// Automatic variables in order of declaration.
172   AutomaticVarsTy Vars;
173   /// Iterator to variable in previous scope that was declared just before
174   /// begin of this scope.
175   const_iterator Prev;
176 
177 public:
178   /// Constructs empty scope linked to previous scope in specified place.
179   LocalScope(BumpVectorContext &ctx, const_iterator P)
180       : ctx(ctx), Vars(ctx, 4), Prev(P) {}
181 
182   /// Begin of scope in direction of CFG building (backwards).
183   const_iterator begin() const { return const_iterator(*this, Vars.size()); }
184 
185   void addVar(VarDecl *VD) {
186     Vars.push_back(VD, ctx);
187   }
188 };
189 
190 /// distance - Calculates distance from this to L. L must be reachable from this
191 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
192 /// number of scopes between this and L.
193 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
194   int D = 0;
195   const_iterator F = *this;
196   while (F.Scope != L.Scope) {
197     assert (F != const_iterator()
198         && "L iterator is not reachable from F iterator.");
199     D += F.VarIter;
200     F = F.Scope->Prev;
201   }
202   D += F.VarIter - L.VarIter;
203   return D;
204 }
205 
206 /// BlockScopePosPair - Structure for specifying position in CFG during its
207 /// build process. It consists of CFGBlock that specifies position in CFG graph
208 /// and  LocalScope::const_iterator that specifies position in LocalScope graph.
209 struct BlockScopePosPair {
210   BlockScopePosPair() : block(0) {}
211   BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
212       : block(b), scopePosition(scopePos) {}
213 
214   CFGBlock *block;
215   LocalScope::const_iterator scopePosition;
216 };
217 
218 /// TryResult - a class representing a variant over the values
219 ///  'true', 'false', or 'unknown'.  This is returned by tryEvaluateBool,
220 ///  and is used by the CFGBuilder to decide if a branch condition
221 ///  can be decided up front during CFG construction.
222 class TryResult {
223   int X;
224 public:
225   TryResult(bool b) : X(b ? 1 : 0) {}
226   TryResult() : X(-1) {}
227 
228   bool isTrue() const { return X == 1; }
229   bool isFalse() const { return X == 0; }
230   bool isKnown() const { return X >= 0; }
231   void negate() {
232     assert(isKnown());
233     X ^= 0x1;
234   }
235 };
236 
237 class reverse_children {
238   llvm::SmallVector<Stmt *, 12> childrenBuf;
239   ArrayRef<Stmt*> children;
240 public:
241   reverse_children(Stmt *S);
242 
243   typedef ArrayRef<Stmt*>::reverse_iterator iterator;
244   iterator begin() const { return children.rbegin(); }
245   iterator end() const { return children.rend(); }
246 };
247 
248 
249 reverse_children::reverse_children(Stmt *S) {
250   if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
251     children = CE->getRawSubExprs();
252     return;
253   }
254   switch (S->getStmtClass()) {
255     // Note: Fill in this switch with more cases we want to optimize.
256     case Stmt::InitListExprClass: {
257       InitListExpr *IE = cast<InitListExpr>(S);
258       children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
259                                     IE->getNumInits());
260       return;
261     }
262     default:
263       break;
264   }
265 
266   // Default case for all other statements.
267   for (Stmt::child_range I = S->children(); I; ++I) {
268     childrenBuf.push_back(*I);
269   }
270 
271   // This needs to be done *after* childrenBuf has been populated.
272   children = childrenBuf;
273 }
274 
275 /// CFGBuilder - This class implements CFG construction from an AST.
276 ///   The builder is stateful: an instance of the builder should be used to only
277 ///   construct a single CFG.
278 ///
279 ///   Example usage:
280 ///
281 ///     CFGBuilder builder;
282 ///     CFG* cfg = builder.BuildAST(stmt1);
283 ///
284 ///  CFG construction is done via a recursive walk of an AST.  We actually parse
285 ///  the AST in reverse order so that the successor of a basic block is
286 ///  constructed prior to its predecessor.  This allows us to nicely capture
287 ///  implicit fall-throughs without extra basic blocks.
288 ///
289 class CFGBuilder {
290   typedef BlockScopePosPair JumpTarget;
291   typedef BlockScopePosPair JumpSource;
292 
293   ASTContext *Context;
294   OwningPtr<CFG> cfg;
295 
296   CFGBlock *Block;
297   CFGBlock *Succ;
298   JumpTarget ContinueJumpTarget;
299   JumpTarget BreakJumpTarget;
300   CFGBlock *SwitchTerminatedBlock;
301   CFGBlock *DefaultCaseBlock;
302   CFGBlock *TryTerminatedBlock;
303 
304   // Current position in local scope.
305   LocalScope::const_iterator ScopePos;
306 
307   // LabelMap records the mapping from Label expressions to their jump targets.
308   typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
309   LabelMapTy LabelMap;
310 
311   // A list of blocks that end with a "goto" that must be backpatched to their
312   // resolved targets upon completion of CFG construction.
313   typedef std::vector<JumpSource> BackpatchBlocksTy;
314   BackpatchBlocksTy BackpatchBlocks;
315 
316   // A list of labels whose address has been taken (for indirect gotos).
317   typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
318   LabelSetTy AddressTakenLabels;
319 
320   bool badCFG;
321   const CFG::BuildOptions &BuildOpts;
322 
323   // State to track for building switch statements.
324   bool switchExclusivelyCovered;
325   Expr::EvalResult *switchCond;
326 
327   CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
328   const Stmt *lastLookup;
329 
330   // Caches boolean evaluations of expressions to avoid multiple re-evaluations
331   // during construction of branches for chained logical operators.
332   typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
333   CachedBoolEvalsTy CachedBoolEvals;
334 
335 public:
336   explicit CFGBuilder(ASTContext *astContext,
337                       const CFG::BuildOptions &buildOpts)
338     : Context(astContext), cfg(new CFG()), // crew a new CFG
339       Block(NULL), Succ(NULL),
340       SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
341       TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts),
342       switchExclusivelyCovered(false), switchCond(0),
343       cachedEntry(0), lastLookup(0) {}
344 
345   // buildCFG - Used by external clients to construct the CFG.
346   CFG* buildCFG(const Decl *D, Stmt *Statement);
347 
348   bool alwaysAdd(const Stmt *stmt);
349 
350 private:
351   // Visitors to walk an AST and construct the CFG.
352   CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
353   CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
354   CFGBlock *VisitBreakStmt(BreakStmt *B);
355   CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
356   CFGBlock *VisitCaseStmt(CaseStmt *C);
357   CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
358   CFGBlock *VisitCompoundStmt(CompoundStmt *C);
359   CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
360                                      AddStmtChoice asc);
361   CFGBlock *VisitContinueStmt(ContinueStmt *C);
362   CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
363                                       AddStmtChoice asc);
364   CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
365   CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
366   CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
367   CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
368   CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
369   CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
370                                        AddStmtChoice asc);
371   CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
372                                         AddStmtChoice asc);
373   CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
374   CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
375   CFGBlock *VisitDeclStmt(DeclStmt *DS);
376   CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
377   CFGBlock *VisitDefaultStmt(DefaultStmt *D);
378   CFGBlock *VisitDoStmt(DoStmt *D);
379   CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
380   CFGBlock *VisitForStmt(ForStmt *F);
381   CFGBlock *VisitGotoStmt(GotoStmt *G);
382   CFGBlock *VisitIfStmt(IfStmt *I);
383   CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
384   CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
385   CFGBlock *VisitLabelStmt(LabelStmt *L);
386   CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
387   CFGBlock *VisitLogicalOperator(BinaryOperator *B);
388   std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
389                                                          Stmt *Term,
390                                                          CFGBlock *TrueBlock,
391                                                          CFGBlock *FalseBlock);
392   CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
393   CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
394   CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
395   CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
396   CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
397   CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
398   CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
399   CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
400   CFGBlock *VisitReturnStmt(ReturnStmt *R);
401   CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
402   CFGBlock *VisitSwitchStmt(SwitchStmt *S);
403   CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
404                                           AddStmtChoice asc);
405   CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
406   CFGBlock *VisitWhileStmt(WhileStmt *W);
407 
408   CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
409   CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
410   CFGBlock *VisitChildren(Stmt *S);
411   CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
412 
413   // Visitors to walk an AST and generate destructors of temporaries in
414   // full expression.
415   CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false);
416   CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E);
417   CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E);
418   CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E,
419       bool BindToTemporary);
420   CFGBlock *
421   VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E,
422                                             bool BindToTemporary);
423 
424   // NYS == Not Yet Supported
425   CFGBlock *NYS() {
426     badCFG = true;
427     return Block;
428   }
429 
430   void autoCreateBlock() { if (!Block) Block = createBlock(); }
431   CFGBlock *createBlock(bool add_successor = true);
432   CFGBlock *createNoReturnBlock();
433 
434   CFGBlock *addStmt(Stmt *S) {
435     return Visit(S, AddStmtChoice::AlwaysAdd);
436   }
437   CFGBlock *addInitializer(CXXCtorInitializer *I);
438   void addAutomaticObjDtors(LocalScope::const_iterator B,
439                             LocalScope::const_iterator E, Stmt *S);
440   void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
441 
442   // Local scopes creation.
443   LocalScope* createOrReuseLocalScope(LocalScope* Scope);
444 
445   void addLocalScopeForStmt(Stmt *S);
446   LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL);
447   LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL);
448 
449   void addLocalScopeAndDtors(Stmt *S);
450 
451   // Interface to CFGBlock - adding CFGElements.
452   void appendStmt(CFGBlock *B, const Stmt *S) {
453     if (alwaysAdd(S) && cachedEntry)
454       cachedEntry->second = B;
455 
456     // All block-level expressions should have already been IgnoreParens()ed.
457     assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
458     B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
459   }
460   void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
461     B->appendInitializer(I, cfg->getBumpVectorContext());
462   }
463   void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
464     B->appendNewAllocator(NE, cfg->getBumpVectorContext());
465   }
466   void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
467     B->appendBaseDtor(BS, cfg->getBumpVectorContext());
468   }
469   void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
470     B->appendMemberDtor(FD, cfg->getBumpVectorContext());
471   }
472   void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
473     B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
474   }
475   void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
476     B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
477   }
478 
479   void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
480     B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
481   }
482 
483   void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
484       LocalScope::const_iterator B, LocalScope::const_iterator E);
485 
486   void addSuccessor(CFGBlock *B, CFGBlock *S) {
487     B->addSuccessor(S, cfg->getBumpVectorContext());
488   }
489 
490   /// Try and evaluate an expression to an integer constant.
491   bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
492     if (!BuildOpts.PruneTriviallyFalseEdges)
493       return false;
494     return !S->isTypeDependent() &&
495            !S->isValueDependent() &&
496            S->EvaluateAsRValue(outResult, *Context);
497   }
498 
499   /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
500   /// if we can evaluate to a known value, otherwise return -1.
501   TryResult tryEvaluateBool(Expr *S) {
502     if (!BuildOpts.PruneTriviallyFalseEdges ||
503         S->isTypeDependent() || S->isValueDependent())
504       return TryResult();
505 
506     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
507       if (Bop->isLogicalOp()) {
508         // Check the cache first.
509         CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
510         if (I != CachedBoolEvals.end())
511           return I->second; // already in map;
512 
513         // Retrieve result at first, or the map might be updated.
514         TryResult Result = evaluateAsBooleanConditionNoCache(S);
515         CachedBoolEvals[S] = Result; // update or insert
516         return Result;
517       }
518       else {
519         switch (Bop->getOpcode()) {
520           default: break;
521           // For 'x & 0' and 'x * 0', we can determine that
522           // the value is always false.
523           case BO_Mul:
524           case BO_And: {
525             // If either operand is zero, we know the value
526             // must be false.
527             llvm::APSInt IntVal;
528             if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
529               if (IntVal.getBoolValue() == false) {
530                 return TryResult(false);
531               }
532             }
533             if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
534               if (IntVal.getBoolValue() == false) {
535                 return TryResult(false);
536               }
537             }
538           }
539           break;
540         }
541       }
542     }
543 
544     return evaluateAsBooleanConditionNoCache(S);
545   }
546 
547   /// \brief Evaluate as boolean \param E without using the cache.
548   TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
549     if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
550       if (Bop->isLogicalOp()) {
551         TryResult LHS = tryEvaluateBool(Bop->getLHS());
552         if (LHS.isKnown()) {
553           // We were able to evaluate the LHS, see if we can get away with not
554           // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
555           if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
556             return LHS.isTrue();
557 
558           TryResult RHS = tryEvaluateBool(Bop->getRHS());
559           if (RHS.isKnown()) {
560             if (Bop->getOpcode() == BO_LOr)
561               return LHS.isTrue() || RHS.isTrue();
562             else
563               return LHS.isTrue() && RHS.isTrue();
564           }
565         } else {
566           TryResult RHS = tryEvaluateBool(Bop->getRHS());
567           if (RHS.isKnown()) {
568             // We can't evaluate the LHS; however, sometimes the result
569             // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
570             if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
571               return RHS.isTrue();
572           }
573         }
574 
575         return TryResult();
576       }
577     }
578 
579     bool Result;
580     if (E->EvaluateAsBooleanCondition(Result, *Context))
581       return Result;
582 
583     return TryResult();
584   }
585 
586 };
587 
588 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
589                                      const Stmt *stmt) const {
590   return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
591 }
592 
593 bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
594   bool shouldAdd = BuildOpts.alwaysAdd(stmt);
595 
596   if (!BuildOpts.forcedBlkExprs)
597     return shouldAdd;
598 
599   if (lastLookup == stmt) {
600     if (cachedEntry) {
601       assert(cachedEntry->first == stmt);
602       return true;
603     }
604     return shouldAdd;
605   }
606 
607   lastLookup = stmt;
608 
609   // Perform the lookup!
610   CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
611 
612   if (!fb) {
613     // No need to update 'cachedEntry', since it will always be null.
614     assert(cachedEntry == 0);
615     return shouldAdd;
616   }
617 
618   CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
619   if (itr == fb->end()) {
620     cachedEntry = 0;
621     return shouldAdd;
622   }
623 
624   cachedEntry = &*itr;
625   return true;
626 }
627 
628 // FIXME: Add support for dependent-sized array types in C++?
629 // Does it even make sense to build a CFG for an uninstantiated template?
630 static const VariableArrayType *FindVA(const Type *t) {
631   while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
632     if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
633       if (vat->getSizeExpr())
634         return vat;
635 
636     t = vt->getElementType().getTypePtr();
637   }
638 
639   return 0;
640 }
641 
642 /// BuildCFG - Constructs a CFG from an AST (a Stmt*).  The AST can represent an
643 ///  arbitrary statement.  Examples include a single expression or a function
644 ///  body (compound statement).  The ownership of the returned CFG is
645 ///  transferred to the caller.  If CFG construction fails, this method returns
646 ///  NULL.
647 CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
648   assert(cfg.get());
649   if (!Statement)
650     return NULL;
651 
652   // Create an empty block that will serve as the exit block for the CFG.  Since
653   // this is the first block added to the CFG, it will be implicitly registered
654   // as the exit block.
655   Succ = createBlock();
656   assert(Succ == &cfg->getExit());
657   Block = NULL;  // the EXIT block is empty.  Create all other blocks lazily.
658 
659   if (BuildOpts.AddImplicitDtors)
660     if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
661       addImplicitDtorsForDestructor(DD);
662 
663   // Visit the statements and create the CFG.
664   CFGBlock *B = addStmt(Statement);
665 
666   if (badCFG)
667     return NULL;
668 
669   // For C++ constructor add initializers to CFG.
670   if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
671     for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
672         E = CD->init_rend(); I != E; ++I) {
673       B = addInitializer(*I);
674       if (badCFG)
675         return NULL;
676     }
677   }
678 
679   if (B)
680     Succ = B;
681 
682   // Backpatch the gotos whose label -> block mappings we didn't know when we
683   // encountered them.
684   for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
685                                    E = BackpatchBlocks.end(); I != E; ++I ) {
686 
687     CFGBlock *B = I->block;
688     const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
689     LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
690 
691     // If there is no target for the goto, then we are looking at an
692     // incomplete AST.  Handle this by not registering a successor.
693     if (LI == LabelMap.end()) continue;
694 
695     JumpTarget JT = LI->second;
696     prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
697                                            JT.scopePosition);
698     addSuccessor(B, JT.block);
699   }
700 
701   // Add successors to the Indirect Goto Dispatch block (if we have one).
702   if (CFGBlock *B = cfg->getIndirectGotoBlock())
703     for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
704                               E = AddressTakenLabels.end(); I != E; ++I ) {
705 
706       // Lookup the target block.
707       LabelMapTy::iterator LI = LabelMap.find(*I);
708 
709       // If there is no target block that contains label, then we are looking
710       // at an incomplete AST.  Handle this by not registering a successor.
711       if (LI == LabelMap.end()) continue;
712 
713       addSuccessor(B, LI->second.block);
714     }
715 
716   // Create an empty entry block that has no predecessors.
717   cfg->setEntry(createBlock());
718 
719   return cfg.take();
720 }
721 
722 /// createBlock - Used to lazily create blocks that are connected
723 ///  to the current (global) succcessor.
724 CFGBlock *CFGBuilder::createBlock(bool add_successor) {
725   CFGBlock *B = cfg->createBlock();
726   if (add_successor && Succ)
727     addSuccessor(B, Succ);
728   return B;
729 }
730 
731 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
732 /// CFG. It is *not* connected to the current (global) successor, and instead
733 /// directly tied to the exit block in order to be reachable.
734 CFGBlock *CFGBuilder::createNoReturnBlock() {
735   CFGBlock *B = createBlock(false);
736   B->setHasNoReturnElement();
737   addSuccessor(B, &cfg->getExit());
738   return B;
739 }
740 
741 /// addInitializer - Add C++ base or member initializer element to CFG.
742 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
743   if (!BuildOpts.AddInitializers)
744     return Block;
745 
746   bool IsReference = false;
747   bool HasTemporaries = false;
748 
749   // Destructors of temporaries in initialization expression should be called
750   // after initialization finishes.
751   Expr *Init = I->getInit();
752   if (Init) {
753     if (FieldDecl *FD = I->getAnyMember())
754       IsReference = FD->getType()->isReferenceType();
755     HasTemporaries = isa<ExprWithCleanups>(Init);
756 
757     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
758       // Generate destructors for temporaries in initialization expression.
759       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
760           IsReference);
761     }
762   }
763 
764   autoCreateBlock();
765   appendInitializer(Block, I);
766 
767   if (Init) {
768     if (HasTemporaries) {
769       // For expression with temporaries go directly to subexpression to omit
770       // generating destructors for the second time.
771       return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
772     }
773     return Visit(Init);
774   }
775 
776   return Block;
777 }
778 
779 /// \brief Retrieve the type of the temporary object whose lifetime was
780 /// extended by a local reference with the given initializer.
781 static QualType getReferenceInitTemporaryType(ASTContext &Context,
782                                               const Expr *Init) {
783   while (true) {
784     // Skip parentheses.
785     Init = Init->IgnoreParens();
786 
787     // Skip through cleanups.
788     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
789       Init = EWC->getSubExpr();
790       continue;
791     }
792 
793     // Skip through the temporary-materialization expression.
794     if (const MaterializeTemporaryExpr *MTE
795           = dyn_cast<MaterializeTemporaryExpr>(Init)) {
796       Init = MTE->GetTemporaryExpr();
797       continue;
798     }
799 
800     // Skip derived-to-base and no-op casts.
801     if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
802       if ((CE->getCastKind() == CK_DerivedToBase ||
803            CE->getCastKind() == CK_UncheckedDerivedToBase ||
804            CE->getCastKind() == CK_NoOp) &&
805           Init->getType()->isRecordType()) {
806         Init = CE->getSubExpr();
807         continue;
808       }
809     }
810 
811     // Skip member accesses into rvalues.
812     if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
813       if (!ME->isArrow() && ME->getBase()->isRValue()) {
814         Init = ME->getBase();
815         continue;
816       }
817     }
818 
819     break;
820   }
821 
822   return Init->getType();
823 }
824 
825 /// addAutomaticObjDtors - Add to current block automatic objects destructors
826 /// for objects in range of local scope positions. Use S as trigger statement
827 /// for destructors.
828 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
829                                       LocalScope::const_iterator E, Stmt *S) {
830   if (!BuildOpts.AddImplicitDtors)
831     return;
832 
833   if (B == E)
834     return;
835 
836   // We need to append the destructors in reverse order, but any one of them
837   // may be a no-return destructor which changes the CFG. As a result, buffer
838   // this sequence up and replay them in reverse order when appending onto the
839   // CFGBlock(s).
840   SmallVector<VarDecl*, 10> Decls;
841   Decls.reserve(B.distance(E));
842   for (LocalScope::const_iterator I = B; I != E; ++I)
843     Decls.push_back(*I);
844 
845   for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
846                                                    E = Decls.rend();
847        I != E; ++I) {
848     // If this destructor is marked as a no-return destructor, we need to
849     // create a new block for the destructor which does not have as a successor
850     // anything built thus far: control won't flow out of this block.
851     QualType Ty = (*I)->getType();
852     if (Ty->isReferenceType()) {
853       Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
854     }
855     Ty = Context->getBaseElementType(Ty);
856 
857     const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
858     if (Dtor->isNoReturn())
859       Block = createNoReturnBlock();
860     else
861       autoCreateBlock();
862 
863     appendAutomaticObjDtor(Block, *I, S);
864   }
865 }
866 
867 /// addImplicitDtorsForDestructor - Add implicit destructors generated for
868 /// base and member objects in destructor.
869 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
870   assert (BuildOpts.AddImplicitDtors
871       && "Can be called only when dtors should be added");
872   const CXXRecordDecl *RD = DD->getParent();
873 
874   // At the end destroy virtual base objects.
875   for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(),
876       VE = RD->vbases_end(); VI != VE; ++VI) {
877     const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl();
878     if (!CD->hasTrivialDestructor()) {
879       autoCreateBlock();
880       appendBaseDtor(Block, VI);
881     }
882   }
883 
884   // Before virtual bases destroy direct base objects.
885   for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
886       BE = RD->bases_end(); BI != BE; ++BI) {
887     if (!BI->isVirtual()) {
888       const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl();
889       if (!CD->hasTrivialDestructor()) {
890         autoCreateBlock();
891         appendBaseDtor(Block, BI);
892       }
893     }
894   }
895 
896   // First destroy member objects.
897   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
898       FE = RD->field_end(); FI != FE; ++FI) {
899     // Check for constant size array. Set type to array element type.
900     QualType QT = FI->getType();
901     if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
902       if (AT->getSize() == 0)
903         continue;
904       QT = AT->getElementType();
905     }
906 
907     if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
908       if (!CD->hasTrivialDestructor()) {
909         autoCreateBlock();
910         appendMemberDtor(Block, *FI);
911       }
912   }
913 }
914 
915 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
916 /// way return valid LocalScope object.
917 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
918   if (!Scope) {
919     llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
920     Scope = alloc.Allocate<LocalScope>();
921     BumpVectorContext ctx(alloc);
922     new (Scope) LocalScope(ctx, ScopePos);
923   }
924   return Scope;
925 }
926 
927 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
928 /// that should create implicit scope (e.g. if/else substatements).
929 void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
930   if (!BuildOpts.AddImplicitDtors)
931     return;
932 
933   LocalScope *Scope = 0;
934 
935   // For compound statement we will be creating explicit scope.
936   if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
937     for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end()
938         ; BI != BE; ++BI) {
939       Stmt *SI = (*BI)->stripLabelLikeStatements();
940       if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
941         Scope = addLocalScopeForDeclStmt(DS, Scope);
942     }
943     return;
944   }
945 
946   // For any other statement scope will be implicit and as such will be
947   // interesting only for DeclStmt.
948   if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
949     addLocalScopeForDeclStmt(DS);
950 }
951 
952 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
953 /// reuse Scope if not NULL.
954 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
955                                                  LocalScope* Scope) {
956   if (!BuildOpts.AddImplicitDtors)
957     return Scope;
958 
959   for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end()
960       ; DI != DE; ++DI) {
961     if (VarDecl *VD = dyn_cast<VarDecl>(*DI))
962       Scope = addLocalScopeForVarDecl(VD, Scope);
963   }
964   return Scope;
965 }
966 
967 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
968 /// create add scope for automatic objects and temporary objects bound to
969 /// const reference. Will reuse Scope if not NULL.
970 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
971                                                 LocalScope* Scope) {
972   if (!BuildOpts.AddImplicitDtors)
973     return Scope;
974 
975   // Check if variable is local.
976   switch (VD->getStorageClass()) {
977   case SC_None:
978   case SC_Auto:
979   case SC_Register:
980     break;
981   default: return Scope;
982   }
983 
984   // Check for const references bound to temporary. Set type to pointee.
985   QualType QT = VD->getType();
986   if (QT.getTypePtr()->isReferenceType()) {
987     // Attempt to determine whether this declaration lifetime-extends a
988     // temporary.
989     //
990     // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
991     // temporaries, and a single declaration can extend multiple temporaries.
992     // We should look at the storage duration on each nested
993     // MaterializeTemporaryExpr instead.
994     const Expr *Init = VD->getInit();
995     if (!Init)
996       return Scope;
997     if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
998       Init = EWC->getSubExpr();
999     if (!isa<MaterializeTemporaryExpr>(Init))
1000       return Scope;
1001 
1002     // Lifetime-extending a temporary.
1003     QT = getReferenceInitTemporaryType(*Context, Init);
1004   }
1005 
1006   // Check for constant size array. Set type to array element type.
1007   while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1008     if (AT->getSize() == 0)
1009       return Scope;
1010     QT = AT->getElementType();
1011   }
1012 
1013   // Check if type is a C++ class with non-trivial destructor.
1014   if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1015     if (!CD->hasTrivialDestructor()) {
1016       // Add the variable to scope
1017       Scope = createOrReuseLocalScope(Scope);
1018       Scope->addVar(VD);
1019       ScopePos = Scope->begin();
1020     }
1021   return Scope;
1022 }
1023 
1024 /// addLocalScopeAndDtors - For given statement add local scope for it and
1025 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
1026 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
1027   if (!BuildOpts.AddImplicitDtors)
1028     return;
1029 
1030   LocalScope::const_iterator scopeBeginPos = ScopePos;
1031   addLocalScopeForStmt(S);
1032   addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1033 }
1034 
1035 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1036 /// variables with automatic storage duration to CFGBlock's elements vector.
1037 /// Elements will be prepended to physical beginning of the vector which
1038 /// happens to be logical end. Use blocks terminator as statement that specifies
1039 /// destructors call site.
1040 /// FIXME: This mechanism for adding automatic destructors doesn't handle
1041 /// no-return destructors properly.
1042 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
1043     LocalScope::const_iterator B, LocalScope::const_iterator E) {
1044   BumpVectorContext &C = cfg->getBumpVectorContext();
1045   CFGBlock::iterator InsertPos
1046     = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1047   for (LocalScope::const_iterator I = B; I != E; ++I)
1048     InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1049                                             Blk->getTerminator());
1050 }
1051 
1052 /// Visit - Walk the subtree of a statement and add extra
1053 ///   blocks for ternary operators, &&, and ||.  We also process "," and
1054 ///   DeclStmts (which may contain nested control-flow).
1055 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
1056   if (!S) {
1057     badCFG = true;
1058     return 0;
1059   }
1060 
1061   if (Expr *E = dyn_cast<Expr>(S))
1062     S = E->IgnoreParens();
1063 
1064   switch (S->getStmtClass()) {
1065     default:
1066       return VisitStmt(S, asc);
1067 
1068     case Stmt::AddrLabelExprClass:
1069       return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
1070 
1071     case Stmt::BinaryConditionalOperatorClass:
1072       return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1073 
1074     case Stmt::BinaryOperatorClass:
1075       return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
1076 
1077     case Stmt::BlockExprClass:
1078       return VisitNoRecurse(cast<Expr>(S), asc);
1079 
1080     case Stmt::BreakStmtClass:
1081       return VisitBreakStmt(cast<BreakStmt>(S));
1082 
1083     case Stmt::CallExprClass:
1084     case Stmt::CXXOperatorCallExprClass:
1085     case Stmt::CXXMemberCallExprClass:
1086     case Stmt::UserDefinedLiteralClass:
1087       return VisitCallExpr(cast<CallExpr>(S), asc);
1088 
1089     case Stmt::CaseStmtClass:
1090       return VisitCaseStmt(cast<CaseStmt>(S));
1091 
1092     case Stmt::ChooseExprClass:
1093       return VisitChooseExpr(cast<ChooseExpr>(S), asc);
1094 
1095     case Stmt::CompoundStmtClass:
1096       return VisitCompoundStmt(cast<CompoundStmt>(S));
1097 
1098     case Stmt::ConditionalOperatorClass:
1099       return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
1100 
1101     case Stmt::ContinueStmtClass:
1102       return VisitContinueStmt(cast<ContinueStmt>(S));
1103 
1104     case Stmt::CXXCatchStmtClass:
1105       return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1106 
1107     case Stmt::ExprWithCleanupsClass:
1108       return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
1109 
1110     case Stmt::CXXDefaultArgExprClass:
1111     case Stmt::CXXDefaultInitExprClass:
1112       // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1113       // called function's declaration, not by the caller. If we simply add
1114       // this expression to the CFG, we could end up with the same Expr
1115       // appearing multiple times.
1116       // PR13385 / <rdar://problem/12156507>
1117       //
1118       // It's likewise possible for multiple CXXDefaultInitExprs for the same
1119       // expression to be used in the same function (through aggregate
1120       // initialization).
1121       return VisitStmt(S, asc);
1122 
1123     case Stmt::CXXBindTemporaryExprClass:
1124       return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1125 
1126     case Stmt::CXXConstructExprClass:
1127       return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1128 
1129     case Stmt::CXXNewExprClass:
1130       return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1131 
1132     case Stmt::CXXDeleteExprClass:
1133       return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1134 
1135     case Stmt::CXXFunctionalCastExprClass:
1136       return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1137 
1138     case Stmt::CXXTemporaryObjectExprClass:
1139       return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1140 
1141     case Stmt::CXXThrowExprClass:
1142       return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
1143 
1144     case Stmt::CXXTryStmtClass:
1145       return VisitCXXTryStmt(cast<CXXTryStmt>(S));
1146 
1147     case Stmt::CXXForRangeStmtClass:
1148       return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1149 
1150     case Stmt::DeclStmtClass:
1151       return VisitDeclStmt(cast<DeclStmt>(S));
1152 
1153     case Stmt::DefaultStmtClass:
1154       return VisitDefaultStmt(cast<DefaultStmt>(S));
1155 
1156     case Stmt::DoStmtClass:
1157       return VisitDoStmt(cast<DoStmt>(S));
1158 
1159     case Stmt::ForStmtClass:
1160       return VisitForStmt(cast<ForStmt>(S));
1161 
1162     case Stmt::GotoStmtClass:
1163       return VisitGotoStmt(cast<GotoStmt>(S));
1164 
1165     case Stmt::IfStmtClass:
1166       return VisitIfStmt(cast<IfStmt>(S));
1167 
1168     case Stmt::ImplicitCastExprClass:
1169       return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
1170 
1171     case Stmt::IndirectGotoStmtClass:
1172       return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
1173 
1174     case Stmt::LabelStmtClass:
1175       return VisitLabelStmt(cast<LabelStmt>(S));
1176 
1177     case Stmt::LambdaExprClass:
1178       return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1179 
1180     case Stmt::MemberExprClass:
1181       return VisitMemberExpr(cast<MemberExpr>(S), asc);
1182 
1183     case Stmt::NullStmtClass:
1184       return Block;
1185 
1186     case Stmt::ObjCAtCatchStmtClass:
1187       return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1188 
1189     case Stmt::ObjCAutoreleasePoolStmtClass:
1190     return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1191 
1192     case Stmt::ObjCAtSynchronizedStmtClass:
1193       return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
1194 
1195     case Stmt::ObjCAtThrowStmtClass:
1196       return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
1197 
1198     case Stmt::ObjCAtTryStmtClass:
1199       return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
1200 
1201     case Stmt::ObjCForCollectionStmtClass:
1202       return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
1203 
1204     case Stmt::OpaqueValueExprClass:
1205       return Block;
1206 
1207     case Stmt::PseudoObjectExprClass:
1208       return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1209 
1210     case Stmt::ReturnStmtClass:
1211       return VisitReturnStmt(cast<ReturnStmt>(S));
1212 
1213     case Stmt::UnaryExprOrTypeTraitExprClass:
1214       return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1215                                            asc);
1216 
1217     case Stmt::StmtExprClass:
1218       return VisitStmtExpr(cast<StmtExpr>(S), asc);
1219 
1220     case Stmt::SwitchStmtClass:
1221       return VisitSwitchStmt(cast<SwitchStmt>(S));
1222 
1223     case Stmt::UnaryOperatorClass:
1224       return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1225 
1226     case Stmt::WhileStmtClass:
1227       return VisitWhileStmt(cast<WhileStmt>(S));
1228   }
1229 }
1230 
1231 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
1232   if (asc.alwaysAdd(*this, S)) {
1233     autoCreateBlock();
1234     appendStmt(Block, S);
1235   }
1236 
1237   return VisitChildren(S);
1238 }
1239 
1240 /// VisitChildren - Visit the children of a Stmt.
1241 CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1242   CFGBlock *B = Block;
1243 
1244   // Visit the children in their reverse order so that they appear in
1245   // left-to-right (natural) order in the CFG.
1246   reverse_children RChildren(S);
1247   for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1248        I != E; ++I) {
1249     if (Stmt *Child = *I)
1250       if (CFGBlock *R = Visit(Child))
1251         B = R;
1252   }
1253   return B;
1254 }
1255 
1256 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1257                                          AddStmtChoice asc) {
1258   AddressTakenLabels.insert(A->getLabel());
1259 
1260   if (asc.alwaysAdd(*this, A)) {
1261     autoCreateBlock();
1262     appendStmt(Block, A);
1263   }
1264 
1265   return Block;
1266 }
1267 
1268 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
1269            AddStmtChoice asc) {
1270   if (asc.alwaysAdd(*this, U)) {
1271     autoCreateBlock();
1272     appendStmt(Block, U);
1273   }
1274 
1275   return Visit(U->getSubExpr(), AddStmtChoice());
1276 }
1277 
1278 CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1279   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1280   appendStmt(ConfluenceBlock, B);
1281 
1282   if (badCFG)
1283     return 0;
1284 
1285   return VisitLogicalOperator(B, 0, ConfluenceBlock, ConfluenceBlock).first;
1286 }
1287 
1288 std::pair<CFGBlock*, CFGBlock*>
1289 CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1290                                  Stmt *Term,
1291                                  CFGBlock *TrueBlock,
1292                                  CFGBlock *FalseBlock) {
1293 
1294   // Introspect the RHS.  If it is a nested logical operation, we recursively
1295   // build the CFG using this function.  Otherwise, resort to default
1296   // CFG construction behavior.
1297   Expr *RHS = B->getRHS()->IgnoreParens();
1298   CFGBlock *RHSBlock, *ExitBlock;
1299 
1300   do {
1301     if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1302       if (B_RHS->isLogicalOp()) {
1303         llvm::tie(RHSBlock, ExitBlock) =
1304           VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1305         break;
1306       }
1307 
1308     // The RHS is not a nested logical operation.  Don't push the terminator
1309     // down further, but instead visit RHS and construct the respective
1310     // pieces of the CFG, and link up the RHSBlock with the terminator
1311     // we have been provided.
1312     ExitBlock = RHSBlock = createBlock(false);
1313 
1314     if (!Term) {
1315       assert(TrueBlock == FalseBlock);
1316       addSuccessor(RHSBlock, TrueBlock);
1317     }
1318     else {
1319       RHSBlock->setTerminator(Term);
1320       TryResult KnownVal = tryEvaluateBool(RHS);
1321       addSuccessor(RHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1322       addSuccessor(RHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1323     }
1324 
1325     Block = RHSBlock;
1326     RHSBlock = addStmt(RHS);
1327   }
1328   while (false);
1329 
1330   if (badCFG)
1331     return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1332 
1333   // Generate the blocks for evaluating the LHS.
1334   Expr *LHS = B->getLHS()->IgnoreParens();
1335 
1336   if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1337     if (B_LHS->isLogicalOp()) {
1338       if (B->getOpcode() == BO_LOr)
1339         FalseBlock = RHSBlock;
1340       else
1341         TrueBlock = RHSBlock;
1342 
1343       // For the LHS, treat 'B' as the terminator that we want to sink
1344       // into the nested branch.  The RHS always gets the top-most
1345       // terminator.
1346       return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1347     }
1348 
1349   // Create the block evaluating the LHS.
1350   // This contains the '&&' or '||' as the terminator.
1351   CFGBlock *LHSBlock = createBlock(false);
1352   LHSBlock->setTerminator(B);
1353 
1354   Block = LHSBlock;
1355   CFGBlock *EntryLHSBlock = addStmt(LHS);
1356 
1357   if (badCFG)
1358     return std::make_pair((CFGBlock*)0, (CFGBlock*)0);
1359 
1360   // See if this is a known constant.
1361   TryResult KnownVal = tryEvaluateBool(LHS);
1362 
1363   // Now link the LHSBlock with RHSBlock.
1364   if (B->getOpcode() == BO_LOr) {
1365     addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : TrueBlock);
1366     addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : RHSBlock);
1367   } else {
1368     assert(B->getOpcode() == BO_LAnd);
1369     addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
1370     addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : FalseBlock);
1371   }
1372 
1373   return std::make_pair(EntryLHSBlock, ExitBlock);
1374 }
1375 
1376 
1377 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1378                                           AddStmtChoice asc) {
1379    // && or ||
1380   if (B->isLogicalOp())
1381     return VisitLogicalOperator(B);
1382 
1383   if (B->getOpcode() == BO_Comma) { // ,
1384     autoCreateBlock();
1385     appendStmt(Block, B);
1386     addStmt(B->getRHS());
1387     return addStmt(B->getLHS());
1388   }
1389 
1390   if (B->isAssignmentOp()) {
1391     if (asc.alwaysAdd(*this, B)) {
1392       autoCreateBlock();
1393       appendStmt(Block, B);
1394     }
1395     Visit(B->getLHS());
1396     return Visit(B->getRHS());
1397   }
1398 
1399   if (asc.alwaysAdd(*this, B)) {
1400     autoCreateBlock();
1401     appendStmt(Block, B);
1402   }
1403 
1404   CFGBlock *RBlock = Visit(B->getRHS());
1405   CFGBlock *LBlock = Visit(B->getLHS());
1406   // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1407   // containing a DoStmt, and the LHS doesn't create a new block, then we should
1408   // return RBlock.  Otherwise we'll incorrectly return NULL.
1409   return (LBlock ? LBlock : RBlock);
1410 }
1411 
1412 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
1413   if (asc.alwaysAdd(*this, E)) {
1414     autoCreateBlock();
1415     appendStmt(Block, E);
1416   }
1417   return Block;
1418 }
1419 
1420 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1421   // "break" is a control-flow statement.  Thus we stop processing the current
1422   // block.
1423   if (badCFG)
1424     return 0;
1425 
1426   // Now create a new block that ends with the break statement.
1427   Block = createBlock(false);
1428   Block->setTerminator(B);
1429 
1430   // If there is no target for the break, then we are looking at an incomplete
1431   // AST.  This means that the CFG cannot be constructed.
1432   if (BreakJumpTarget.block) {
1433     addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1434     addSuccessor(Block, BreakJumpTarget.block);
1435   } else
1436     badCFG = true;
1437 
1438 
1439   return Block;
1440 }
1441 
1442 static bool CanThrow(Expr *E, ASTContext &Ctx) {
1443   QualType Ty = E->getType();
1444   if (Ty->isFunctionPointerType())
1445     Ty = Ty->getAs<PointerType>()->getPointeeType();
1446   else if (Ty->isBlockPointerType())
1447     Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
1448 
1449   const FunctionType *FT = Ty->getAs<FunctionType>();
1450   if (FT) {
1451     if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
1452       if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
1453           Proto->isNothrow(Ctx))
1454         return false;
1455   }
1456   return true;
1457 }
1458 
1459 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
1460   // Compute the callee type.
1461   QualType calleeType = C->getCallee()->getType();
1462   if (calleeType == Context->BoundMemberTy) {
1463     QualType boundType = Expr::findBoundMemberType(C->getCallee());
1464 
1465     // We should only get a null bound type if processing a dependent
1466     // CFG.  Recover by assuming nothing.
1467     if (!boundType.isNull()) calleeType = boundType;
1468   }
1469 
1470   // If this is a call to a no-return function, this stops the block here.
1471   bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1472 
1473   bool AddEHEdge = false;
1474 
1475   // Languages without exceptions are assumed to not throw.
1476   if (Context->getLangOpts().Exceptions) {
1477     if (BuildOpts.AddEHEdges)
1478       AddEHEdge = true;
1479   }
1480 
1481   // If this is a call to a builtin function, it might not actually evaluate
1482   // its arguments. Don't add them to the CFG if this is the case.
1483   bool OmitArguments = false;
1484 
1485   if (FunctionDecl *FD = C->getDirectCallee()) {
1486     if (FD->isNoReturn())
1487       NoReturn = true;
1488     if (FD->hasAttr<NoThrowAttr>())
1489       AddEHEdge = false;
1490     if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1491       OmitArguments = true;
1492   }
1493 
1494   if (!CanThrow(C->getCallee(), *Context))
1495     AddEHEdge = false;
1496 
1497   if (OmitArguments) {
1498     assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1499     assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1500     autoCreateBlock();
1501     appendStmt(Block, C);
1502     return Visit(C->getCallee());
1503   }
1504 
1505   if (!NoReturn && !AddEHEdge) {
1506     return VisitStmt(C, asc.withAlwaysAdd(true));
1507   }
1508 
1509   if (Block) {
1510     Succ = Block;
1511     if (badCFG)
1512       return 0;
1513   }
1514 
1515   if (NoReturn)
1516     Block = createNoReturnBlock();
1517   else
1518     Block = createBlock();
1519 
1520   appendStmt(Block, C);
1521 
1522   if (AddEHEdge) {
1523     // Add exceptional edges.
1524     if (TryTerminatedBlock)
1525       addSuccessor(Block, TryTerminatedBlock);
1526     else
1527       addSuccessor(Block, &cfg->getExit());
1528   }
1529 
1530   return VisitChildren(C);
1531 }
1532 
1533 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1534                                       AddStmtChoice asc) {
1535   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1536   appendStmt(ConfluenceBlock, C);
1537   if (badCFG)
1538     return 0;
1539 
1540   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1541   Succ = ConfluenceBlock;
1542   Block = NULL;
1543   CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
1544   if (badCFG)
1545     return 0;
1546 
1547   Succ = ConfluenceBlock;
1548   Block = NULL;
1549   CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
1550   if (badCFG)
1551     return 0;
1552 
1553   Block = createBlock(false);
1554   // See if this is a known constant.
1555   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1556   addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1557   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1558   Block->setTerminator(C);
1559   return addStmt(C->getCond());
1560 }
1561 
1562 
1563 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
1564   addLocalScopeAndDtors(C);
1565   CFGBlock *LastBlock = Block;
1566 
1567   for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1568        I != E; ++I ) {
1569     // If we hit a segment of code just containing ';' (NullStmts), we can
1570     // get a null block back.  In such cases, just use the LastBlock
1571     if (CFGBlock *newBlock = addStmt(*I))
1572       LastBlock = newBlock;
1573 
1574     if (badCFG)
1575       return NULL;
1576   }
1577 
1578   return LastBlock;
1579 }
1580 
1581 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
1582                                                AddStmtChoice asc) {
1583   const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
1584   const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL);
1585 
1586   // Create the confluence block that will "merge" the results of the ternary
1587   // expression.
1588   CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1589   appendStmt(ConfluenceBlock, C);
1590   if (badCFG)
1591     return 0;
1592 
1593   AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
1594 
1595   // Create a block for the LHS expression if there is an LHS expression.  A
1596   // GCC extension allows LHS to be NULL, causing the condition to be the
1597   // value that is returned instead.
1598   //  e.g: x ?: y is shorthand for: x ? x : y;
1599   Succ = ConfluenceBlock;
1600   Block = NULL;
1601   CFGBlock *LHSBlock = 0;
1602   const Expr *trueExpr = C->getTrueExpr();
1603   if (trueExpr != opaqueValue) {
1604     LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
1605     if (badCFG)
1606       return 0;
1607     Block = NULL;
1608   }
1609   else
1610     LHSBlock = ConfluenceBlock;
1611 
1612   // Create the block for the RHS expression.
1613   Succ = ConfluenceBlock;
1614   CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
1615   if (badCFG)
1616     return 0;
1617 
1618   // If the condition is a logical '&&' or '||', build a more accurate CFG.
1619   if (BinaryOperator *Cond =
1620         dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1621     if (Cond->isLogicalOp())
1622       return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1623 
1624   // Create the block that will contain the condition.
1625   Block = createBlock(false);
1626 
1627   // See if this is a known constant.
1628   const TryResult& KnownVal = tryEvaluateBool(C->getCond());
1629   addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
1630   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
1631   Block->setTerminator(C);
1632   Expr *condExpr = C->getCond();
1633 
1634   if (opaqueValue) {
1635     // Run the condition expression if it's not trivially expressed in
1636     // terms of the opaque value (or if there is no opaque value).
1637     if (condExpr != opaqueValue)
1638       addStmt(condExpr);
1639 
1640     // Before that, run the common subexpression if there was one.
1641     // At least one of this or the above will be run.
1642     return addStmt(BCO->getCommon());
1643   }
1644 
1645   return addStmt(condExpr);
1646 }
1647 
1648 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
1649   // Check if the Decl is for an __label__.  If so, elide it from the
1650   // CFG entirely.
1651   if (isa<LabelDecl>(*DS->decl_begin()))
1652     return Block;
1653 
1654   // This case also handles static_asserts.
1655   if (DS->isSingleDecl())
1656     return VisitDeclSubExpr(DS);
1657 
1658   CFGBlock *B = 0;
1659 
1660   // Build an individual DeclStmt for each decl.
1661   for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1662                                        E = DS->decl_rend();
1663        I != E; ++I) {
1664     // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1665     unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
1666                ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
1667 
1668     // Allocate the DeclStmt using the BumpPtrAllocator.  It will get
1669     // automatically freed with the CFG.
1670     DeclGroupRef DG(*I);
1671     Decl *D = *I;
1672     void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
1673     DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
1674     cfg->addSyntheticDeclStmt(DSNew, DS);
1675 
1676     // Append the fake DeclStmt to block.
1677     B = VisitDeclSubExpr(DSNew);
1678   }
1679 
1680   return B;
1681 }
1682 
1683 /// VisitDeclSubExpr - Utility method to add block-level expressions for
1684 /// DeclStmts and initializers in them.
1685 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
1686   assert(DS->isSingleDecl() && "Can handle single declarations only.");
1687   VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1688 
1689   if (!VD) {
1690     // Of everything that can be declared in a DeclStmt, only VarDecls impact
1691     // runtime semantics.
1692     return Block;
1693   }
1694 
1695   bool IsReference = false;
1696   bool HasTemporaries = false;
1697 
1698   // Guard static initializers under a branch.
1699   CFGBlock *blockAfterStaticInit = 0;
1700 
1701   if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
1702     // For static variables, we need to create a branch to track
1703     // whether or not they are initialized.
1704     if (Block) {
1705       Succ = Block;
1706       Block = 0;
1707       if (badCFG)
1708         return 0;
1709     }
1710     blockAfterStaticInit = Succ;
1711   }
1712 
1713   // Destructors of temporaries in initialization expression should be called
1714   // after initialization finishes.
1715   Expr *Init = VD->getInit();
1716   if (Init) {
1717     IsReference = VD->getType()->isReferenceType();
1718     HasTemporaries = isa<ExprWithCleanups>(Init);
1719 
1720     if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
1721       // Generate destructors for temporaries in initialization expression.
1722       VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1723           IsReference);
1724     }
1725   }
1726 
1727   autoCreateBlock();
1728   appendStmt(Block, DS);
1729 
1730   // Keep track of the last non-null block, as 'Block' can be nulled out
1731   // if the initializer expression is something like a 'while' in a
1732   // statement-expression.
1733   CFGBlock *LastBlock = Block;
1734 
1735   if (Init) {
1736     if (HasTemporaries) {
1737       // For expression with temporaries go directly to subexpression to omit
1738       // generating destructors for the second time.
1739       ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
1740       if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
1741         LastBlock = newBlock;
1742     }
1743     else {
1744       if (CFGBlock *newBlock = Visit(Init))
1745         LastBlock = newBlock;
1746     }
1747   }
1748 
1749   // If the type of VD is a VLA, then we must process its size expressions.
1750   for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
1751        VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) {
1752     if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
1753       LastBlock = newBlock;
1754   }
1755 
1756   // Remove variable from local scope.
1757   if (ScopePos && VD == *ScopePos)
1758     ++ScopePos;
1759 
1760   CFGBlock *B = LastBlock;
1761   if (blockAfterStaticInit) {
1762     Succ = B;
1763     Block = createBlock(false);
1764     Block->setTerminator(DS);
1765     addSuccessor(Block, blockAfterStaticInit);
1766     addSuccessor(Block, B);
1767     B = Block;
1768   }
1769 
1770   return B;
1771 }
1772 
1773 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
1774   // We may see an if statement in the middle of a basic block, or it may be the
1775   // first statement we are processing.  In either case, we create a new basic
1776   // block.  First, we create the blocks for the then...else statements, and
1777   // then we create the block containing the if statement.  If we were in the
1778   // middle of a block, we stop processing that block.  That block is then the
1779   // implicit successor for the "then" and "else" clauses.
1780 
1781   // Save local scope position because in case of condition variable ScopePos
1782   // won't be restored when traversing AST.
1783   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1784 
1785   // Create local scope for possible condition variable.
1786   // Store scope position. Add implicit destructor.
1787   if (VarDecl *VD = I->getConditionVariable()) {
1788     LocalScope::const_iterator BeginScopePos = ScopePos;
1789     addLocalScopeForVarDecl(VD);
1790     addAutomaticObjDtors(ScopePos, BeginScopePos, I);
1791   }
1792 
1793   // The block we were processing is now finished.  Make it the successor
1794   // block.
1795   if (Block) {
1796     Succ = Block;
1797     if (badCFG)
1798       return 0;
1799   }
1800 
1801   // Process the false branch.
1802   CFGBlock *ElseBlock = Succ;
1803 
1804   if (Stmt *Else = I->getElse()) {
1805     SaveAndRestore<CFGBlock*> sv(Succ);
1806 
1807     // NULL out Block so that the recursive call to Visit will
1808     // create a new basic block.
1809     Block = NULL;
1810 
1811     // If branch is not a compound statement create implicit scope
1812     // and add destructors.
1813     if (!isa<CompoundStmt>(Else))
1814       addLocalScopeAndDtors(Else);
1815 
1816     ElseBlock = addStmt(Else);
1817 
1818     if (!ElseBlock) // Can occur when the Else body has all NullStmts.
1819       ElseBlock = sv.get();
1820     else if (Block) {
1821       if (badCFG)
1822         return 0;
1823     }
1824   }
1825 
1826   // Process the true branch.
1827   CFGBlock *ThenBlock;
1828   {
1829     Stmt *Then = I->getThen();
1830     assert(Then);
1831     SaveAndRestore<CFGBlock*> sv(Succ);
1832     Block = NULL;
1833 
1834     // If branch is not a compound statement create implicit scope
1835     // and add destructors.
1836     if (!isa<CompoundStmt>(Then))
1837       addLocalScopeAndDtors(Then);
1838 
1839     ThenBlock = addStmt(Then);
1840 
1841     if (!ThenBlock) {
1842       // We can reach here if the "then" body has all NullStmts.
1843       // Create an empty block so we can distinguish between true and false
1844       // branches in path-sensitive analyses.
1845       ThenBlock = createBlock(false);
1846       addSuccessor(ThenBlock, sv.get());
1847     } else if (Block) {
1848       if (badCFG)
1849         return 0;
1850     }
1851   }
1852 
1853   // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
1854   // having these handle the actual control-flow jump.  Note that
1855   // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
1856   // we resort to the old control-flow behavior.  This special handling
1857   // removes infeasible paths from the control-flow graph by having the
1858   // control-flow transfer of '&&' or '||' go directly into the then/else
1859   // blocks directly.
1860   if (!I->getConditionVariable())
1861     if (BinaryOperator *Cond =
1862             dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
1863       if (Cond->isLogicalOp())
1864         return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
1865 
1866   // Now create a new block containing the if statement.
1867   Block = createBlock(false);
1868 
1869   // Set the terminator of the new block to the If statement.
1870   Block->setTerminator(I);
1871 
1872   // See if this is a known constant.
1873   const TryResult &KnownVal = tryEvaluateBool(I->getCond());
1874 
1875   // Now add the successors.
1876   addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
1877   addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
1878 
1879   // Add the condition as the last statement in the new block.  This may create
1880   // new blocks as the condition may contain control-flow.  Any newly created
1881   // blocks will be pointed to be "Block".
1882   CFGBlock *LastBlock = addStmt(I->getCond());
1883 
1884   // Finally, if the IfStmt contains a condition variable, add both the IfStmt
1885   // and the condition variable initialization to the CFG.
1886   if (VarDecl *VD = I->getConditionVariable()) {
1887     if (Expr *Init = VD->getInit()) {
1888       autoCreateBlock();
1889       appendStmt(Block, I->getConditionVariableDeclStmt());
1890       LastBlock = addStmt(Init);
1891     }
1892   }
1893 
1894   return LastBlock;
1895 }
1896 
1897 
1898 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
1899   // If we were in the middle of a block we stop processing that block.
1900   //
1901   // NOTE: If a "return" appears in the middle of a block, this means that the
1902   //       code afterwards is DEAD (unreachable).  We still keep a basic block
1903   //       for that code; a simple "mark-and-sweep" from the entry block will be
1904   //       able to report such dead blocks.
1905 
1906   // Create the new block.
1907   Block = createBlock(false);
1908 
1909   addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
1910 
1911   // If the one of the destructors does not return, we already have the Exit
1912   // block as a successor.
1913   if (!Block->hasNoReturnElement())
1914     addSuccessor(Block, &cfg->getExit());
1915 
1916   // Add the return statement to the block.  This may create new blocks if R
1917   // contains control-flow (short-circuit operations).
1918   return VisitStmt(R, AddStmtChoice::AlwaysAdd);
1919 }
1920 
1921 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
1922   // Get the block of the labeled statement.  Add it to our map.
1923   addStmt(L->getSubStmt());
1924   CFGBlock *LabelBlock = Block;
1925 
1926   if (!LabelBlock)              // This can happen when the body is empty, i.e.
1927     LabelBlock = createBlock(); // scopes that only contains NullStmts.
1928 
1929   assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
1930          "label already in map");
1931   LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
1932 
1933   // Labels partition blocks, so this is the end of the basic block we were
1934   // processing (L is the block's label).  Because this is label (and we have
1935   // already processed the substatement) there is no extra control-flow to worry
1936   // about.
1937   LabelBlock->setLabel(L);
1938   if (badCFG)
1939     return 0;
1940 
1941   // We set Block to NULL to allow lazy creation of a new block (if necessary);
1942   Block = NULL;
1943 
1944   // This block is now the implicit successor of other blocks.
1945   Succ = LabelBlock;
1946 
1947   return LabelBlock;
1948 }
1949 
1950 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
1951   CFGBlock *LastBlock = VisitNoRecurse(E, asc);
1952   for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
1953        et = E->capture_init_end(); it != et; ++it) {
1954     if (Expr *Init = *it) {
1955       CFGBlock *Tmp = Visit(Init);
1956       if (Tmp != 0)
1957         LastBlock = Tmp;
1958     }
1959   }
1960   return LastBlock;
1961 }
1962 
1963 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
1964   // Goto is a control-flow statement.  Thus we stop processing the current
1965   // block and create a new one.
1966 
1967   Block = createBlock(false);
1968   Block->setTerminator(G);
1969 
1970   // If we already know the mapping to the label block add the successor now.
1971   LabelMapTy::iterator I = LabelMap.find(G->getLabel());
1972 
1973   if (I == LabelMap.end())
1974     // We will need to backpatch this block later.
1975     BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
1976   else {
1977     JumpTarget JT = I->second;
1978     addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
1979     addSuccessor(Block, JT.block);
1980   }
1981 
1982   return Block;
1983 }
1984 
1985 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
1986   CFGBlock *LoopSuccessor = NULL;
1987 
1988   // Save local scope position because in case of condition variable ScopePos
1989   // won't be restored when traversing AST.
1990   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
1991 
1992   // Create local scope for init statement and possible condition variable.
1993   // Add destructor for init statement and condition variable.
1994   // Store scope position for continue statement.
1995   if (Stmt *Init = F->getInit())
1996     addLocalScopeForStmt(Init);
1997   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
1998 
1999   if (VarDecl *VD = F->getConditionVariable())
2000     addLocalScopeForVarDecl(VD);
2001   LocalScope::const_iterator ContinueScopePos = ScopePos;
2002 
2003   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2004 
2005   // "for" is a control-flow statement.  Thus we stop processing the current
2006   // block.
2007   if (Block) {
2008     if (badCFG)
2009       return 0;
2010     LoopSuccessor = Block;
2011   } else
2012     LoopSuccessor = Succ;
2013 
2014   // Save the current value for the break targets.
2015   // All breaks should go to the code following the loop.
2016   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2017   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2018 
2019   CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2020 
2021   // Now create the loop body.
2022   {
2023     assert(F->getBody());
2024 
2025     // Save the current values for Block, Succ, continue and break targets.
2026     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2027     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
2028 
2029     // Create an empty block to represent the transition block for looping back
2030     // to the head of the loop.  If we have increment code, it will
2031     // go in this block as well.
2032     Block = Succ = TransitionBlock = createBlock(false);
2033     TransitionBlock->setLoopTarget(F);
2034 
2035     if (Stmt *I = F->getInc()) {
2036       // Generate increment code in its own basic block.  This is the target of
2037       // continue statements.
2038       Succ = addStmt(I);
2039     }
2040 
2041     // Finish up the increment (or empty) block if it hasn't been already.
2042     if (Block) {
2043       assert(Block == Succ);
2044       if (badCFG)
2045         return 0;
2046       Block = 0;
2047     }
2048 
2049    // The starting block for the loop increment is the block that should
2050    // represent the 'loop target' for looping back to the start of the loop.
2051    ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2052    ContinueJumpTarget.block->setLoopTarget(F);
2053 
2054     // Loop body should end with destructor of Condition variable (if any).
2055     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
2056 
2057     // If body is not a compound statement create implicit scope
2058     // and add destructors.
2059     if (!isa<CompoundStmt>(F->getBody()))
2060       addLocalScopeAndDtors(F->getBody());
2061 
2062     // Now populate the body block, and in the process create new blocks as we
2063     // walk the body of the loop.
2064     BodyBlock = addStmt(F->getBody());
2065 
2066     if (!BodyBlock) {
2067       // In the case of "for (...;...;...);" we can have a null BodyBlock.
2068       // Use the continue jump target as the proxy for the body.
2069       BodyBlock = ContinueJumpTarget.block;
2070     }
2071     else if (badCFG)
2072       return 0;
2073   }
2074 
2075   // Because of short-circuit evaluation, the condition of the loop can span
2076   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2077   // evaluate the condition.
2078   CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2079 
2080   do {
2081     Expr *C = F->getCond();
2082 
2083     // Specially handle logical operators, which have a slightly
2084     // more optimal CFG representation.
2085     if (BinaryOperator *Cond =
2086             dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : 0))
2087       if (Cond->isLogicalOp()) {
2088         llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2089           VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2090         break;
2091       }
2092 
2093     // The default case when not handling logical operators.
2094     EntryConditionBlock = ExitConditionBlock = createBlock(false);
2095     ExitConditionBlock->setTerminator(F);
2096 
2097     // See if this is a known constant.
2098     TryResult KnownVal(true);
2099 
2100     if (C) {
2101       // Now add the actual condition to the condition block.
2102       // Because the condition itself may contain control-flow, new blocks may
2103       // be created.  Thus we update "Succ" after adding the condition.
2104       Block = ExitConditionBlock;
2105       EntryConditionBlock = addStmt(C);
2106 
2107       // If this block contains a condition variable, add both the condition
2108       // variable and initializer to the CFG.
2109       if (VarDecl *VD = F->getConditionVariable()) {
2110         if (Expr *Init = VD->getInit()) {
2111           autoCreateBlock();
2112           appendStmt(Block, F->getConditionVariableDeclStmt());
2113           EntryConditionBlock = addStmt(Init);
2114           assert(Block == EntryConditionBlock);
2115         }
2116       }
2117 
2118       if (Block && badCFG)
2119         return 0;
2120 
2121       KnownVal = tryEvaluateBool(C);
2122     }
2123 
2124     // Add the loop body entry as a successor to the condition.
2125     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2126     // Link up the condition block with the code that follows the loop.  (the
2127     // false branch).
2128     addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2129 
2130   } while (false);
2131 
2132   // Link up the loop-back block to the entry condition block.
2133   addSuccessor(TransitionBlock, EntryConditionBlock);
2134 
2135   // The condition block is the implicit successor for any code above the loop.
2136   Succ = EntryConditionBlock;
2137 
2138   // If the loop contains initialization, create a new block for those
2139   // statements.  This block can also contain statements that precede the loop.
2140   if (Stmt *I = F->getInit()) {
2141     Block = createBlock();
2142     return addStmt(I);
2143   }
2144 
2145   // There is no loop initialization.  We are thus basically a while loop.
2146   // NULL out Block to force lazy block construction.
2147   Block = NULL;
2148   Succ = EntryConditionBlock;
2149   return EntryConditionBlock;
2150 }
2151 
2152 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
2153   if (asc.alwaysAdd(*this, M)) {
2154     autoCreateBlock();
2155     appendStmt(Block, M);
2156   }
2157   return Visit(M->getBase());
2158 }
2159 
2160 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
2161   // Objective-C fast enumeration 'for' statements:
2162   //  http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2163   //
2164   //  for ( Type newVariable in collection_expression ) { statements }
2165   //
2166   //  becomes:
2167   //
2168   //   prologue:
2169   //     1. collection_expression
2170   //     T. jump to loop_entry
2171   //   loop_entry:
2172   //     1. side-effects of element expression
2173   //     1. ObjCForCollectionStmt [performs binding to newVariable]
2174   //     T. ObjCForCollectionStmt  TB, FB  [jumps to TB if newVariable != nil]
2175   //   TB:
2176   //     statements
2177   //     T. jump to loop_entry
2178   //   FB:
2179   //     what comes after
2180   //
2181   //  and
2182   //
2183   //  Type existingItem;
2184   //  for ( existingItem in expression ) { statements }
2185   //
2186   //  becomes:
2187   //
2188   //   the same with newVariable replaced with existingItem; the binding works
2189   //   the same except that for one ObjCForCollectionStmt::getElement() returns
2190   //   a DeclStmt and the other returns a DeclRefExpr.
2191   //
2192 
2193   CFGBlock *LoopSuccessor = 0;
2194 
2195   if (Block) {
2196     if (badCFG)
2197       return 0;
2198     LoopSuccessor = Block;
2199     Block = 0;
2200   } else
2201     LoopSuccessor = Succ;
2202 
2203   // Build the condition blocks.
2204   CFGBlock *ExitConditionBlock = createBlock(false);
2205 
2206   // Set the terminator for the "exit" condition block.
2207   ExitConditionBlock->setTerminator(S);
2208 
2209   // The last statement in the block should be the ObjCForCollectionStmt, which
2210   // performs the actual binding to 'element' and determines if there are any
2211   // more items in the collection.
2212   appendStmt(ExitConditionBlock, S);
2213   Block = ExitConditionBlock;
2214 
2215   // Walk the 'element' expression to see if there are any side-effects.  We
2216   // generate new blocks as necessary.  We DON'T add the statement by default to
2217   // the CFG unless it contains control-flow.
2218   CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2219                                         AddStmtChoice::NotAlwaysAdd);
2220   if (Block) {
2221     if (badCFG)
2222       return 0;
2223     Block = 0;
2224   }
2225 
2226   // The condition block is the implicit successor for the loop body as well as
2227   // any code above the loop.
2228   Succ = EntryConditionBlock;
2229 
2230   // Now create the true branch.
2231   {
2232     // Save the current values for Succ, continue and break targets.
2233     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2234     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2235                                save_break(BreakJumpTarget);
2236 
2237     // Add an intermediate block between the BodyBlock and the
2238     // EntryConditionBlock to represent the "loop back" transition, for looping
2239     // back to the head of the loop.
2240     CFGBlock *LoopBackBlock = 0;
2241     Succ = LoopBackBlock = createBlock();
2242     LoopBackBlock->setLoopTarget(S);
2243 
2244     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2245     ContinueJumpTarget = JumpTarget(Succ, ScopePos);
2246 
2247     CFGBlock *BodyBlock = addStmt(S->getBody());
2248 
2249     if (!BodyBlock)
2250       BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
2251     else if (Block) {
2252       if (badCFG)
2253         return 0;
2254     }
2255 
2256     // This new body block is a successor to our "exit" condition block.
2257     addSuccessor(ExitConditionBlock, BodyBlock);
2258   }
2259 
2260   // Link up the condition block with the code that follows the loop.
2261   // (the false branch).
2262   addSuccessor(ExitConditionBlock, LoopSuccessor);
2263 
2264   // Now create a prologue block to contain the collection expression.
2265   Block = createBlock();
2266   return addStmt(S->getCollection());
2267 }
2268 
2269 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2270   // Inline the body.
2271   return addStmt(S->getSubStmt());
2272   // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2273 }
2274 
2275 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
2276   // FIXME: Add locking 'primitives' to CFG for @synchronized.
2277 
2278   // Inline the body.
2279   CFGBlock *SyncBlock = addStmt(S->getSynchBody());
2280 
2281   // The sync body starts its own basic block.  This makes it a little easier
2282   // for diagnostic clients.
2283   if (SyncBlock) {
2284     if (badCFG)
2285       return 0;
2286 
2287     Block = 0;
2288     Succ = SyncBlock;
2289   }
2290 
2291   // Add the @synchronized to the CFG.
2292   autoCreateBlock();
2293   appendStmt(Block, S);
2294 
2295   // Inline the sync expression.
2296   return addStmt(S->getSynchExpr());
2297 }
2298 
2299 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
2300   // FIXME
2301   return NYS();
2302 }
2303 
2304 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2305   autoCreateBlock();
2306 
2307   // Add the PseudoObject as the last thing.
2308   appendStmt(Block, E);
2309 
2310   CFGBlock *lastBlock = Block;
2311 
2312   // Before that, evaluate all of the semantics in order.  In
2313   // CFG-land, that means appending them in reverse order.
2314   for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2315     Expr *Semantic = E->getSemanticExpr(--i);
2316 
2317     // If the semantic is an opaque value, we're being asked to bind
2318     // it to its source expression.
2319     if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2320       Semantic = OVE->getSourceExpr();
2321 
2322     if (CFGBlock *B = Visit(Semantic))
2323       lastBlock = B;
2324   }
2325 
2326   return lastBlock;
2327 }
2328 
2329 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
2330   CFGBlock *LoopSuccessor = NULL;
2331 
2332   // Save local scope position because in case of condition variable ScopePos
2333   // won't be restored when traversing AST.
2334   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2335 
2336   // Create local scope for possible condition variable.
2337   // Store scope position for continue statement.
2338   LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2339   if (VarDecl *VD = W->getConditionVariable()) {
2340     addLocalScopeForVarDecl(VD);
2341     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2342   }
2343 
2344   // "while" is a control-flow statement.  Thus we stop processing the current
2345   // block.
2346   if (Block) {
2347     if (badCFG)
2348       return 0;
2349     LoopSuccessor = Block;
2350     Block = 0;
2351   } else {
2352     LoopSuccessor = Succ;
2353   }
2354 
2355   CFGBlock *BodyBlock = 0, *TransitionBlock = 0;
2356 
2357   // Process the loop body.
2358   {
2359     assert(W->getBody());
2360 
2361     // Save the current values for Block, Succ, continue and break targets.
2362     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2363     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2364                                save_break(BreakJumpTarget);
2365 
2366     // Create an empty block to represent the transition block for looping back
2367     // to the head of the loop.
2368     Succ = TransitionBlock = createBlock(false);
2369     TransitionBlock->setLoopTarget(W);
2370     ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
2371 
2372     // All breaks should go to the code following the loop.
2373     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2374 
2375     // Loop body should end with destructor of Condition variable (if any).
2376     addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2377 
2378     // If body is not a compound statement create implicit scope
2379     // and add destructors.
2380     if (!isa<CompoundStmt>(W->getBody()))
2381       addLocalScopeAndDtors(W->getBody());
2382 
2383     // Create the body.  The returned block is the entry to the loop body.
2384     BodyBlock = addStmt(W->getBody());
2385 
2386     if (!BodyBlock)
2387       BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
2388     else if (Block && badCFG)
2389       return 0;
2390   }
2391 
2392   // Because of short-circuit evaluation, the condition of the loop can span
2393   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2394   // evaluate the condition.
2395   CFGBlock *EntryConditionBlock = 0, *ExitConditionBlock = 0;
2396 
2397   do {
2398     Expr *C = W->getCond();
2399 
2400     // Specially handle logical operators, which have a slightly
2401     // more optimal CFG representation.
2402     if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
2403       if (Cond->isLogicalOp()) {
2404         llvm::tie(EntryConditionBlock, ExitConditionBlock) =
2405           VisitLogicalOperator(Cond, W, BodyBlock,
2406                                LoopSuccessor);
2407         break;
2408       }
2409 
2410     // The default case when not handling logical operators.
2411     ExitConditionBlock = createBlock(false);
2412     ExitConditionBlock->setTerminator(W);
2413 
2414     // Now add the actual condition to the condition block.
2415     // Because the condition itself may contain control-flow, new blocks may
2416     // be created.  Thus we update "Succ" after adding the condition.
2417     Block = ExitConditionBlock;
2418     Block = EntryConditionBlock = addStmt(C);
2419 
2420     // If this block contains a condition variable, add both the condition
2421     // variable and initializer to the CFG.
2422     if (VarDecl *VD = W->getConditionVariable()) {
2423       if (Expr *Init = VD->getInit()) {
2424         autoCreateBlock();
2425         appendStmt(Block, W->getConditionVariableDeclStmt());
2426         EntryConditionBlock = addStmt(Init);
2427         assert(Block == EntryConditionBlock);
2428       }
2429     }
2430 
2431     if (Block && badCFG)
2432       return 0;
2433 
2434     // See if this is a known constant.
2435     const TryResult& KnownVal = tryEvaluateBool(C);
2436 
2437     // Add the loop body entry as a successor to the condition.
2438     addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
2439     // Link up the condition block with the code that follows the loop.  (the
2440     // false branch).
2441     addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2442 
2443   } while(false);
2444 
2445   // Link up the loop-back block to the entry condition block.
2446   addSuccessor(TransitionBlock, EntryConditionBlock);
2447 
2448   // There can be no more statements in the condition block since we loop back
2449   // to this block.  NULL out Block to force lazy creation of another block.
2450   Block = NULL;
2451 
2452   // Return the condition block, which is the dominating block for the loop.
2453   Succ = EntryConditionBlock;
2454   return EntryConditionBlock;
2455 }
2456 
2457 
2458 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
2459   // FIXME: For now we pretend that @catch and the code it contains does not
2460   //  exit.
2461   return Block;
2462 }
2463 
2464 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
2465   // FIXME: This isn't complete.  We basically treat @throw like a return
2466   //  statement.
2467 
2468   // If we were in the middle of a block we stop processing that block.
2469   if (badCFG)
2470     return 0;
2471 
2472   // Create the new block.
2473   Block = createBlock(false);
2474 
2475   // The Exit block is the only successor.
2476   addSuccessor(Block, &cfg->getExit());
2477 
2478   // Add the statement to the block.  This may create new blocks if S contains
2479   // control-flow (short-circuit operations).
2480   return VisitStmt(S, AddStmtChoice::AlwaysAdd);
2481 }
2482 
2483 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
2484   // If we were in the middle of a block we stop processing that block.
2485   if (badCFG)
2486     return 0;
2487 
2488   // Create the new block.
2489   Block = createBlock(false);
2490 
2491   if (TryTerminatedBlock)
2492     // The current try statement is the only successor.
2493     addSuccessor(Block, TryTerminatedBlock);
2494   else
2495     // otherwise the Exit block is the only successor.
2496     addSuccessor(Block, &cfg->getExit());
2497 
2498   // Add the statement to the block.  This may create new blocks if S contains
2499   // control-flow (short-circuit operations).
2500   return VisitStmt(T, AddStmtChoice::AlwaysAdd);
2501 }
2502 
2503 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
2504   CFGBlock *LoopSuccessor = NULL;
2505 
2506   // "do...while" is a control-flow statement.  Thus we stop processing the
2507   // current block.
2508   if (Block) {
2509     if (badCFG)
2510       return 0;
2511     LoopSuccessor = Block;
2512   } else
2513     LoopSuccessor = Succ;
2514 
2515   // Because of short-circuit evaluation, the condition of the loop can span
2516   // multiple basic blocks.  Thus we need the "Entry" and "Exit" blocks that
2517   // evaluate the condition.
2518   CFGBlock *ExitConditionBlock = createBlock(false);
2519   CFGBlock *EntryConditionBlock = ExitConditionBlock;
2520 
2521   // Set the terminator for the "exit" condition block.
2522   ExitConditionBlock->setTerminator(D);
2523 
2524   // Now add the actual condition to the condition block.  Because the condition
2525   // itself may contain control-flow, new blocks may be created.
2526   if (Stmt *C = D->getCond()) {
2527     Block = ExitConditionBlock;
2528     EntryConditionBlock = addStmt(C);
2529     if (Block) {
2530       if (badCFG)
2531         return 0;
2532     }
2533   }
2534 
2535   // The condition block is the implicit successor for the loop body.
2536   Succ = EntryConditionBlock;
2537 
2538   // See if this is a known constant.
2539   const TryResult &KnownVal = tryEvaluateBool(D->getCond());
2540 
2541   // Process the loop body.
2542   CFGBlock *BodyBlock = NULL;
2543   {
2544     assert(D->getBody());
2545 
2546     // Save the current values for Block, Succ, and continue and break targets
2547     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2548     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2549         save_break(BreakJumpTarget);
2550 
2551     // All continues within this loop should go to the condition block
2552     ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
2553 
2554     // All breaks should go to the code following the loop.
2555     BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
2556 
2557     // NULL out Block to force lazy instantiation of blocks for the body.
2558     Block = NULL;
2559 
2560     // If body is not a compound statement create implicit scope
2561     // and add destructors.
2562     if (!isa<CompoundStmt>(D->getBody()))
2563       addLocalScopeAndDtors(D->getBody());
2564 
2565     // Create the body.  The returned block is the entry to the loop body.
2566     BodyBlock = addStmt(D->getBody());
2567 
2568     if (!BodyBlock)
2569       BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
2570     else if (Block) {
2571       if (badCFG)
2572         return 0;
2573     }
2574 
2575     if (!KnownVal.isFalse()) {
2576       // Add an intermediate block between the BodyBlock and the
2577       // ExitConditionBlock to represent the "loop back" transition.  Create an
2578       // empty block to represent the transition block for looping back to the
2579       // head of the loop.
2580       // FIXME: Can we do this more efficiently without adding another block?
2581       Block = NULL;
2582       Succ = BodyBlock;
2583       CFGBlock *LoopBackBlock = createBlock();
2584       LoopBackBlock->setLoopTarget(D);
2585 
2586       // Add the loop body entry as a successor to the condition.
2587       addSuccessor(ExitConditionBlock, LoopBackBlock);
2588     }
2589     else
2590       addSuccessor(ExitConditionBlock, NULL);
2591   }
2592 
2593   // Link up the condition block with the code that follows the loop.
2594   // (the false branch).
2595   addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
2596 
2597   // There can be no more statements in the body block(s) since we loop back to
2598   // the body.  NULL out Block to force lazy creation of another block.
2599   Block = NULL;
2600 
2601   // Return the loop body, which is the dominating block for the loop.
2602   Succ = BodyBlock;
2603   return BodyBlock;
2604 }
2605 
2606 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
2607   // "continue" is a control-flow statement.  Thus we stop processing the
2608   // current block.
2609   if (badCFG)
2610     return 0;
2611 
2612   // Now create a new block that ends with the continue statement.
2613   Block = createBlock(false);
2614   Block->setTerminator(C);
2615 
2616   // If there is no target for the continue, then we are looking at an
2617   // incomplete AST.  This means the CFG cannot be constructed.
2618   if (ContinueJumpTarget.block) {
2619     addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2620     addSuccessor(Block, ContinueJumpTarget.block);
2621   } else
2622     badCFG = true;
2623 
2624   return Block;
2625 }
2626 
2627 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2628                                                     AddStmtChoice asc) {
2629 
2630   if (asc.alwaysAdd(*this, E)) {
2631     autoCreateBlock();
2632     appendStmt(Block, E);
2633   }
2634 
2635   // VLA types have expressions that must be evaluated.
2636   CFGBlock *lastBlock = Block;
2637 
2638   if (E->isArgumentType()) {
2639     for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
2640          VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
2641       lastBlock = addStmt(VA->getSizeExpr());
2642   }
2643   return lastBlock;
2644 }
2645 
2646 /// VisitStmtExpr - Utility method to handle (nested) statement
2647 ///  expressions (a GCC extension).
2648 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
2649   if (asc.alwaysAdd(*this, SE)) {
2650     autoCreateBlock();
2651     appendStmt(Block, SE);
2652   }
2653   return VisitCompoundStmt(SE->getSubStmt());
2654 }
2655 
2656 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
2657   // "switch" is a control-flow statement.  Thus we stop processing the current
2658   // block.
2659   CFGBlock *SwitchSuccessor = NULL;
2660 
2661   // Save local scope position because in case of condition variable ScopePos
2662   // won't be restored when traversing AST.
2663   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2664 
2665   // Create local scope for possible condition variable.
2666   // Store scope position. Add implicit destructor.
2667   if (VarDecl *VD = Terminator->getConditionVariable()) {
2668     LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
2669     addLocalScopeForVarDecl(VD);
2670     addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
2671   }
2672 
2673   if (Block) {
2674     if (badCFG)
2675       return 0;
2676     SwitchSuccessor = Block;
2677   } else SwitchSuccessor = Succ;
2678 
2679   // Save the current "switch" context.
2680   SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
2681                             save_default(DefaultCaseBlock);
2682   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
2683 
2684   // Set the "default" case to be the block after the switch statement.  If the
2685   // switch statement contains a "default:", this value will be overwritten with
2686   // the block for that code.
2687   DefaultCaseBlock = SwitchSuccessor;
2688 
2689   // Create a new block that will contain the switch statement.
2690   SwitchTerminatedBlock = createBlock(false);
2691 
2692   // Now process the switch body.  The code after the switch is the implicit
2693   // successor.
2694   Succ = SwitchSuccessor;
2695   BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
2696 
2697   // When visiting the body, the case statements should automatically get linked
2698   // up to the switch.  We also don't keep a pointer to the body, since all
2699   // control-flow from the switch goes to case/default statements.
2700   assert(Terminator->getBody() && "switch must contain a non-NULL body");
2701   Block = NULL;
2702 
2703   // For pruning unreachable case statements, save the current state
2704   // for tracking the condition value.
2705   SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
2706                                                      false);
2707 
2708   // Determine if the switch condition can be explicitly evaluated.
2709   assert(Terminator->getCond() && "switch condition must be non-NULL");
2710   Expr::EvalResult result;
2711   bool b = tryEvaluate(Terminator->getCond(), result);
2712   SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
2713                                                     b ? &result : 0);
2714 
2715   // If body is not a compound statement create implicit scope
2716   // and add destructors.
2717   if (!isa<CompoundStmt>(Terminator->getBody()))
2718     addLocalScopeAndDtors(Terminator->getBody());
2719 
2720   addStmt(Terminator->getBody());
2721   if (Block) {
2722     if (badCFG)
2723       return 0;
2724   }
2725 
2726   // If we have no "default:" case, the default transition is to the code
2727   // following the switch body.  Moreover, take into account if all the
2728   // cases of a switch are covered (e.g., switching on an enum value).
2729   //
2730   // Note: We add a successor to a switch that is considered covered yet has no
2731   //       case statements if the enumeration has no enumerators.
2732   bool SwitchAlwaysHasSuccessor = false;
2733   SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
2734   SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
2735                               Terminator->getSwitchCaseList();
2736   addSuccessor(SwitchTerminatedBlock,
2737                SwitchAlwaysHasSuccessor ? 0 : DefaultCaseBlock);
2738 
2739   // Add the terminator and condition in the switch block.
2740   SwitchTerminatedBlock->setTerminator(Terminator);
2741   Block = SwitchTerminatedBlock;
2742   CFGBlock *LastBlock = addStmt(Terminator->getCond());
2743 
2744   // Finally, if the SwitchStmt contains a condition variable, add both the
2745   // SwitchStmt and the condition variable initialization to the CFG.
2746   if (VarDecl *VD = Terminator->getConditionVariable()) {
2747     if (Expr *Init = VD->getInit()) {
2748       autoCreateBlock();
2749       appendStmt(Block, Terminator->getConditionVariableDeclStmt());
2750       LastBlock = addStmt(Init);
2751     }
2752   }
2753 
2754   return LastBlock;
2755 }
2756 
2757 static bool shouldAddCase(bool &switchExclusivelyCovered,
2758                           const Expr::EvalResult *switchCond,
2759                           const CaseStmt *CS,
2760                           ASTContext &Ctx) {
2761   if (!switchCond)
2762     return true;
2763 
2764   bool addCase = false;
2765 
2766   if (!switchExclusivelyCovered) {
2767     if (switchCond->Val.isInt()) {
2768       // Evaluate the LHS of the case value.
2769       const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
2770       const llvm::APSInt &condInt = switchCond->Val.getInt();
2771 
2772       if (condInt == lhsInt) {
2773         addCase = true;
2774         switchExclusivelyCovered = true;
2775       }
2776       else if (condInt < lhsInt) {
2777         if (const Expr *RHS = CS->getRHS()) {
2778           // Evaluate the RHS of the case value.
2779           const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
2780           if (V2 <= condInt) {
2781             addCase = true;
2782             switchExclusivelyCovered = true;
2783           }
2784         }
2785       }
2786     }
2787     else
2788       addCase = true;
2789   }
2790   return addCase;
2791 }
2792 
2793 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
2794   // CaseStmts are essentially labels, so they are the first statement in a
2795   // block.
2796   CFGBlock *TopBlock = 0, *LastBlock = 0;
2797 
2798   if (Stmt *Sub = CS->getSubStmt()) {
2799     // For deeply nested chains of CaseStmts, instead of doing a recursion
2800     // (which can blow out the stack), manually unroll and create blocks
2801     // along the way.
2802     while (isa<CaseStmt>(Sub)) {
2803       CFGBlock *currentBlock = createBlock(false);
2804       currentBlock->setLabel(CS);
2805 
2806       if (TopBlock)
2807         addSuccessor(LastBlock, currentBlock);
2808       else
2809         TopBlock = currentBlock;
2810 
2811       addSuccessor(SwitchTerminatedBlock,
2812                    shouldAddCase(switchExclusivelyCovered, switchCond,
2813                                  CS, *Context)
2814                    ? currentBlock : 0);
2815 
2816       LastBlock = currentBlock;
2817       CS = cast<CaseStmt>(Sub);
2818       Sub = CS->getSubStmt();
2819     }
2820 
2821     addStmt(Sub);
2822   }
2823 
2824   CFGBlock *CaseBlock = Block;
2825   if (!CaseBlock)
2826     CaseBlock = createBlock();
2827 
2828   // Cases statements partition blocks, so this is the top of the basic block we
2829   // were processing (the "case XXX:" is the label).
2830   CaseBlock->setLabel(CS);
2831 
2832   if (badCFG)
2833     return 0;
2834 
2835   // Add this block to the list of successors for the block with the switch
2836   // statement.
2837   assert(SwitchTerminatedBlock);
2838   addSuccessor(SwitchTerminatedBlock,
2839                shouldAddCase(switchExclusivelyCovered, switchCond,
2840                              CS, *Context)
2841                ? CaseBlock : 0);
2842 
2843   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2844   Block = NULL;
2845 
2846   if (TopBlock) {
2847     addSuccessor(LastBlock, CaseBlock);
2848     Succ = TopBlock;
2849   } else {
2850     // This block is now the implicit successor of other blocks.
2851     Succ = CaseBlock;
2852   }
2853 
2854   return Succ;
2855 }
2856 
2857 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
2858   if (Terminator->getSubStmt())
2859     addStmt(Terminator->getSubStmt());
2860 
2861   DefaultCaseBlock = Block;
2862 
2863   if (!DefaultCaseBlock)
2864     DefaultCaseBlock = createBlock();
2865 
2866   // Default statements partition blocks, so this is the top of the basic block
2867   // we were processing (the "default:" is the label).
2868   DefaultCaseBlock->setLabel(Terminator);
2869 
2870   if (badCFG)
2871     return 0;
2872 
2873   // Unlike case statements, we don't add the default block to the successors
2874   // for the switch statement immediately.  This is done when we finish
2875   // processing the switch statement.  This allows for the default case
2876   // (including a fall-through to the code after the switch statement) to always
2877   // be the last successor of a switch-terminated block.
2878 
2879   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2880   Block = NULL;
2881 
2882   // This block is now the implicit successor of other blocks.
2883   Succ = DefaultCaseBlock;
2884 
2885   return DefaultCaseBlock;
2886 }
2887 
2888 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
2889   // "try"/"catch" is a control-flow statement.  Thus we stop processing the
2890   // current block.
2891   CFGBlock *TrySuccessor = NULL;
2892 
2893   if (Block) {
2894     if (badCFG)
2895       return 0;
2896     TrySuccessor = Block;
2897   } else TrySuccessor = Succ;
2898 
2899   CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
2900 
2901   // Create a new block that will contain the try statement.
2902   CFGBlock *NewTryTerminatedBlock = createBlock(false);
2903   // Add the terminator in the try block.
2904   NewTryTerminatedBlock->setTerminator(Terminator);
2905 
2906   bool HasCatchAll = false;
2907   for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
2908     // The code after the try is the implicit successor.
2909     Succ = TrySuccessor;
2910     CXXCatchStmt *CS = Terminator->getHandler(h);
2911     if (CS->getExceptionDecl() == 0) {
2912       HasCatchAll = true;
2913     }
2914     Block = NULL;
2915     CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
2916     if (CatchBlock == 0)
2917       return 0;
2918     // Add this block to the list of successors for the block with the try
2919     // statement.
2920     addSuccessor(NewTryTerminatedBlock, CatchBlock);
2921   }
2922   if (!HasCatchAll) {
2923     if (PrevTryTerminatedBlock)
2924       addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
2925     else
2926       addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2927   }
2928 
2929   // The code after the try is the implicit successor.
2930   Succ = TrySuccessor;
2931 
2932   // Save the current "try" context.
2933   SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
2934   cfg->addTryDispatchBlock(TryTerminatedBlock);
2935 
2936   assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
2937   Block = NULL;
2938   return addStmt(Terminator->getTryBlock());
2939 }
2940 
2941 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
2942   // CXXCatchStmt are treated like labels, so they are the first statement in a
2943   // block.
2944 
2945   // Save local scope position because in case of exception variable ScopePos
2946   // won't be restored when traversing AST.
2947   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2948 
2949   // Create local scope for possible exception variable.
2950   // Store scope position. Add implicit destructor.
2951   if (VarDecl *VD = CS->getExceptionDecl()) {
2952     LocalScope::const_iterator BeginScopePos = ScopePos;
2953     addLocalScopeForVarDecl(VD);
2954     addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
2955   }
2956 
2957   if (CS->getHandlerBlock())
2958     addStmt(CS->getHandlerBlock());
2959 
2960   CFGBlock *CatchBlock = Block;
2961   if (!CatchBlock)
2962     CatchBlock = createBlock();
2963 
2964   // CXXCatchStmt is more than just a label.  They have semantic meaning
2965   // as well, as they implicitly "initialize" the catch variable.  Add
2966   // it to the CFG as a CFGElement so that the control-flow of these
2967   // semantics gets captured.
2968   appendStmt(CatchBlock, CS);
2969 
2970   // Also add the CXXCatchStmt as a label, to mirror handling of regular
2971   // labels.
2972   CatchBlock->setLabel(CS);
2973 
2974   // Bail out if the CFG is bad.
2975   if (badCFG)
2976     return 0;
2977 
2978   // We set Block to NULL to allow lazy creation of a new block (if necessary)
2979   Block = NULL;
2980 
2981   return CatchBlock;
2982 }
2983 
2984 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
2985   // C++0x for-range statements are specified as [stmt.ranged]:
2986   //
2987   // {
2988   //   auto && __range = range-init;
2989   //   for ( auto __begin = begin-expr,
2990   //         __end = end-expr;
2991   //         __begin != __end;
2992   //         ++__begin ) {
2993   //     for-range-declaration = *__begin;
2994   //     statement
2995   //   }
2996   // }
2997 
2998   // Save local scope position before the addition of the implicit variables.
2999   SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3000 
3001   // Create local scopes and destructors for range, begin and end variables.
3002   if (Stmt *Range = S->getRangeStmt())
3003     addLocalScopeForStmt(Range);
3004   if (Stmt *BeginEnd = S->getBeginEndStmt())
3005     addLocalScopeForStmt(BeginEnd);
3006   addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3007 
3008   LocalScope::const_iterator ContinueScopePos = ScopePos;
3009 
3010   // "for" is a control-flow statement.  Thus we stop processing the current
3011   // block.
3012   CFGBlock *LoopSuccessor = NULL;
3013   if (Block) {
3014     if (badCFG)
3015       return 0;
3016     LoopSuccessor = Block;
3017   } else
3018     LoopSuccessor = Succ;
3019 
3020   // Save the current value for the break targets.
3021   // All breaks should go to the code following the loop.
3022   SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3023   BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3024 
3025   // The block for the __begin != __end expression.
3026   CFGBlock *ConditionBlock = createBlock(false);
3027   ConditionBlock->setTerminator(S);
3028 
3029   // Now add the actual condition to the condition block.
3030   if (Expr *C = S->getCond()) {
3031     Block = ConditionBlock;
3032     CFGBlock *BeginConditionBlock = addStmt(C);
3033     if (badCFG)
3034       return 0;
3035     assert(BeginConditionBlock == ConditionBlock &&
3036            "condition block in for-range was unexpectedly complex");
3037     (void)BeginConditionBlock;
3038   }
3039 
3040   // The condition block is the implicit successor for the loop body as well as
3041   // any code above the loop.
3042   Succ = ConditionBlock;
3043 
3044   // See if this is a known constant.
3045   TryResult KnownVal(true);
3046 
3047   if (S->getCond())
3048     KnownVal = tryEvaluateBool(S->getCond());
3049 
3050   // Now create the loop body.
3051   {
3052     assert(S->getBody());
3053 
3054     // Save the current values for Block, Succ, and continue targets.
3055     SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3056     SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3057 
3058     // Generate increment code in its own basic block.  This is the target of
3059     // continue statements.
3060     Block = 0;
3061     Succ = addStmt(S->getInc());
3062     ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3063 
3064     // The starting block for the loop increment is the block that should
3065     // represent the 'loop target' for looping back to the start of the loop.
3066     ContinueJumpTarget.block->setLoopTarget(S);
3067 
3068     // Finish up the increment block and prepare to start the loop body.
3069     assert(Block);
3070     if (badCFG)
3071       return 0;
3072     Block = 0;
3073 
3074 
3075     // Add implicit scope and dtors for loop variable.
3076     addLocalScopeAndDtors(S->getLoopVarStmt());
3077 
3078     // Populate a new block to contain the loop body and loop variable.
3079     addStmt(S->getBody());
3080     if (badCFG)
3081       return 0;
3082     CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
3083     if (badCFG)
3084       return 0;
3085 
3086     // This new body block is a successor to our condition block.
3087     addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : LoopVarStmtBlock);
3088   }
3089 
3090   // Link up the condition block with the code that follows the loop (the
3091   // false branch).
3092   addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor);
3093 
3094   // Add the initialization statements.
3095   Block = createBlock();
3096   addStmt(S->getBeginEndStmt());
3097   return addStmt(S->getRangeStmt());
3098 }
3099 
3100 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
3101     AddStmtChoice asc) {
3102   if (BuildOpts.AddTemporaryDtors) {
3103     // If adding implicit destructors visit the full expression for adding
3104     // destructors of temporaries.
3105     VisitForTemporaryDtors(E->getSubExpr());
3106 
3107     // Full expression has to be added as CFGStmt so it will be sequenced
3108     // before destructors of it's temporaries.
3109     asc = asc.withAlwaysAdd(true);
3110   }
3111   return Visit(E->getSubExpr(), asc);
3112 }
3113 
3114 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3115                                                 AddStmtChoice asc) {
3116   if (asc.alwaysAdd(*this, E)) {
3117     autoCreateBlock();
3118     appendStmt(Block, E);
3119 
3120     // We do not want to propagate the AlwaysAdd property.
3121     asc = asc.withAlwaysAdd(false);
3122   }
3123   return Visit(E->getSubExpr(), asc);
3124 }
3125 
3126 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3127                                             AddStmtChoice asc) {
3128   autoCreateBlock();
3129   appendStmt(Block, C);
3130 
3131   return VisitChildren(C);
3132 }
3133 
3134 CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3135                                       AddStmtChoice asc) {
3136 
3137   autoCreateBlock();
3138   appendStmt(Block, NE);
3139 
3140   if (NE->getInitializer())
3141     Block = Visit(NE->getInitializer());
3142   if (BuildOpts.AddCXXNewAllocator)
3143     appendNewAllocator(Block, NE);
3144   if (NE->isArray())
3145     Block = Visit(NE->getArraySize());
3146   for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3147        E = NE->placement_arg_end(); I != E; ++I)
3148     Block = Visit(*I);
3149   return Block;
3150 }
3151 
3152 CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3153                                          AddStmtChoice asc) {
3154   autoCreateBlock();
3155   appendStmt(Block, DE);
3156   QualType DTy = DE->getDestroyedType();
3157   DTy = DTy.getNonReferenceType();
3158   CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3159   if (RD) {
3160     if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3161       appendDeleteDtor(Block, RD, DE);
3162   }
3163 
3164   return VisitChildren(DE);
3165 }
3166 
3167 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3168                                                  AddStmtChoice asc) {
3169   if (asc.alwaysAdd(*this, E)) {
3170     autoCreateBlock();
3171     appendStmt(Block, E);
3172     // We do not want to propagate the AlwaysAdd property.
3173     asc = asc.withAlwaysAdd(false);
3174   }
3175   return Visit(E->getSubExpr(), asc);
3176 }
3177 
3178 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3179                                                   AddStmtChoice asc) {
3180   autoCreateBlock();
3181   appendStmt(Block, C);
3182   return VisitChildren(C);
3183 }
3184 
3185 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3186                                             AddStmtChoice asc) {
3187   if (asc.alwaysAdd(*this, E)) {
3188     autoCreateBlock();
3189     appendStmt(Block, E);
3190   }
3191   return Visit(E->getSubExpr(), AddStmtChoice());
3192 }
3193 
3194 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3195   // Lazily create the indirect-goto dispatch block if there isn't one already.
3196   CFGBlock *IBlock = cfg->getIndirectGotoBlock();
3197 
3198   if (!IBlock) {
3199     IBlock = createBlock(false);
3200     cfg->setIndirectGotoBlock(IBlock);
3201   }
3202 
3203   // IndirectGoto is a control-flow statement.  Thus we stop processing the
3204   // current block and create a new one.
3205   if (badCFG)
3206     return 0;
3207 
3208   Block = createBlock(false);
3209   Block->setTerminator(I);
3210   addSuccessor(Block, IBlock);
3211   return addStmt(I->getTarget());
3212 }
3213 
3214 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) {
3215   assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3216 
3217 tryAgain:
3218   if (!E) {
3219     badCFG = true;
3220     return NULL;
3221   }
3222   switch (E->getStmtClass()) {
3223     default:
3224       return VisitChildrenForTemporaryDtors(E);
3225 
3226     case Stmt::BinaryOperatorClass:
3227       return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E));
3228 
3229     case Stmt::CXXBindTemporaryExprClass:
3230       return VisitCXXBindTemporaryExprForTemporaryDtors(
3231           cast<CXXBindTemporaryExpr>(E), BindToTemporary);
3232 
3233     case Stmt::BinaryConditionalOperatorClass:
3234     case Stmt::ConditionalOperatorClass:
3235       return VisitConditionalOperatorForTemporaryDtors(
3236           cast<AbstractConditionalOperator>(E), BindToTemporary);
3237 
3238     case Stmt::ImplicitCastExprClass:
3239       // For implicit cast we want BindToTemporary to be passed further.
3240       E = cast<CastExpr>(E)->getSubExpr();
3241       goto tryAgain;
3242 
3243     case Stmt::ParenExprClass:
3244       E = cast<ParenExpr>(E)->getSubExpr();
3245       goto tryAgain;
3246 
3247     case Stmt::MaterializeTemporaryExprClass:
3248       E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr();
3249       goto tryAgain;
3250   }
3251 }
3252 
3253 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) {
3254   // When visiting children for destructors we want to visit them in reverse
3255   // order that they will appear in the CFG.  Because the CFG is built
3256   // bottom-up, this means we visit them in their natural order, which
3257   // reverses them in the CFG.
3258   CFGBlock *B = Block;
3259   for (Stmt::child_range I = E->children(); I; ++I) {
3260     if (Stmt *Child = *I)
3261       if (CFGBlock *R = VisitForTemporaryDtors(Child))
3262         B = R;
3263   }
3264   return B;
3265 }
3266 
3267 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) {
3268   if (E->isLogicalOp()) {
3269     // Destructors for temporaries in LHS expression should be called after
3270     // those for RHS expression. Even if this will unnecessarily create a block,
3271     // this block will be used at least by the full expression.
3272     autoCreateBlock();
3273     CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS());
3274     if (badCFG)
3275       return NULL;
3276 
3277     Succ = ConfluenceBlock;
3278     Block = NULL;
3279     CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3280 
3281     if (RHSBlock) {
3282       if (badCFG)
3283         return NULL;
3284 
3285       // If RHS expression did produce destructors we need to connect created
3286       // blocks to CFG in same manner as for binary operator itself.
3287       CFGBlock *LHSBlock = createBlock(false);
3288       LHSBlock->setTerminator(CFGTerminator(E, true));
3289 
3290       // For binary operator LHS block is before RHS in list of predecessors
3291       // of ConfluenceBlock.
3292       std::reverse(ConfluenceBlock->pred_begin(),
3293           ConfluenceBlock->pred_end());
3294 
3295       // See if this is a known constant.
3296       TryResult KnownVal = tryEvaluateBool(E->getLHS());
3297       if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr))
3298         KnownVal.negate();
3299 
3300       // Link LHSBlock with RHSBlock exactly the same way as for binary operator
3301       // itself.
3302       if (E->getOpcode() == BO_LOr) {
3303         addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3304         addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3305       } else {
3306         assert (E->getOpcode() == BO_LAnd);
3307         addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
3308         addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
3309       }
3310 
3311       Block = LHSBlock;
3312       return LHSBlock;
3313     }
3314 
3315     Block = ConfluenceBlock;
3316     return ConfluenceBlock;
3317   }
3318 
3319   if (E->isAssignmentOp()) {
3320     // For assignment operator (=) LHS expression is visited
3321     // before RHS expression. For destructors visit them in reverse order.
3322     CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3323     CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3324     return LHSBlock ? LHSBlock : RHSBlock;
3325   }
3326 
3327   // For any other binary operator RHS expression is visited before
3328   // LHS expression (order of children). For destructors visit them in reverse
3329   // order.
3330   CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS());
3331   CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS());
3332   return RHSBlock ? RHSBlock : LHSBlock;
3333 }
3334 
3335 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
3336     CXXBindTemporaryExpr *E, bool BindToTemporary) {
3337   // First add destructors for temporaries in subexpression.
3338   CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr());
3339   if (!BindToTemporary) {
3340     // If lifetime of temporary is not prolonged (by assigning to constant
3341     // reference) add destructor for it.
3342 
3343     // If the destructor is marked as a no-return destructor, we need to create
3344     // a new block for the destructor which does not have as a successor
3345     // anything built thus far. Control won't flow out of this block.
3346     const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
3347     if (Dtor->isNoReturn())
3348       Block = createNoReturnBlock();
3349     else
3350       autoCreateBlock();
3351 
3352     appendTemporaryDtor(Block, E);
3353     B = Block;
3354   }
3355   return B;
3356 }
3357 
3358 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
3359     AbstractConditionalOperator *E, bool BindToTemporary) {
3360   // First add destructors for condition expression.  Even if this will
3361   // unnecessarily create a block, this block will be used at least by the full
3362   // expression.
3363   autoCreateBlock();
3364   CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond());
3365   if (badCFG)
3366     return NULL;
3367   if (BinaryConditionalOperator *BCO
3368         = dyn_cast<BinaryConditionalOperator>(E)) {
3369     ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon());
3370     if (badCFG)
3371       return NULL;
3372   }
3373 
3374   // Try to add block with destructors for LHS expression.
3375   CFGBlock *LHSBlock = NULL;
3376   Succ = ConfluenceBlock;
3377   Block = NULL;
3378   LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary);
3379   if (badCFG)
3380     return NULL;
3381 
3382   // Try to add block with destructors for RHS expression;
3383   Succ = ConfluenceBlock;
3384   Block = NULL;
3385   CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(),
3386                                               BindToTemporary);
3387   if (badCFG)
3388     return NULL;
3389 
3390   if (!RHSBlock && !LHSBlock) {
3391     // If neither LHS nor RHS expression had temporaries to destroy don't create
3392     // more blocks.
3393     Block = ConfluenceBlock;
3394     return Block;
3395   }
3396 
3397   Block = createBlock(false);
3398   Block->setTerminator(CFGTerminator(E, true));
3399 
3400   // See if this is a known constant.
3401   const TryResult &KnownVal = tryEvaluateBool(E->getCond());
3402 
3403   if (LHSBlock) {
3404     addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
3405   } else if (KnownVal.isFalse()) {
3406     addSuccessor(Block, NULL);
3407   } else {
3408     addSuccessor(Block, ConfluenceBlock);
3409     std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end());
3410   }
3411 
3412   if (!RHSBlock)
3413     RHSBlock = ConfluenceBlock;
3414   addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
3415 
3416   return Block;
3417 }
3418 
3419 } // end anonymous namespace
3420 
3421 /// createBlock - Constructs and adds a new CFGBlock to the CFG.  The block has
3422 ///  no successors or predecessors.  If this is the first block created in the
3423 ///  CFG, it is automatically set to be the Entry and Exit of the CFG.
3424 CFGBlock *CFG::createBlock() {
3425   bool first_block = begin() == end();
3426 
3427   // Create the block.
3428   CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
3429   new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
3430   Blocks.push_back(Mem, BlkBVC);
3431 
3432   // If this is the first block, set it as the Entry and Exit.
3433   if (first_block)
3434     Entry = Exit = &back();
3435 
3436   // Return the block.
3437   return &back();
3438 }
3439 
3440 /// buildCFG - Constructs a CFG from an AST.  Ownership of the returned
3441 ///  CFG is returned to the caller.
3442 CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C,
3443     const BuildOptions &BO) {
3444   CFGBuilder Builder(C, BO);
3445   return Builder.buildCFG(D, Statement);
3446 }
3447 
3448 const CXXDestructorDecl *
3449 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
3450   switch (getKind()) {
3451     case CFGElement::Statement:
3452     case CFGElement::Initializer:
3453     case CFGElement::NewAllocator:
3454       llvm_unreachable("getDestructorDecl should only be used with "
3455                        "ImplicitDtors");
3456     case CFGElement::AutomaticObjectDtor: {
3457       const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
3458       QualType ty = var->getType();
3459       ty = ty.getNonReferenceType();
3460       while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
3461         ty = arrayType->getElementType();
3462       }
3463       const RecordType *recordType = ty->getAs<RecordType>();
3464       const CXXRecordDecl *classDecl =
3465       cast<CXXRecordDecl>(recordType->getDecl());
3466       return classDecl->getDestructor();
3467     }
3468     case CFGElement::DeleteDtor: {
3469       const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3470       QualType DTy = DE->getDestroyedType();
3471       DTy = DTy.getNonReferenceType();
3472       const CXXRecordDecl *classDecl =
3473           astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3474       return classDecl->getDestructor();
3475     }
3476     case CFGElement::TemporaryDtor: {
3477       const CXXBindTemporaryExpr *bindExpr =
3478         castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
3479       const CXXTemporary *temp = bindExpr->getTemporary();
3480       return temp->getDestructor();
3481     }
3482     case CFGElement::BaseDtor:
3483     case CFGElement::MemberDtor:
3484 
3485       // Not yet supported.
3486       return 0;
3487   }
3488   llvm_unreachable("getKind() returned bogus value");
3489 }
3490 
3491 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
3492   if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3493     return DD->isNoReturn();
3494   return false;
3495 }
3496 
3497 //===----------------------------------------------------------------------===//
3498 // Filtered walking of the CFG.
3499 //===----------------------------------------------------------------------===//
3500 
3501 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
3502         const CFGBlock *From, const CFGBlock *To) {
3503 
3504   if (To && F.IgnoreDefaultsWithCoveredEnums) {
3505     // If the 'To' has no label or is labeled but the label isn't a
3506     // CaseStmt then filter this edge.
3507     if (const SwitchStmt *S =
3508         dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
3509       if (S->isAllEnumCasesCovered()) {
3510         const Stmt *L = To->getLabel();
3511         if (!L || !isa<CaseStmt>(L))
3512           return true;
3513       }
3514     }
3515   }
3516 
3517   return false;
3518 }
3519 
3520 //===----------------------------------------------------------------------===//
3521 // CFG pretty printing
3522 //===----------------------------------------------------------------------===//
3523 
3524 namespace {
3525 
3526 class StmtPrinterHelper : public PrinterHelper  {
3527   typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3528   typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
3529   StmtMapTy StmtMap;
3530   DeclMapTy DeclMap;
3531   signed currentBlock;
3532   unsigned currStmt;
3533   const LangOptions &LangOpts;
3534 public:
3535 
3536   StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
3537     : currentBlock(0), currStmt(0), LangOpts(LO)
3538   {
3539     for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3540       unsigned j = 1;
3541       for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
3542            BI != BEnd; ++BI, ++j ) {
3543         if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3544           const Stmt *stmt= SE->getStmt();
3545           std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
3546           StmtMap[stmt] = P;
3547 
3548           switch (stmt->getStmtClass()) {
3549             case Stmt::DeclStmtClass:
3550                 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3551                 break;
3552             case Stmt::IfStmtClass: {
3553               const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3554               if (var)
3555                 DeclMap[var] = P;
3556               break;
3557             }
3558             case Stmt::ForStmtClass: {
3559               const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3560               if (var)
3561                 DeclMap[var] = P;
3562               break;
3563             }
3564             case Stmt::WhileStmtClass: {
3565               const VarDecl *var =
3566                 cast<WhileStmt>(stmt)->getConditionVariable();
3567               if (var)
3568                 DeclMap[var] = P;
3569               break;
3570             }
3571             case Stmt::SwitchStmtClass: {
3572               const VarDecl *var =
3573                 cast<SwitchStmt>(stmt)->getConditionVariable();
3574               if (var)
3575                 DeclMap[var] = P;
3576               break;
3577             }
3578             case Stmt::CXXCatchStmtClass: {
3579               const VarDecl *var =
3580                 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3581               if (var)
3582                 DeclMap[var] = P;
3583               break;
3584             }
3585             default:
3586               break;
3587           }
3588         }
3589       }
3590     }
3591   }
3592 
3593 
3594   virtual ~StmtPrinterHelper() {}
3595 
3596   const LangOptions &getLangOpts() const { return LangOpts; }
3597   void setBlockID(signed i) { currentBlock = i; }
3598   void setStmtID(unsigned i) { currStmt = i; }
3599 
3600   virtual bool handledStmt(Stmt *S, raw_ostream &OS) {
3601     StmtMapTy::iterator I = StmtMap.find(S);
3602 
3603     if (I == StmtMap.end())
3604       return false;
3605 
3606     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3607                           && I->second.second == currStmt) {
3608       return false;
3609     }
3610 
3611     OS << "[B" << I->second.first << "." << I->second.second << "]";
3612     return true;
3613   }
3614 
3615   bool handleDecl(const Decl *D, raw_ostream &OS) {
3616     DeclMapTy::iterator I = DeclMap.find(D);
3617 
3618     if (I == DeclMap.end())
3619       return false;
3620 
3621     if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
3622                           && I->second.second == currStmt) {
3623       return false;
3624     }
3625 
3626     OS << "[B" << I->second.first << "." << I->second.second << "]";
3627     return true;
3628   }
3629 };
3630 } // end anonymous namespace
3631 
3632 
3633 namespace {
3634 class CFGBlockTerminatorPrint
3635   : public StmtVisitor<CFGBlockTerminatorPrint,void> {
3636 
3637   raw_ostream &OS;
3638   StmtPrinterHelper* Helper;
3639   PrintingPolicy Policy;
3640 public:
3641   CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
3642                           const PrintingPolicy &Policy)
3643     : OS(os), Helper(helper), Policy(Policy) {
3644     this->Policy.IncludeNewlines = false;
3645   }
3646 
3647   void VisitIfStmt(IfStmt *I) {
3648     OS << "if ";
3649     I->getCond()->printPretty(OS,Helper,Policy);
3650   }
3651 
3652   // Default case.
3653   void VisitStmt(Stmt *Terminator) {
3654     Terminator->printPretty(OS, Helper, Policy);
3655   }
3656 
3657   void VisitDeclStmt(DeclStmt *DS) {
3658     VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
3659     OS << "static init " << VD->getName();
3660   }
3661 
3662   void VisitForStmt(ForStmt *F) {
3663     OS << "for (" ;
3664     if (F->getInit())
3665       OS << "...";
3666     OS << "; ";
3667     if (Stmt *C = F->getCond())
3668       C->printPretty(OS, Helper, Policy);
3669     OS << "; ";
3670     if (F->getInc())
3671       OS << "...";
3672     OS << ")";
3673   }
3674 
3675   void VisitWhileStmt(WhileStmt *W) {
3676     OS << "while " ;
3677     if (Stmt *C = W->getCond())
3678       C->printPretty(OS, Helper, Policy);
3679   }
3680 
3681   void VisitDoStmt(DoStmt *D) {
3682     OS << "do ... while ";
3683     if (Stmt *C = D->getCond())
3684       C->printPretty(OS, Helper, Policy);
3685   }
3686 
3687   void VisitSwitchStmt(SwitchStmt *Terminator) {
3688     OS << "switch ";
3689     Terminator->getCond()->printPretty(OS, Helper, Policy);
3690   }
3691 
3692   void VisitCXXTryStmt(CXXTryStmt *CS) {
3693     OS << "try ...";
3694   }
3695 
3696   void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
3697     C->getCond()->printPretty(OS, Helper, Policy);
3698     OS << " ? ... : ...";
3699   }
3700 
3701   void VisitChooseExpr(ChooseExpr *C) {
3702     OS << "__builtin_choose_expr( ";
3703     C->getCond()->printPretty(OS, Helper, Policy);
3704     OS << " )";
3705   }
3706 
3707   void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
3708     OS << "goto *";
3709     I->getTarget()->printPretty(OS, Helper, Policy);
3710   }
3711 
3712   void VisitBinaryOperator(BinaryOperator* B) {
3713     if (!B->isLogicalOp()) {
3714       VisitExpr(B);
3715       return;
3716     }
3717 
3718     B->getLHS()->printPretty(OS, Helper, Policy);
3719 
3720     switch (B->getOpcode()) {
3721       case BO_LOr:
3722         OS << " || ...";
3723         return;
3724       case BO_LAnd:
3725         OS << " && ...";
3726         return;
3727       default:
3728         llvm_unreachable("Invalid logical operator.");
3729     }
3730   }
3731 
3732   void VisitExpr(Expr *E) {
3733     E->printPretty(OS, Helper, Policy);
3734   }
3735 };
3736 } // end anonymous namespace
3737 
3738 static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
3739                        const CFGElement &E) {
3740   if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
3741     const Stmt *S = CS->getStmt();
3742 
3743     // special printing for statement-expressions.
3744     if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
3745       const CompoundStmt *Sub = SE->getSubStmt();
3746 
3747       if (Sub->children()) {
3748         OS << "({ ... ; ";
3749         Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
3750         OS << " })\n";
3751         return;
3752       }
3753     }
3754     // special printing for comma expressions.
3755     if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
3756       if (B->getOpcode() == BO_Comma) {
3757         OS << "... , ";
3758         Helper.handledStmt(B->getRHS(),OS);
3759         OS << '\n';
3760         return;
3761       }
3762     }
3763     S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3764 
3765     if (isa<CXXOperatorCallExpr>(S)) {
3766       OS << " (OperatorCall)";
3767     }
3768     else if (isa<CXXBindTemporaryExpr>(S)) {
3769       OS << " (BindTemporary)";
3770     }
3771     else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
3772       OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
3773     }
3774     else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
3775       OS << " (" << CE->getStmtClassName() << ", "
3776          << CE->getCastKindName()
3777          << ", " << CE->getType().getAsString()
3778          << ")";
3779     }
3780 
3781     // Expressions need a newline.
3782     if (isa<Expr>(S))
3783       OS << '\n';
3784 
3785   } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
3786     const CXXCtorInitializer *I = IE->getInitializer();
3787     if (I->isBaseInitializer())
3788       OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
3789     else if (I->isDelegatingInitializer())
3790       OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
3791     else OS << I->getAnyMember()->getName();
3792 
3793     OS << "(";
3794     if (Expr *IE = I->getInit())
3795       IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
3796     OS << ")";
3797 
3798     if (I->isBaseInitializer())
3799       OS << " (Base initializer)\n";
3800     else if (I->isDelegatingInitializer())
3801       OS << " (Delegating initializer)\n";
3802     else OS << " (Member initializer)\n";
3803 
3804   } else if (Optional<CFGAutomaticObjDtor> DE =
3805                  E.getAs<CFGAutomaticObjDtor>()) {
3806     const VarDecl *VD = DE->getVarDecl();
3807     Helper.handleDecl(VD, OS);
3808 
3809     const Type* T = VD->getType().getTypePtr();
3810     if (const ReferenceType* RT = T->getAs<ReferenceType>())
3811       T = RT->getPointeeType().getTypePtr();
3812     T = T->getBaseElementTypeUnsafe();
3813 
3814     OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
3815     OS << " (Implicit destructor)\n";
3816 
3817   } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
3818     OS << "CFGNewAllocator(";
3819     if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
3820       AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
3821     OS << ")\n";
3822   } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
3823     const CXXRecordDecl *RD = DE->getCXXRecordDecl();
3824     if (!RD)
3825       return;
3826     CXXDeleteExpr *DelExpr =
3827         const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
3828     Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
3829     OS << "->~" << RD->getName().str() << "()";
3830     OS << " (Implicit destructor)\n";
3831   } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
3832     const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
3833     OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
3834     OS << " (Base object destructor)\n";
3835 
3836   } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
3837     const FieldDecl *FD = ME->getFieldDecl();
3838     const Type *T = FD->getType()->getBaseElementTypeUnsafe();
3839     OS << "this->" << FD->getName();
3840     OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
3841     OS << " (Member object destructor)\n";
3842 
3843   } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
3844     const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
3845     OS << "~";
3846     BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
3847     OS << "() (Temporary object destructor)\n";
3848   }
3849 }
3850 
3851 static void print_block(raw_ostream &OS, const CFG* cfg,
3852                         const CFGBlock &B,
3853                         StmtPrinterHelper &Helper, bool print_edges,
3854                         bool ShowColors) {
3855 
3856   Helper.setBlockID(B.getBlockID());
3857 
3858   // Print the header.
3859   if (ShowColors)
3860     OS.changeColor(raw_ostream::YELLOW, true);
3861 
3862   OS << "\n [B" << B.getBlockID();
3863 
3864   if (&B == &cfg->getEntry())
3865     OS << " (ENTRY)]\n";
3866   else if (&B == &cfg->getExit())
3867     OS << " (EXIT)]\n";
3868   else if (&B == cfg->getIndirectGotoBlock())
3869     OS << " (INDIRECT GOTO DISPATCH)]\n";
3870   else
3871     OS << "]\n";
3872 
3873   if (ShowColors)
3874     OS.resetColor();
3875 
3876   // Print the label of this block.
3877   if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
3878 
3879     if (print_edges)
3880       OS << "  ";
3881 
3882     if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
3883       OS << L->getName();
3884     else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
3885       OS << "case ";
3886       C->getLHS()->printPretty(OS, &Helper,
3887                                PrintingPolicy(Helper.getLangOpts()));
3888       if (C->getRHS()) {
3889         OS << " ... ";
3890         C->getRHS()->printPretty(OS, &Helper,
3891                                  PrintingPolicy(Helper.getLangOpts()));
3892       }
3893     } else if (isa<DefaultStmt>(Label))
3894       OS << "default";
3895     else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
3896       OS << "catch (";
3897       if (CS->getExceptionDecl())
3898         CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
3899                                       0);
3900       else
3901         OS << "...";
3902       OS << ")";
3903 
3904     } else
3905       llvm_unreachable("Invalid label statement in CFGBlock.");
3906 
3907     OS << ":\n";
3908   }
3909 
3910   // Iterate through the statements in the block and print them.
3911   unsigned j = 1;
3912 
3913   for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
3914        I != E ; ++I, ++j ) {
3915 
3916     // Print the statement # in the basic block and the statement itself.
3917     if (print_edges)
3918       OS << " ";
3919 
3920     OS << llvm::format("%3d", j) << ": ";
3921 
3922     Helper.setStmtID(j);
3923 
3924     print_elem(OS, Helper, *I);
3925   }
3926 
3927   // Print the terminator of this block.
3928   if (B.getTerminator()) {
3929     if (ShowColors)
3930       OS.changeColor(raw_ostream::GREEN);
3931 
3932     OS << "   T: ";
3933 
3934     Helper.setBlockID(-1);
3935 
3936     PrintingPolicy PP(Helper.getLangOpts());
3937     CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
3938     TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt()));
3939     OS << '\n';
3940 
3941     if (ShowColors)
3942       OS.resetColor();
3943   }
3944 
3945   if (print_edges) {
3946     // Print the predecessors of this block.
3947     if (!B.pred_empty()) {
3948       const raw_ostream::Colors Color = raw_ostream::BLUE;
3949       if (ShowColors)
3950         OS.changeColor(Color);
3951       OS << "   Preds " ;
3952       if (ShowColors)
3953         OS.resetColor();
3954       OS << '(' << B.pred_size() << "):";
3955       unsigned i = 0;
3956 
3957       if (ShowColors)
3958         OS.changeColor(Color);
3959 
3960       for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
3961            I != E; ++I, ++i) {
3962 
3963         if (i % 10 == 8)
3964           OS << "\n     ";
3965 
3966         OS << " B" << (*I)->getBlockID();
3967       }
3968 
3969       if (ShowColors)
3970         OS.resetColor();
3971 
3972       OS << '\n';
3973     }
3974 
3975     // Print the successors of this block.
3976     if (!B.succ_empty()) {
3977       const raw_ostream::Colors Color = raw_ostream::MAGENTA;
3978       if (ShowColors)
3979         OS.changeColor(Color);
3980       OS << "   Succs ";
3981       if (ShowColors)
3982         OS.resetColor();
3983       OS << '(' << B.succ_size() << "):";
3984       unsigned i = 0;
3985 
3986       if (ShowColors)
3987         OS.changeColor(Color);
3988 
3989       for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
3990            I != E; ++I, ++i) {
3991 
3992         if (i % 10 == 8)
3993           OS << "\n    ";
3994 
3995         if (*I)
3996           OS << " B" << (*I)->getBlockID();
3997         else
3998           OS  << " NULL";
3999       }
4000 
4001       if (ShowColors)
4002         OS.resetColor();
4003       OS << '\n';
4004     }
4005   }
4006 }
4007 
4008 
4009 /// dump - A simple pretty printer of a CFG that outputs to stderr.
4010 void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4011   print(llvm::errs(), LO, ShowColors);
4012 }
4013 
4014 /// print - A simple pretty printer of a CFG that outputs to an ostream.
4015 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
4016   StmtPrinterHelper Helper(this, LO);
4017 
4018   // Print the entry block.
4019   print_block(OS, this, getEntry(), Helper, true, ShowColors);
4020 
4021   // Iterate through the CFGBlocks and print them one by one.
4022   for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4023     // Skip the entry block, because we already printed it.
4024     if (&(**I) == &getEntry() || &(**I) == &getExit())
4025       continue;
4026 
4027     print_block(OS, this, **I, Helper, true, ShowColors);
4028   }
4029 
4030   // Print the exit block.
4031   print_block(OS, this, getExit(), Helper, true, ShowColors);
4032   OS << '\n';
4033   OS.flush();
4034 }
4035 
4036 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
4037 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4038                     bool ShowColors) const {
4039   print(llvm::errs(), cfg, LO, ShowColors);
4040 }
4041 
4042 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4043 ///   Generally this will only be called from CFG::print.
4044 void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
4045                      const LangOptions &LO, bool ShowColors) const {
4046   StmtPrinterHelper Helper(cfg, LO);
4047   print_block(OS, cfg, *this, Helper, true, ShowColors);
4048   OS << '\n';
4049 }
4050 
4051 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
4052 void CFGBlock::printTerminator(raw_ostream &OS,
4053                                const LangOptions &LO) const {
4054   CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
4055   TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt()));
4056 }
4057 
4058 Stmt *CFGBlock::getTerminatorCondition() {
4059   Stmt *Terminator = this->Terminator;
4060   if (!Terminator)
4061     return NULL;
4062 
4063   Expr *E = NULL;
4064 
4065   switch (Terminator->getStmtClass()) {
4066     default:
4067       break;
4068 
4069     case Stmt::CXXForRangeStmtClass:
4070       E = cast<CXXForRangeStmt>(Terminator)->getCond();
4071       break;
4072 
4073     case Stmt::ForStmtClass:
4074       E = cast<ForStmt>(Terminator)->getCond();
4075       break;
4076 
4077     case Stmt::WhileStmtClass:
4078       E = cast<WhileStmt>(Terminator)->getCond();
4079       break;
4080 
4081     case Stmt::DoStmtClass:
4082       E = cast<DoStmt>(Terminator)->getCond();
4083       break;
4084 
4085     case Stmt::IfStmtClass:
4086       E = cast<IfStmt>(Terminator)->getCond();
4087       break;
4088 
4089     case Stmt::ChooseExprClass:
4090       E = cast<ChooseExpr>(Terminator)->getCond();
4091       break;
4092 
4093     case Stmt::IndirectGotoStmtClass:
4094       E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4095       break;
4096 
4097     case Stmt::SwitchStmtClass:
4098       E = cast<SwitchStmt>(Terminator)->getCond();
4099       break;
4100 
4101     case Stmt::BinaryConditionalOperatorClass:
4102       E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4103       break;
4104 
4105     case Stmt::ConditionalOperatorClass:
4106       E = cast<ConditionalOperator>(Terminator)->getCond();
4107       break;
4108 
4109     case Stmt::BinaryOperatorClass: // '&&' and '||'
4110       E = cast<BinaryOperator>(Terminator)->getLHS();
4111       break;
4112 
4113     case Stmt::ObjCForCollectionStmtClass:
4114       return Terminator;
4115   }
4116 
4117   return E ? E->IgnoreParens() : NULL;
4118 }
4119 
4120 //===----------------------------------------------------------------------===//
4121 // CFG Graphviz Visualization
4122 //===----------------------------------------------------------------------===//
4123 
4124 
4125 #ifndef NDEBUG
4126 static StmtPrinterHelper* GraphHelper;
4127 #endif
4128 
4129 void CFG::viewCFG(const LangOptions &LO) const {
4130 #ifndef NDEBUG
4131   StmtPrinterHelper H(this, LO);
4132   GraphHelper = &H;
4133   llvm::ViewGraph(this,"CFG");
4134   GraphHelper = NULL;
4135 #endif
4136 }
4137 
4138 namespace llvm {
4139 template<>
4140 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
4141 
4142   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4143 
4144   static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
4145 
4146 #ifndef NDEBUG
4147     std::string OutSStr;
4148     llvm::raw_string_ostream Out(OutSStr);
4149     print_block(Out,Graph, *Node, *GraphHelper, false, false);
4150     std::string& OutStr = Out.str();
4151 
4152     if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4153 
4154     // Process string output to make it nicer...
4155     for (unsigned i = 0; i != OutStr.length(); ++i)
4156       if (OutStr[i] == '\n') {                            // Left justify
4157         OutStr[i] = '\\';
4158         OutStr.insert(OutStr.begin()+i+1, 'l');
4159       }
4160 
4161     return OutStr;
4162 #else
4163     return "";
4164 #endif
4165   }
4166 };
4167 } // end namespace llvm
4168