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