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