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