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