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