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