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