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