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