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