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