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