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