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