blob: fa55f9db8aca78889ef3bbb5415f5e6aca6ee1e3 [file] [log] [blame]
Eugene Zelenko38c70522017-12-07 21:55:09 +00001//===- CFG.cpp - Classes for representing and building CFGs ---------------===//
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00007//
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
Ted Kremenek6796fbd2009-07-16 18:13:04 +000015#include "clang/Analysis/CFG.h"
Benjamin Kramer1ea8e092012-07-04 17:04:04 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/DeclCXX.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000021#include "clang/AST/DeclGroup.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/OperationKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/PrettyPrinter.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/StmtVisitor.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000030#include "clang/AST/Type.h"
31#include "clang/Analysis/Support/BumpVector.h"
Jordan Rose5374c072013-08-19 16:27:28 +000032#include "clang/Basic/Builtins.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000033#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/Specifiers.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/APSInt.h"
40#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000041#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000042#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SetVector.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000045#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000046#include "llvm/ADT/SmallVector.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000047#include "llvm/Support/Allocator.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000048#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/DOTGraphTraits.h"
51#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000052#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000053#include "llvm/Support/GraphWriter.h"
54#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000055#include "llvm/Support/raw_ostream.h"
56#include <cassert>
57#include <memory>
58#include <string>
59#include <tuple>
60#include <utility>
61#include <vector>
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000062
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000063using namespace clang;
64
Ted Kremenek5ef32db2011-08-12 23:37:29 +000065static SourceLocation GetEndLoc(Decl *D) {
66 if (VarDecl *VD = dyn_cast<VarDecl>(D))
67 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000068 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000069 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000070}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000071
George Burgess IVced56e62015-10-01 18:47:52 +000072/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
73/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
Eugene Zelenko38c70522017-12-07 21:55:09 +000074static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
George Burgess IVced56e62015-10-01 18:47:52 +000075 E = E->IgnoreParens();
76 if (isa<IntegerLiteral>(E))
77 return E;
78 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
79 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
80 return nullptr;
81}
82
83/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
84/// an integer literal or an enum constant.
85///
86/// If this fails, at least one of the returned DeclRefExpr or Expr will be
87/// null.
88static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
89tryNormalizeBinaryOperator(const BinaryOperator *B) {
90 BinaryOperatorKind Op = B->getOpcode();
91
92 const Expr *MaybeDecl = B->getLHS();
93 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
94 // Expr looked like `0 == Foo` instead of `Foo == 0`
95 if (Constant == nullptr) {
96 // Flip the operator
97 if (Op == BO_GT)
98 Op = BO_LT;
99 else if (Op == BO_GE)
100 Op = BO_LE;
101 else if (Op == BO_LT)
102 Op = BO_GT;
103 else if (Op == BO_LE)
104 Op = BO_GE;
105
106 MaybeDecl = B->getRHS();
107 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
108 }
109
110 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
111 return std::make_tuple(D, Op, Constant);
112}
113
114/// For an expression `x == Foo && x == Bar`, this determines whether the
115/// `Foo` and `Bar` are either of the same enumeration type, or both integer
116/// literals.
117///
118/// It's an error to pass this arguments that are not either IntegerLiterals
119/// or DeclRefExprs (that have decls of type EnumConstantDecl)
120static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
121 // User intent isn't clear if they're mixing int literals with enum
122 // constants.
123 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
124 return false;
125
126 // Integer literal comparisons, regardless of literal type, are acceptable.
127 if (isa<IntegerLiteral>(E1))
128 return true;
129
130 // IntegerLiterals are handled above and only EnumConstantDecls are expected
131 // beyond this point
132 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
133 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
134 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
135
136 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
137 const DeclContext *DC1 = Decl1->getDeclContext();
138 const DeclContext *DC2 = Decl2->getDeclContext();
139
140 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
141 return DC1 == DC2;
142}
143
Eugene Zelenko38c70522017-12-07 21:55:09 +0000144namespace {
145
Ted Kremenek7c58d352011-03-10 01:14:11 +0000146class CFGBuilder;
147
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000148/// The CFG builder uses a recursive algorithm to build the CFG. When
149/// we process an expression, sometimes we know that we must add the
150/// subexpressions as block-level expressions. For example:
151///
152/// exp1 || exp2
153///
154/// When processing the '||' expression, we know that exp1 and exp2
155/// need to be added as block-level expressions, even though they
156/// might not normally need to be. AddStmtChoice records this
157/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
158/// the builder has an option not to add a subexpression as a
159/// block-level expression.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000160class AddStmtChoice {
161public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000162 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000163
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000164 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000165
Ted Kremenek7c58d352011-03-10 01:14:11 +0000166 bool alwaysAdd(CFGBuilder &builder,
167 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000168
169 /// Return a copy of this object, except with the 'always-add' bit
170 /// set as specified.
171 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000172 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000173 }
174
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000175private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000176 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000177};
Mike Stump31feda52009-07-17 01:31:16 +0000178
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000179/// LocalScope - Node in tree of local scopes created for C++ implicit
180/// destructor calls generation. It contains list of automatic variables
181/// declared in the scope and link to position in previous scope this scope
182/// began in.
183///
184/// The process of creating local scopes is as follows:
185/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
186/// - Before processing statements in scope (e.g. CompoundStmt) create
187/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
188/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000189/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000190/// at this VarDecl,
191/// - For every normal (without jump) end of scope add to CFGBlock destructors
192/// for objects in the current scope,
193/// - For every jump add to CFGBlock destructors for objects
194/// between CFGBuilder::ScopePos and local scope position saved for jump
195/// target. Thanks to C++ restrictions on goto jumps we can be sure that
196/// jump target position will be on the path to root from CFGBuilder::ScopePos
197/// (adding any variable that doesn't need constructor to be called to
198/// LocalScope can break this assumption),
199///
200class LocalScope {
201public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000202 friend class const_iterator;
203
204 using AutomaticVarsTy = BumpVector<VarDecl *>;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000205
206 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000207 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000208 class const_iterator {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000209 const LocalScope* Scope = nullptr;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000210
211 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
212 /// Invalid iterator (with null Scope) has VarIter equal to 0.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000213 unsigned VarIter = 0;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000214
215 public:
216 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
217 /// Incrementing invalid iterator is allowed and will result in invalid
218 /// iterator.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000219 const_iterator() = default;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000220
221 /// Create valid iterator. In case when S.Prev is an invalid iterator and
222 /// I is equal to 0, this will create invalid iterator.
223 const_iterator(const LocalScope& S, unsigned I)
224 : Scope(&S), VarIter(I) {
225 // Iterator to "end" of scope is not allowed. Handle it by going up
226 // in scopes tree possibly up to invalid iterator in the root.
227 if (VarIter == 0 && Scope)
228 *this = Scope->Prev;
229 }
230
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000231 VarDecl *const* operator->() const {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000232 assert(Scope && "Dereferencing invalid iterator is not allowed");
233 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000234 return &Scope->Vars[VarIter - 1];
235 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000236 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000237 return *this->operator->();
238 }
239
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000240 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000241 if (!Scope)
242 return *this;
243
Eugene Zelenko38c70522017-12-07 21:55:09 +0000244 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000245 --VarIter;
246 if (VarIter == 0)
247 *this = Scope->Prev;
248 return *this;
249 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000250 const_iterator operator++(int) {
251 const_iterator P = *this;
252 ++*this;
253 return P;
254 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000255
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000256 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000257 return Scope == rhs.Scope && VarIter == rhs.VarIter;
258 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000259 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000260 return !(*this == rhs);
261 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000262
Aaron Ballman67347662015-02-15 22:00:28 +0000263 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000264 return *this != const_iterator();
265 }
266
267 int distance(const_iterator L);
Matthias Gehre351c2182017-07-12 07:04:19 +0000268 const_iterator shared_parent(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000269 };
270
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000271private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000272 BumpVectorContext ctx;
273
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000274 /// Automatic variables in order of declaration.
275 AutomaticVarsTy Vars;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000276
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000277 /// Iterator to variable in previous scope that was declared just before
278 /// begin of this scope.
279 const_iterator Prev;
280
281public:
282 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000283 LocalScope(BumpVectorContext ctx, const_iterator P)
284 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000285
286 /// Begin of scope in direction of CFG building (backwards).
287 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000288
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000289 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000290 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000291 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000292};
293
Eugene Zelenko38c70522017-12-07 21:55:09 +0000294} // namespace
295
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000296/// distance - Calculates distance from this to L. L must be reachable from this
297/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
298/// number of scopes between this and L.
299int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
300 int D = 0;
301 const_iterator F = *this;
302 while (F.Scope != L.Scope) {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000303 assert(F != const_iterator() &&
304 "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000305 D += F.VarIter;
306 F = F.Scope->Prev;
307 }
308 D += F.VarIter - L.VarIter;
309 return D;
310}
311
Matthias Gehre351c2182017-07-12 07:04:19 +0000312/// Calculates the closest parent of this iterator
313/// that is in a scope reachable through the parents of L.
314/// I.e. when using 'goto' from this to L, the lifetime of all variables
315/// between this and shared_parent(L) end.
316LocalScope::const_iterator
317LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
318 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
319 while (true) {
320 ScopesOfL.insert(L.Scope);
321 if (L == const_iterator())
322 break;
323 L = L.Scope->Prev;
324 }
325
326 const_iterator F = *this;
327 while (true) {
328 if (ScopesOfL.count(F.Scope))
329 return F;
330 assert(F != const_iterator() &&
331 "L iterator is not reachable from F iterator.");
332 F = F.Scope->Prev;
333 }
334}
335
Eugene Zelenko38c70522017-12-07 21:55:09 +0000336namespace {
337
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000338/// Structure for specifying position in CFG during its build process. It
339/// consists of CFGBlock that specifies position in CFG and
340/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000341struct BlockScopePosPair {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000342 CFGBlock *block = nullptr;
343 LocalScope::const_iterator scopePosition;
344
345 BlockScopePosPair() = default;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000346 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000347 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000348};
349
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000350/// TryResult - a class representing a variant over the values
351/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
352/// and is used by the CFGBuilder to decide if a branch condition
353/// can be decided up front during CFG construction.
354class TryResult {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000355 int X = -1;
356
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000357public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000358 TryResult() = default;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000359 TryResult(bool b) : X(b ? 1 : 0) {}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000360
361 bool isTrue() const { return X == 1; }
362 bool isFalse() const { return X == 0; }
363 bool isKnown() const { return X >= 0; }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000364
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000365 void negate() {
366 assert(isKnown());
367 X ^= 0x1;
368 }
369};
370
Eugene Zelenko38c70522017-12-07 21:55:09 +0000371} // namespace
372
373static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000374 if (!R1.isKnown() || !R2.isKnown())
375 return TryResult();
376 return TryResult(R1.isTrue() && R2.isTrue());
377}
378
Eugene Zelenko38c70522017-12-07 21:55:09 +0000379namespace {
380
Ted Kremenek8ae67872013-02-05 22:00:19 +0000381class reverse_children {
382 llvm::SmallVector<Stmt *, 12> childrenBuf;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000383 ArrayRef<Stmt *> children;
384
Ted Kremenek8ae67872013-02-05 22:00:19 +0000385public:
386 reverse_children(Stmt *S);
387
Eugene Zelenko38c70522017-12-07 21:55:09 +0000388 using iterator = ArrayRef<Stmt *>::reverse_iterator;
389
Ted Kremenek8ae67872013-02-05 22:00:19 +0000390 iterator begin() const { return children.rbegin(); }
391 iterator end() const { return children.rend(); }
392};
393
Eugene Zelenko38c70522017-12-07 21:55:09 +0000394} // namespace
Ted Kremenek8ae67872013-02-05 22:00:19 +0000395
396reverse_children::reverse_children(Stmt *S) {
397 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
398 children = CE->getRawSubExprs();
399 return;
400 }
401 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000402 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000403 case Stmt::InitListExprClass: {
404 InitListExpr *IE = cast<InitListExpr>(S);
405 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
406 IE->getNumInits());
407 return;
408 }
409 default:
410 break;
411 }
412
413 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000414 for (Stmt *SubStmt : S->children())
415 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000416
417 // This needs to be done *after* childrenBuf has been populated.
418 children = childrenBuf;
419}
420
Eugene Zelenko38c70522017-12-07 21:55:09 +0000421namespace {
422
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000423/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000424/// The builder is stateful: an instance of the builder should be used to only
425/// construct a single CFG.
426///
427/// Example usage:
428///
429/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000430/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000431///
Mike Stump31feda52009-07-17 01:31:16 +0000432/// CFG construction is done via a recursive walk of an AST. We actually parse
433/// the AST in reverse order so that the successor of a basic block is
434/// constructed prior to its predecessor. This allows us to nicely capture
435/// implicit fall-throughs without extra basic blocks.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000436class CFGBuilder {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000437 using JumpTarget = BlockScopePosPair;
438 using JumpSource = BlockScopePosPair;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000439
Mike Stump0d76d072009-07-20 23:24:15 +0000440 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000441 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000442
Eugene Zelenko38c70522017-12-07 21:55:09 +0000443 // Current block.
444 CFGBlock *Block = nullptr;
445
446 // Block after the current block.
447 CFGBlock *Succ = nullptr;
448
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000449 JumpTarget ContinueJumpTarget;
450 JumpTarget BreakJumpTarget;
Nico Weber699670e2017-08-23 15:33:16 +0000451 JumpTarget SEHLeaveJumpTarget;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000452 CFGBlock *SwitchTerminatedBlock = nullptr;
453 CFGBlock *DefaultCaseBlock = nullptr;
Nico Weber699670e2017-08-23 15:33:16 +0000454
455 // This can point either to a try or a __try block. The frontend forbids
456 // mixing both kinds in one function, so having one for both is enough.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000457 CFGBlock *TryTerminatedBlock = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000458
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000459 // Current position in local scope.
460 LocalScope::const_iterator ScopePos;
461
462 // LabelMap records the mapping from Label expressions to their jump targets.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000463 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000464 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000465
466 // A list of blocks that end with a "goto" that must be backpatched to their
467 // resolved targets upon completion of CFG construction.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000468 using BackpatchBlocksTy = std::vector<JumpSource>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000469 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000470
Ted Kremenekeda180e22007-08-28 19:26:49 +0000471 // A list of labels whose address has been taken (for indirect gotos).
Eugene Zelenko38c70522017-12-07 21:55:09 +0000472 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000473 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000474
Artem Dergachev41ffb302018-02-08 22:58:15 +0000475 // Information about the currently visited C++ object construction site.
476 // This is set in the construction trigger and read when the constructor
477 // itself is being visited.
478 ConstructionContext CurrentConstructionContext = {};
479
Eugene Zelenko38c70522017-12-07 21:55:09 +0000480 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000481 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000482
483 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000484 bool switchExclusivelyCovered = false;
485 Expr::EvalResult *switchCond = nullptr;
Ted Kremeneka099c592011-03-10 03:50:34 +0000486
Eugene Zelenko38c70522017-12-07 21:55:09 +0000487 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
488 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000489
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000490 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
491 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000492 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000493 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000494
Mike Stump31feda52009-07-17 01:31:16 +0000495public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000496 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000497 const CFG::BuildOptions &buildOpts)
498 : Context(astContext), cfg(new CFG()), // crew a new CFG
Eugene Zelenko38c70522017-12-07 21:55:09 +0000499 BuildOpts(buildOpts) {}
Mike Stump31feda52009-07-17 01:31:16 +0000500
Ted Kremenek9aae5132007-08-23 21:42:29 +0000501 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000502 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000503
Ted Kremeneka099c592011-03-10 03:50:34 +0000504 bool alwaysAdd(const Stmt *stmt);
505
Ted Kremenek93668002009-07-17 22:18:43 +0000506private:
507 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000508 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
509 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000510 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000511 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000512 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000513 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000514 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000515 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
516 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000517 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000518 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
519 AddStmtChoice asc);
520 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
521 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000522 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000523 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000524 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
525 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
526 AddStmtChoice asc);
527 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
528 AddStmtChoice asc);
529 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
530 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000531 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000532 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000533 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
534 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000535 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000536 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000537 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000538 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000539 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000540 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
541 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000542 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000543 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000544 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000545 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
546 Stmt *Term,
547 CFGBlock *TrueBlock,
548 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000549 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000550 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
551 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
552 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
553 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000554 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000555 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000556 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000557 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Nico Weber699670e2017-08-23 15:33:16 +0000558 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
559 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
560 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
561 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000562 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000563 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000564 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
565 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000566 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000567 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000568
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000569 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
570 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000571 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000572 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000573
Manuel Klimekb5616c92014-08-07 10:42:17 +0000574 /// When creating the CFG for temporary destructors, we want to mirror the
575 /// branch structure of the corresponding constructor calls.
576 /// Thus, while visiting a statement for temporary destructors, we keep a
577 /// context to keep track of the following information:
578 /// - whether a subexpression is executed unconditionally
579 /// - if a subexpression is executed conditionally, the first
580 /// CXXBindTemporaryExpr we encounter in that subexpression (which
581 /// corresponds to the last temporary destructor we have to call for this
582 /// subexpression) and the CFG block at that point (which will become the
583 /// successor block when inserting the decision point).
584 ///
585 /// That way, we can build the branch structure for temporary destructors as
586 /// follows:
587 /// 1. If a subexpression is executed unconditionally, we add the temporary
588 /// destructor calls to the current block.
589 /// 2. If a subexpression is executed conditionally, when we encounter a
590 /// CXXBindTemporaryExpr:
591 /// a) If it is the first temporary destructor call in the subexpression,
592 /// we remember the CXXBindTemporaryExpr and the current block in the
593 /// TempDtorContext; we start a new block, and insert the temporary
594 /// destructor call.
595 /// b) Otherwise, add the temporary destructor call to the current block.
596 /// 3. When we finished visiting a conditionally executed subexpression,
597 /// and we found at least one temporary constructor during the visitation
598 /// (2.a has executed), we insert a decision block that uses the
599 /// CXXBindTemporaryExpr as terminator, and branches to the current block
600 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
601 /// branches to the stored successor.
602 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000603 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000604 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000605 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000606
607 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000608 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000609 /// conditionally executed, and it is the first one we encounter while
610 /// visiting a subexpression - other temporary destructors at the same level
611 /// will be added to the same block and are executed under the same
612 /// condition.
613 bool needsTempDtorBranch() const {
614 return IsConditional && !TerminatorExpr;
615 }
616
617 /// Remember the successor S of a temporary destructor decision branch for
618 /// the corresponding CXXBindTemporaryExpr E.
619 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
620 Succ = S;
621 TerminatorExpr = E;
622 }
623
Eugene Zelenko38c70522017-12-07 21:55:09 +0000624 const bool IsConditional = false;
625 const TryResult KnownExecuted = true;
626 CFGBlock *Succ = nullptr;
627 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000628 };
629
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000630 // Visitors to walk an AST and generate destructors of temporaries in
631 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000632 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
633 TempDtorContext &Context);
634 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
635 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
636 TempDtorContext &Context);
637 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
638 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
639 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
640 AbstractConditionalOperator *E, bool BindToTemporary,
641 TempDtorContext &Context);
642 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
643 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000644
Ted Kremenek6065ef62008-04-28 18:00:46 +0000645 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000646 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000647 badCFG = true;
648 return Block;
649 }
Mike Stump31feda52009-07-17 01:31:16 +0000650
Artem Dergachev41ffb302018-02-08 22:58:15 +0000651 // Scan the child statement \p Child to find the constructor that might
652 // have been directly triggered by the current node, \p Trigger. If such
653 // constructor has been found, set current construction context to point
654 // to the trigger statement. The construction context will be unset once
655 // it is consumed when the CFG building procedure processes the
656 // construct-expression and adds the respective CFGConstructor element.
Artem Dergachev5a281bb2018-02-10 02:18:04 +0000657 void EnterConstructionContextIfNecessary(
658 ConstructionContext::TriggerTy Trigger, Stmt *Child);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000659 // Unset the construction context after consuming it. This is done immediately
660 // after adding the CFGConstructor element, so there's no need to
661 // do this manually in every Visit... function.
662 void ExitConstructionContext();
663
Ted Kremenek93668002009-07-17 22:18:43 +0000664 void autoCreateBlock() { if (!Block) Block = createBlock(); }
665 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000666 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000667
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000668 CFGBlock *addStmt(Stmt *S) {
669 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000670 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000671
Alexis Hunt1d792652011-01-08 20:30:50 +0000672 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000673 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000674 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000675 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000676 void addLifetimeEnds(LocalScope::const_iterator B,
677 LocalScope::const_iterator E, Stmt *S);
678 void addAutomaticObjHandling(LocalScope::const_iterator B,
679 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000680 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000681
Marcin Swiderski5e415732010-09-30 23:05:00 +0000682 // Local scopes creation.
683 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
684
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000685 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000686 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
687 LocalScope* Scope = nullptr);
688 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000689
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000690 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000691
692 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000693
Ted Kremenek37881932011-04-04 23:29:12 +0000694 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000695 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000696 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000697
Jordy Rose17347372011-06-10 08:49:37 +0000698 // All block-level expressions should have already been IgnoreParens()ed.
699 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000700 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000701 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000702
Artem Dergachev41ffb302018-02-08 22:58:15 +0000703 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
704 if (BuildOpts.AddRichCXXConstructors) {
705 if (!CurrentConstructionContext.isNull()) {
706 B->appendConstructor(CE, CurrentConstructionContext,
707 cfg->getBumpVectorContext());
708 ExitConstructionContext();
709 return;
710 }
711 }
712
713 // No valid construction context found. Fall back to statement.
714 B->appendStmt(CE, cfg->getBumpVectorContext());
715 }
716
Alexis Hunt1d792652011-01-08 20:30:50 +0000717 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000718 B->appendInitializer(I, cfg->getBumpVectorContext());
719 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000720
Jordan Rosec9176072014-01-13 17:59:19 +0000721 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
722 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
723 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000724
Marcin Swiderski20b88732010-10-05 05:37:00 +0000725 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
726 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
727 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000728
Marcin Swiderski20b88732010-10-05 05:37:00 +0000729 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
730 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
731 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000732
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000733 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
734 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
735 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000736
Chandler Carruthad747252011-09-13 06:09:01 +0000737 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
738 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
739 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000740
Matthias Gehre351c2182017-07-12 07:04:19 +0000741 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
742 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
743 }
744
Peter Szecsi999a25f2017-08-19 11:19:16 +0000745 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
746 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
747 }
748
Jordan Rosed2f40792013-09-03 17:00:57 +0000749 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
750 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
751 }
752
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000753 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000754 LocalScope::const_iterator B, LocalScope::const_iterator E);
755
Matthias Gehre351c2182017-07-12 07:04:19 +0000756 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
757 LocalScope::const_iterator B,
758 LocalScope::const_iterator E);
759
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000760 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
761 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
762 cfg->getBumpVectorContext());
763 }
764
765 /// Add a reachable successor to a block, with the alternate variant that is
766 /// unreachable.
767 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
768 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
769 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000770 }
Mike Stump11289f42009-09-09 15:08:12 +0000771
Richard Trieuf935b562014-04-05 05:17:01 +0000772 /// \brief Find a relational comparison with an expression evaluating to a
773 /// boolean and a constant other than 0 and 1.
774 /// e.g. if ((x < y) == 10)
775 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
776 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
777 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
778
779 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
780 const Expr *BoolExpr = RHSExpr;
781 bool IntFirst = true;
782 if (!IntLiteral) {
783 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
784 BoolExpr = LHSExpr;
785 IntFirst = false;
786 }
787
788 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
789 return TryResult();
790
791 llvm::APInt IntValue = IntLiteral->getValue();
792 if ((IntValue == 1) || (IntValue == 0))
793 return TryResult();
794
795 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
796 !IntValue.isNegative();
797
798 BinaryOperatorKind Bok = B->getOpcode();
799 if (Bok == BO_GT || Bok == BO_GE) {
800 // Always true for 10 > bool and bool > -1
801 // Always false for -1 > bool and bool > 10
802 return TryResult(IntFirst == IntLarger);
803 } else {
804 // Always true for -1 < bool and bool < 10
805 // Always false for 10 < bool and bool < -1
806 return TryResult(IntFirst != IntLarger);
807 }
808 }
809
Jordan Rose7afd71e2014-05-20 17:31:11 +0000810 /// Find an incorrect equality comparison. Either with an expression
811 /// evaluating to a boolean and a constant other than 0 and 1.
812 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
813 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000814 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
815 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
816 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
817
818 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
819 const Expr *BoolExpr = RHSExpr;
820
821 if (!IntLiteral) {
822 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
823 BoolExpr = LHSExpr;
824 }
825
Jordan Rose7afd71e2014-05-20 17:31:11 +0000826 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000827 return TryResult();
828
Jordan Rose7afd71e2014-05-20 17:31:11 +0000829 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
830 if (BitOp && (BitOp->getOpcode() == BO_And ||
831 BitOp->getOpcode() == BO_Or)) {
832 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
833 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
834
835 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
836
837 if (!IntLiteral2)
838 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
839
840 if (!IntLiteral2)
841 return TryResult();
842
843 llvm::APInt L1 = IntLiteral->getValue();
844 llvm::APInt L2 = IntLiteral2->getValue();
845 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
846 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
847 if (BuildOpts.Observer)
848 BuildOpts.Observer->compareBitwiseEquality(B,
849 B->getOpcode() != BO_EQ);
850 TryResult(B->getOpcode() != BO_EQ);
851 }
852 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
853 llvm::APInt IntValue = IntLiteral->getValue();
854 if ((IntValue == 1) || (IntValue == 0)) {
855 return TryResult();
856 }
857 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000858 }
859
Jordan Rose7afd71e2014-05-20 17:31:11 +0000860 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000861 }
862
863 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
864 const llvm::APSInt &Value1,
865 const llvm::APSInt &Value2) {
866 assert(Value1.isSigned() == Value2.isSigned());
867 switch (Relation) {
868 default:
869 return TryResult();
870 case BO_EQ:
871 return TryResult(Value1 == Value2);
872 case BO_NE:
873 return TryResult(Value1 != Value2);
874 case BO_LT:
875 return TryResult(Value1 < Value2);
876 case BO_LE:
877 return TryResult(Value1 <= Value2);
878 case BO_GT:
879 return TryResult(Value1 > Value2);
880 case BO_GE:
881 return TryResult(Value1 >= Value2);
882 }
883 }
884
885 /// \brief Find a pair of comparison expressions with or without parentheses
886 /// with a shared variable and constants and a logical operator between them
887 /// that always evaluates to either true or false.
888 /// e.g. if (x != 3 || x != 4)
889 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
890 assert(B->isLogicalOp());
891 const BinaryOperator *LHS =
892 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
893 const BinaryOperator *RHS =
894 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
895 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000896 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000897
898 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000899 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000900
George Burgess IVced56e62015-10-01 18:47:52 +0000901 const DeclRefExpr *Decl1;
902 const Expr *Expr1;
903 BinaryOperatorKind BO1;
904 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000905
George Burgess IVced56e62015-10-01 18:47:52 +0000906 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000907 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000908
George Burgess IVced56e62015-10-01 18:47:52 +0000909 const DeclRefExpr *Decl2;
910 const Expr *Expr2;
911 BinaryOperatorKind BO2;
912 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000913
George Burgess IVced56e62015-10-01 18:47:52 +0000914 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000915 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000916
917 // Check that it is the same variable on both sides.
918 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000919 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000920
George Burgess IVced56e62015-10-01 18:47:52 +0000921 // Make sure the user's intent is clear (e.g. they're comparing against two
922 // int literals, or two things from the same enum)
923 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000924 return {};
George Burgess IVced56e62015-10-01 18:47:52 +0000925
Richard Trieuf935b562014-04-05 05:17:01 +0000926 llvm::APSInt L1, L2;
927
George Burgess IVced56e62015-10-01 18:47:52 +0000928 if (!Expr1->EvaluateAsInt(L1, *Context) ||
929 !Expr2->EvaluateAsInt(L2, *Context))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000930 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000931
932 // Can't compare signed with unsigned or with different bit width.
933 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000934 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000935
936 // Values that will be used to determine if result of logical
937 // operator is always true/false
938 const llvm::APSInt Values[] = {
939 // Value less than both Value1 and Value2
940 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
941 // L1
942 L1,
943 // Value between Value1 and Value2
944 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
945 L1.isUnsigned()),
946 // L2
947 L2,
948 // Value greater than both Value1 and Value2
949 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
950 };
951
952 // Check whether expression is always true/false by evaluating the following
953 // * variable x is less than the smallest literal.
954 // * variable x is equal to the smallest literal.
955 // * Variable x is between smallest and largest literal.
956 // * Variable x is equal to the largest literal.
957 // * Variable x is greater than largest literal.
958 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +0000959 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +0000960 TryResult Res1, Res2;
961 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
962 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
963
964 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000965 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000966
967 if (B->getOpcode() == BO_LAnd) {
968 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
969 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
970 } else {
971 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
972 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
973 }
974 }
975
976 if (AlwaysTrue || AlwaysFalse) {
977 if (BuildOpts.Observer)
978 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
979 return TryResult(AlwaysTrue);
980 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000981 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000982 }
983
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000984 /// Try and evaluate an expression to an integer constant.
985 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
986 if (!BuildOpts.PruneTriviallyFalseEdges)
987 return false;
988 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000989 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000990 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000991 }
Mike Stump11289f42009-09-09 15:08:12 +0000992
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000993 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000994 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000995 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000996 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000997 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000998 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000999
1000 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1001 if (Bop->isLogicalOp()) {
1002 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001003 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1004 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001005 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001006
1007 // Retrieve result at first, or the map might be updated.
1008 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1009 CachedBoolEvals[S] = Result; // update or insert
1010 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001011 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001012 else {
1013 switch (Bop->getOpcode()) {
1014 default: break;
1015 // For 'x & 0' and 'x * 0', we can determine that
1016 // the value is always false.
1017 case BO_Mul:
1018 case BO_And: {
1019 // If either operand is zero, we know the value
1020 // must be false.
1021 llvm::APSInt IntVal;
1022 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001023 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001024 return TryResult(false);
1025 }
1026 }
1027 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001028 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001029 return TryResult(false);
1030 }
1031 }
1032 }
1033 break;
1034 }
1035 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001036 }
1037
1038 return evaluateAsBooleanConditionNoCache(S);
1039 }
1040
1041 /// \brief Evaluate as boolean \param E without using the cache.
1042 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1043 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1044 if (Bop->isLogicalOp()) {
1045 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1046 if (LHS.isKnown()) {
1047 // We were able to evaluate the LHS, see if we can get away with not
1048 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1049 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1050 return LHS.isTrue();
1051
1052 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1053 if (RHS.isKnown()) {
1054 if (Bop->getOpcode() == BO_LOr)
1055 return LHS.isTrue() || RHS.isTrue();
1056 else
1057 return LHS.isTrue() && RHS.isTrue();
1058 }
1059 } else {
1060 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1061 if (RHS.isKnown()) {
1062 // We can't evaluate the LHS; however, sometimes the result
1063 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1064 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1065 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001066 } else {
1067 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1068 if (BopRes.isKnown())
1069 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001070 }
1071 }
1072
Eugene Zelenko38c70522017-12-07 21:55:09 +00001073 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001074 } else if (Bop->isEqualityOp()) {
1075 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1076 if (BopRes.isKnown())
1077 return BopRes.isTrue();
1078 } else if (Bop->isRelationalOp()) {
1079 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1080 if (BopRes.isKnown())
1081 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001082 }
1083 }
1084
1085 bool Result;
1086 if (E->EvaluateAsBooleanCondition(Result, *Context))
1087 return Result;
1088
Eugene Zelenko38c70522017-12-07 21:55:09 +00001089 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001090 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001091
1092 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001093};
Mike Stump31feda52009-07-17 01:31:16 +00001094
Eugene Zelenko38c70522017-12-07 21:55:09 +00001095} // namespace
1096
Ted Kremeneka099c592011-03-10 03:50:34 +00001097inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1098 const Stmt *stmt) const {
1099 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1100}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001101
Ted Kremeneka099c592011-03-10 03:50:34 +00001102bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001103 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1104
Ted Kremeneka099c592011-03-10 03:50:34 +00001105 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001106 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001107
1108 if (lastLookup == stmt) {
1109 if (cachedEntry) {
1110 assert(cachedEntry->first == stmt);
1111 return true;
1112 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001113 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001114 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001115
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001116 lastLookup = stmt;
1117
1118 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001119 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1120
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001121 if (!fb) {
1122 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001123 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001124 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001125 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001126
1127 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001128 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001129 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001130 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001131 }
1132
Ted Kremeneka099c592011-03-10 03:50:34 +00001133 cachedEntry = &*itr;
1134 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001135}
1136
Douglas Gregor4619e432008-12-05 23:32:09 +00001137// FIXME: Add support for dependent-sized array types in C++?
1138// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001139static const VariableArrayType *FindVA(const Type *t) {
1140 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1141 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001142 if (vat->getSizeExpr())
1143 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001144
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001145 t = vt->getElementType().getTypePtr();
1146 }
Mike Stump31feda52009-07-17 01:31:16 +00001147
Craig Topper25542942014-05-20 04:30:07 +00001148 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001149}
Mike Stump31feda52009-07-17 01:31:16 +00001150
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001151void CFGBuilder::EnterConstructionContextIfNecessary(
1152 ConstructionContext::TriggerTy Trigger, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001153 if (!BuildOpts.AddRichCXXConstructors)
1154 return;
1155 if (!Child)
1156 return;
Artem Dergachev675d6f42018-02-09 01:43:26 +00001157 if (isa<CXXConstructExpr>(Child)) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001158 assert(CurrentConstructionContext.isNull() &&
1159 "Already within a construction context!");
1160 CurrentConstructionContext = ConstructionContext(Trigger);
1161 }
1162}
1163
1164void CFGBuilder::ExitConstructionContext() {
1165 assert(!CurrentConstructionContext.isNull() &&
1166 "Cannot exit construction context without the context!");
1167 CurrentConstructionContext = ConstructionContext();
1168}
1169
1170
Mike Stump31feda52009-07-17 01:31:16 +00001171/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1172/// arbitrary statement. Examples include a single expression or a function
1173/// body (compound statement). The ownership of the returned CFG is
1174/// transferred to the caller. If CFG construction fails, this method returns
1175/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001176std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001177 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001178 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001179 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001180
Mike Stump31feda52009-07-17 01:31:16 +00001181 // Create an empty block that will serve as the exit block for the CFG. Since
1182 // this is the first block added to the CFG, it will be implicitly registered
1183 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001184 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001185 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001186 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001187
Matthias Gehre351c2182017-07-12 07:04:19 +00001188 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1189 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1190
Marcin Swiderski20b88732010-10-05 05:37:00 +00001191 if (BuildOpts.AddImplicitDtors)
1192 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1193 addImplicitDtorsForDestructor(DD);
1194
Ted Kremenek9aae5132007-08-23 21:42:29 +00001195 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001196 CFGBlock *B = addStmt(Statement);
1197
1198 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001199 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001200
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001201 // For C++ constructor add initializers to CFG.
1202 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001203 for (auto *I : llvm::reverse(CD->inits())) {
1204 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001205 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001206 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001207 }
1208 }
1209
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001210 if (B)
1211 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001212
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001213 // Backpatch the gotos whose label -> block mappings we didn't know when we
1214 // encountered them.
1215 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1216 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001217
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001218 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001219 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001220 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001221
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001222 // If there is no target for the goto, then we are looking at an
1223 // incomplete AST. Handle this by not registering a successor.
1224 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001225
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001226 JumpTarget JT = LI->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00001227 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1228 JT.scopePosition);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001229 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1230 JT.scopePosition);
1231 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001232 }
1233
1234 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001235 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001236 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1237 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001238 // Lookup the target block.
1239 LabelMapTy::iterator LI = LabelMap.find(*I);
1240
1241 // If there is no target block that contains label, then we are looking
1242 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001243 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001244
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001245 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001246 }
Mike Stump31feda52009-07-17 01:31:16 +00001247
Mike Stump31feda52009-07-17 01:31:16 +00001248 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001249 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001250
David Blaikiee90195c2014-08-29 18:53:26 +00001251 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001252}
Mike Stump31feda52009-07-17 01:31:16 +00001253
Ted Kremenek9aae5132007-08-23 21:42:29 +00001254/// createBlock - Used to lazily create blocks that are connected
1255/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001256CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1257 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001258 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001259 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001260 return B;
1261}
Mike Stump31feda52009-07-17 01:31:16 +00001262
Chandler Carrutha70991b2011-09-13 09:13:49 +00001263/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1264/// CFG. It is *not* connected to the current (global) successor, and instead
1265/// directly tied to the exit block in order to be reachable.
1266CFGBlock *CFGBuilder::createNoReturnBlock() {
1267 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001268 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001269 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001270 return B;
1271}
1272
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001273/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001274CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001275 if (!BuildOpts.AddInitializers)
1276 return Block;
1277
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001278 bool HasTemporaries = false;
1279
1280 // Destructors of temporaries in initialization expression should be called
1281 // after initialization finishes.
1282 Expr *Init = I->getInit();
1283 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001284 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001285
Jordan Rose6d671cc2012-09-05 22:55:23 +00001286 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001287 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001288 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001289 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1290 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001291 }
1292 }
1293
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001294 autoCreateBlock();
1295 appendInitializer(Block, I);
1296
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001297 if (Init) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001298 EnterConstructionContextIfNecessary(I, Init);
1299
Ted Kremenek8219b822010-12-16 07:46:53 +00001300 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001301 // For expression with temporaries go directly to subexpression to omit
1302 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001303 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1304 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001305 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1306 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1307 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1308 // may cause the same Expr to appear more than once in the CFG. Doing it
1309 // here is safe because there's only one initializer per field.
1310 autoCreateBlock();
1311 appendStmt(Block, Default);
1312 if (Stmt *Child = Default->getExpr())
1313 if (CFGBlock *R = Visit(Child))
1314 Block = R;
1315 return Block;
1316 }
1317 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001318 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001319 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001320
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001321 return Block;
1322}
1323
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001324/// \brief Retrieve the type of the temporary object whose lifetime was
1325/// extended by a local reference with the given initializer.
1326static QualType getReferenceInitTemporaryType(ASTContext &Context,
Richard Smithb8c0f552016-12-09 18:49:13 +00001327 const Expr *Init,
1328 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001329 while (true) {
1330 // Skip parentheses.
1331 Init = Init->IgnoreParens();
1332
1333 // Skip through cleanups.
1334 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1335 Init = EWC->getSubExpr();
1336 continue;
1337 }
1338
1339 // Skip through the temporary-materialization expression.
1340 if (const MaterializeTemporaryExpr *MTE
1341 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1342 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001343 if (FoundMTE)
1344 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001345 continue;
1346 }
1347
1348 // Skip derived-to-base and no-op casts.
1349 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1350 if ((CE->getCastKind() == CK_DerivedToBase ||
1351 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1352 CE->getCastKind() == CK_NoOp) &&
1353 Init->getType()->isRecordType()) {
1354 Init = CE->getSubExpr();
1355 continue;
1356 }
1357 }
1358
1359 // Skip member accesses into rvalues.
1360 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1361 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1362 Init = ME->getBase();
1363 continue;
1364 }
1365 }
1366
1367 break;
1368 }
1369
1370 return Init->getType();
1371}
Matthias Gehre351c2182017-07-12 07:04:19 +00001372
Peter Szecsi999a25f2017-08-19 11:19:16 +00001373// TODO: Support adding LoopExit element to the CFG in case where the loop is
1374// ended by ReturnStmt, GotoStmt or ThrowExpr.
1375void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1376 if(!BuildOpts.AddLoopExit)
1377 return;
1378 autoCreateBlock();
1379 appendLoopExit(Block, LoopStmt);
1380}
1381
Matthias Gehre351c2182017-07-12 07:04:19 +00001382void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1383 LocalScope::const_iterator E,
1384 Stmt *S) {
1385 if (BuildOpts.AddImplicitDtors)
1386 addAutomaticObjDtors(B, E, S);
1387 if (BuildOpts.AddLifetime)
1388 addLifetimeEnds(B, E, S);
1389}
1390
1391/// Add to current block automatic objects that leave the scope.
1392void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1393 LocalScope::const_iterator E, Stmt *S) {
1394 if (!BuildOpts.AddLifetime)
1395 return;
1396
1397 if (B == E)
1398 return;
1399
1400 // To go from B to E, one first goes up the scopes from B to P
1401 // then sideways in one scope from P to P' and then down
1402 // the scopes from P' to E.
1403 // The lifetime of all objects between B and P end.
1404 LocalScope::const_iterator P = B.shared_parent(E);
1405 int dist = B.distance(P);
1406 if (dist <= 0)
1407 return;
1408
1409 // We need to perform the scope leaving in reverse order
1410 SmallVector<VarDecl *, 10> DeclsTrivial;
1411 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1412 DeclsTrivial.reserve(dist);
1413 DeclsNonTrivial.reserve(dist);
1414
1415 for (LocalScope::const_iterator I = B; I != P; ++I)
1416 if (hasTrivialDestructor(*I))
1417 DeclsTrivial.push_back(*I);
1418 else
1419 DeclsNonTrivial.push_back(*I);
1420
1421 autoCreateBlock();
1422 // object with trivial destructor end their lifetime last (when storage
1423 // duration ends)
1424 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1425 E = DeclsTrivial.rend();
1426 I != E; ++I)
1427 appendLifetimeEnds(Block, *I, S);
1428
1429 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1430 I = DeclsNonTrivial.rbegin(),
1431 E = DeclsNonTrivial.rend();
1432 I != E; ++I)
1433 appendLifetimeEnds(Block, *I, S);
1434}
1435
Marcin Swiderski5e415732010-09-30 23:05:00 +00001436/// addAutomaticObjDtors - Add to current block automatic objects destructors
1437/// for objects in range of local scope positions. Use S as trigger statement
1438/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001439void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001440 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001441 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001442 return;
1443
Marcin Swiderski5e415732010-09-30 23:05:00 +00001444 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001445 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001446
Chandler Carruthad747252011-09-13 06:09:01 +00001447 // We need to append the destructors in reverse order, but any one of them
1448 // may be a no-return destructor which changes the CFG. As a result, buffer
1449 // this sequence up and replay them in reverse order when appending onto the
1450 // CFGBlock(s).
1451 SmallVector<VarDecl*, 10> Decls;
1452 Decls.reserve(B.distance(E));
1453 for (LocalScope::const_iterator I = B; I != E; ++I)
1454 Decls.push_back(*I);
1455
1456 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1457 E = Decls.rend();
1458 I != E; ++I) {
1459 // If this destructor is marked as a no-return destructor, we need to
1460 // create a new block for the destructor which does not have as a successor
1461 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001462 QualType Ty = (*I)->getType();
1463 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001464 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001465 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001466 Ty = Context->getBaseElementType(Ty);
1467
Richard Trieu95a192a2015-05-28 00:14:02 +00001468 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001469 Block = createNoReturnBlock();
1470 else
Chandler Carruthad747252011-09-13 06:09:01 +00001471 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001472
1473 appendAutomaticObjDtor(Block, *I, S);
1474 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001475}
1476
Marcin Swiderski20b88732010-10-05 05:37:00 +00001477/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1478/// base and member objects in destructor.
1479void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001480 assert(BuildOpts.AddImplicitDtors &&
1481 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001482 const CXXRecordDecl *RD = DD->getParent();
1483
1484 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001485 for (const auto &VI : RD->vbases()) {
1486 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001487 if (!CD->hasTrivialDestructor()) {
1488 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001489 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001490 }
1491 }
1492
1493 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001494 for (const auto &BI : RD->bases()) {
1495 if (!BI.isVirtual()) {
1496 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001497 if (!CD->hasTrivialDestructor()) {
1498 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001499 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001500 }
1501 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001502 }
1503
1504 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001505 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001506 // Check for constant size array. Set type to array element type.
1507 QualType QT = FI->getType();
1508 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1509 if (AT->getSize() == 0)
1510 continue;
1511 QT = AT->getElementType();
1512 }
1513
1514 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001515 if (!CD->hasTrivialDestructor()) {
1516 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001517 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001518 }
1519 }
1520}
1521
Marcin Swiderski5e415732010-09-30 23:05:00 +00001522/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1523/// way return valid LocalScope object.
1524LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001525 if (Scope)
1526 return Scope;
1527 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1528 return new (alloc.Allocate<LocalScope>())
1529 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001530}
1531
1532/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001533/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001534void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001535 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001536 return;
1537
Craig Topper25542942014-05-20 04:30:07 +00001538 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001539
1540 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001541 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001542 for (auto *BI : CS->body()) {
1543 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001544 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001545 Scope = addLocalScopeForDeclStmt(DS, Scope);
1546 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001547 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001548 }
1549
1550 // For any other statement scope will be implicit and as such will be
1551 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001552 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001553 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001554}
1555
1556/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1557/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001558LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001559 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001560 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001561 return Scope;
1562
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001563 for (auto *DI : DS->decls())
1564 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001565 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001566 return Scope;
1567}
1568
Matthias Gehre351c2182017-07-12 07:04:19 +00001569bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1570 // Check for const references bound to temporary. Set type to pointee.
1571 QualType QT = VD->getType();
1572 if (QT.getTypePtr()->isReferenceType()) {
1573 // Attempt to determine whether this declaration lifetime-extends a
1574 // temporary.
1575 //
1576 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1577 // temporaries, and a single declaration can extend multiple temporaries.
1578 // We should look at the storage duration on each nested
1579 // MaterializeTemporaryExpr instead.
1580
1581 const Expr *Init = VD->getInit();
1582 if (!Init)
1583 return true;
1584
1585 // Lifetime-extending a temporary.
1586 bool FoundMTE = false;
1587 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1588 if (!FoundMTE)
1589 return true;
1590 }
1591
1592 // Check for constant size array. Set type to array element type.
1593 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1594 if (AT->getSize() == 0)
1595 return true;
1596 QT = AT->getElementType();
1597 }
1598
1599 // Check if type is a C++ class with non-trivial destructor.
1600 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1601 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1602 return true;
1603}
1604
Marcin Swiderski5e415732010-09-30 23:05:00 +00001605/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1606/// create add scope for automatic objects and temporary objects bound to
1607/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001608LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001609 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001610 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1611 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1612 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001613 return Scope;
1614
1615 // Check if variable is local.
1616 switch (VD->getStorageClass()) {
1617 case SC_None:
1618 case SC_Auto:
1619 case SC_Register:
1620 break;
1621 default: return Scope;
1622 }
1623
Matthias Gehre351c2182017-07-12 07:04:19 +00001624 if (BuildOpts.AddImplicitDtors) {
1625 if (!hasTrivialDestructor(VD)) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001626 // Add the variable to scope
1627 Scope = createOrReuseLocalScope(Scope);
1628 Scope->addVar(VD);
1629 ScopePos = Scope->begin();
1630 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001631 return Scope;
1632 }
1633
1634 assert(BuildOpts.AddLifetime);
1635 // Add the variable to scope
1636 Scope = createOrReuseLocalScope(Scope);
1637 Scope->addVar(VD);
1638 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001639 return Scope;
1640}
1641
1642/// addLocalScopeAndDtors - For given statement add local scope for it and
1643/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001644void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001645 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001646 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001647 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001648}
1649
Marcin Swiderski321a7072010-09-30 22:54:37 +00001650/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1651/// variables with automatic storage duration to CFGBlock's elements vector.
1652/// Elements will be prepended to physical beginning of the vector which
1653/// happens to be logical end. Use blocks terminator as statement that specifies
1654/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001655/// FIXME: This mechanism for adding automatic destructors doesn't handle
1656/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001657void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001658 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001659 if (!BuildOpts.AddImplicitDtors)
1660 return;
Chandler Carruthad747252011-09-13 06:09:01 +00001661 BumpVectorContext &C = cfg->getBumpVectorContext();
1662 CFGBlock::iterator InsertPos
1663 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1664 for (LocalScope::const_iterator I = B; I != E; ++I)
1665 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1666 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001667}
1668
Matthias Gehre351c2182017-07-12 07:04:19 +00001669/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1670/// variables with automatic storage duration to CFGBlock's elements vector.
1671/// Elements will be prepended to physical beginning of the vector which
1672/// happens to be logical end. Use blocks terminator as statement that specifies
1673/// where lifetime ends.
1674void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1675 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1676 if (!BuildOpts.AddLifetime)
1677 return;
1678 BumpVectorContext &C = cfg->getBumpVectorContext();
1679 CFGBlock::iterator InsertPos =
1680 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1681 for (LocalScope::const_iterator I = B; I != E; ++I)
1682 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1683}
Eugene Zelenko38c70522017-12-07 21:55:09 +00001684
Ted Kremenek93668002009-07-17 22:18:43 +00001685/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001686/// blocks for ternary operators, &&, and ||. We also process "," and
1687/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001688CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001689 if (!S) {
1690 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001691 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001692 }
Jordy Rose17347372011-06-10 08:49:37 +00001693
1694 if (Expr *E = dyn_cast<Expr>(S))
1695 S = E->IgnoreParens();
1696
Ted Kremenek93668002009-07-17 22:18:43 +00001697 switch (S->getStmtClass()) {
1698 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001699 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001700
1701 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001702 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001703
John McCallc07a0c72011-02-17 10:25:35 +00001704 case Stmt::BinaryConditionalOperatorClass:
1705 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1706
Ted Kremenek93668002009-07-17 22:18:43 +00001707 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001708 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Ted Kremenek93668002009-07-17 22:18:43 +00001710 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00001711 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001712
Ted Kremenek93668002009-07-17 22:18:43 +00001713 case Stmt::BreakStmtClass:
1714 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001715
Ted Kremenek93668002009-07-17 22:18:43 +00001716 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001717 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001718 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001719 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001720 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Ted Kremenek93668002009-07-17 22:18:43 +00001722 case Stmt::CaseStmtClass:
1723 return VisitCaseStmt(cast<CaseStmt>(S));
1724
1725 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001726 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001727
Ted Kremenek93668002009-07-17 22:18:43 +00001728 case Stmt::CompoundStmtClass:
1729 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001730
Ted Kremenek93668002009-07-17 22:18:43 +00001731 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001732 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Ted Kremenek93668002009-07-17 22:18:43 +00001734 case Stmt::ContinueStmtClass:
1735 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001736
Ted Kremenekb27378c2010-01-19 20:40:33 +00001737 case Stmt::CXXCatchStmtClass:
1738 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1739
John McCall5d413782010-12-06 08:20:24 +00001740 case Stmt::ExprWithCleanupsClass:
1741 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001742
Jordan Rosee5d53932012-08-23 18:10:53 +00001743 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001744 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001745 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1746 // called function's declaration, not by the caller. If we simply add
1747 // this expression to the CFG, we could end up with the same Expr
1748 // appearing multiple times.
1749 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001750 //
1751 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1752 // expression to be used in the same function (through aggregate
1753 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001754 return VisitStmt(S, asc);
1755
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001756 case Stmt::CXXBindTemporaryExprClass:
1757 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1758
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001759 case Stmt::CXXConstructExprClass:
1760 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1761
Jordan Rosec9176072014-01-13 17:59:19 +00001762 case Stmt::CXXNewExprClass:
1763 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1764
Jordan Rosed2f40792013-09-03 17:00:57 +00001765 case Stmt::CXXDeleteExprClass:
1766 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1767
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001768 case Stmt::CXXFunctionalCastExprClass:
1769 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1770
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001771 case Stmt::CXXTemporaryObjectExprClass:
1772 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1773
Ted Kremenekb27378c2010-01-19 20:40:33 +00001774 case Stmt::CXXThrowExprClass:
1775 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001776
Ted Kremenekb27378c2010-01-19 20:40:33 +00001777 case Stmt::CXXTryStmtClass:
1778 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001779
Richard Smith02e85f32011-04-14 22:09:26 +00001780 case Stmt::CXXForRangeStmtClass:
1781 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1782
Ted Kremenek93668002009-07-17 22:18:43 +00001783 case Stmt::DeclStmtClass:
1784 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001785
Ted Kremenek93668002009-07-17 22:18:43 +00001786 case Stmt::DefaultStmtClass:
1787 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001788
Ted Kremenek93668002009-07-17 22:18:43 +00001789 case Stmt::DoStmtClass:
1790 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001791
Ted Kremenek93668002009-07-17 22:18:43 +00001792 case Stmt::ForStmtClass:
1793 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001794
Ted Kremenek93668002009-07-17 22:18:43 +00001795 case Stmt::GotoStmtClass:
1796 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001797
Ted Kremenek93668002009-07-17 22:18:43 +00001798 case Stmt::IfStmtClass:
1799 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001800
Ted Kremenek8219b822010-12-16 07:46:53 +00001801 case Stmt::ImplicitCastExprClass:
1802 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001803
Ted Kremenek93668002009-07-17 22:18:43 +00001804 case Stmt::IndirectGotoStmtClass:
1805 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001806
Ted Kremenek93668002009-07-17 22:18:43 +00001807 case Stmt::LabelStmtClass:
1808 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001809
Ted Kremenekda76a942012-04-12 20:34:52 +00001810 case Stmt::LambdaExprClass:
1811 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1812
Ted Kremenek5868ec62010-04-11 17:02:10 +00001813 case Stmt::MemberExprClass:
1814 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1815
Ted Kremenek04268232011-11-05 00:10:15 +00001816 case Stmt::NullStmtClass:
1817 return Block;
1818
Ted Kremenek93668002009-07-17 22:18:43 +00001819 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001820 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1821
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001822 case Stmt::ObjCAutoreleasePoolStmtClass:
1823 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1824
Ted Kremenek93668002009-07-17 22:18:43 +00001825 case Stmt::ObjCAtSynchronizedStmtClass:
1826 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001827
Ted Kremenek93668002009-07-17 22:18:43 +00001828 case Stmt::ObjCAtThrowStmtClass:
1829 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001830
Ted Kremenek93668002009-07-17 22:18:43 +00001831 case Stmt::ObjCAtTryStmtClass:
1832 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001833
Ted Kremenek93668002009-07-17 22:18:43 +00001834 case Stmt::ObjCForCollectionStmtClass:
1835 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001836
Ted Kremenek04268232011-11-05 00:10:15 +00001837 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001838 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001839
John McCallfe96e0b2011-11-06 09:01:30 +00001840 case Stmt::PseudoObjectExprClass:
1841 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1842
Ted Kremenek93668002009-07-17 22:18:43 +00001843 case Stmt::ReturnStmtClass:
1844 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001845
Nico Weber699670e2017-08-23 15:33:16 +00001846 case Stmt::SEHExceptStmtClass:
1847 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
1848
1849 case Stmt::SEHFinallyStmtClass:
1850 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
1851
1852 case Stmt::SEHLeaveStmtClass:
1853 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
1854
1855 case Stmt::SEHTryStmtClass:
1856 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
1857
Peter Collingbournee190dee2011-03-11 19:24:49 +00001858 case Stmt::UnaryExprOrTypeTraitExprClass:
1859 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1860 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Ted Kremenek93668002009-07-17 22:18:43 +00001862 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001863 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001864
Ted Kremenek93668002009-07-17 22:18:43 +00001865 case Stmt::SwitchStmtClass:
1866 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001867
Zhanyong Wan6dace612010-11-22 08:45:56 +00001868 case Stmt::UnaryOperatorClass:
1869 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1870
Ted Kremenek93668002009-07-17 22:18:43 +00001871 case Stmt::WhileStmtClass:
1872 return VisitWhileStmt(cast<WhileStmt>(S));
1873 }
1874}
Mike Stump11289f42009-09-09 15:08:12 +00001875
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001876CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001877 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001878 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001879 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001880 }
Mike Stump11289f42009-09-09 15:08:12 +00001881
Ted Kremenek93668002009-07-17 22:18:43 +00001882 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001883}
Mike Stump31feda52009-07-17 01:31:16 +00001884
Ted Kremenek93668002009-07-17 22:18:43 +00001885/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001886CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1887 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001888
Ted Kremenek8ae67872013-02-05 22:00:19 +00001889 // Visit the children in their reverse order so that they appear in
1890 // left-to-right (natural) order in the CFG.
1891 reverse_children RChildren(S);
1892 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1893 I != E; ++I) {
1894 if (Stmt *Child = *I)
1895 if (CFGBlock *R = Visit(Child))
1896 B = R;
1897 }
1898 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001899}
Mike Stump11289f42009-09-09 15:08:12 +00001900
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001901CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1902 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001903 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001904
Ted Kremenek7c58d352011-03-10 01:14:11 +00001905 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001906 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001907 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001908 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001909
Ted Kremenek9aae5132007-08-23 21:42:29 +00001910 return Block;
1911}
Mike Stump11289f42009-09-09 15:08:12 +00001912
Zhanyong Wan6dace612010-11-22 08:45:56 +00001913CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001914 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001915 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001916 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001917 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001918 }
1919
Ted Kremenek8219b822010-12-16 07:46:53 +00001920 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001921}
1922
Ted Kremeneka16436f2012-07-14 05:04:06 +00001923CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1924 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1925 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001926
Ted Kremeneka16436f2012-07-14 05:04:06 +00001927 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001928 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001929
Craig Topper25542942014-05-20 04:30:07 +00001930 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1931 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001932}
1933
1934std::pair<CFGBlock*, CFGBlock*>
1935CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1936 Stmt *Term,
1937 CFGBlock *TrueBlock,
1938 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00001939 // Introspect the RHS. If it is a nested logical operation, we recursively
1940 // build the CFG using this function. Otherwise, resort to default
1941 // CFG construction behavior.
1942 Expr *RHS = B->getRHS()->IgnoreParens();
1943 CFGBlock *RHSBlock, *ExitBlock;
1944
1945 do {
1946 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1947 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001948 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001949 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1950 break;
1951 }
1952
1953 // The RHS is not a nested logical operation. Don't push the terminator
1954 // down further, but instead visit RHS and construct the respective
1955 // pieces of the CFG, and link up the RHSBlock with the terminator
1956 // we have been provided.
1957 ExitBlock = RHSBlock = createBlock(false);
1958
Richard Trieu6a6af522017-01-04 00:46:30 +00001959 // Even though KnownVal is only used in the else branch of the next
1960 // conditional, tryEvaluateBool performs additional checking on the
1961 // Expr, so it should be called unconditionally.
1962 TryResult KnownVal = tryEvaluateBool(RHS);
1963 if (!KnownVal.isKnown())
1964 KnownVal = tryEvaluateBool(B);
1965
Ted Kremenekb50e7162012-07-14 05:04:10 +00001966 if (!Term) {
1967 assert(TrueBlock == FalseBlock);
1968 addSuccessor(RHSBlock, TrueBlock);
1969 }
1970 else {
1971 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00001972 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1973 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001974 }
1975
1976 Block = RHSBlock;
1977 RHSBlock = addStmt(RHS);
1978 }
1979 while (false);
1980
1981 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001982 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001983
1984 // Generate the blocks for evaluating the LHS.
1985 Expr *LHS = B->getLHS()->IgnoreParens();
1986
1987 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1988 if (B_LHS->isLogicalOp()) {
1989 if (B->getOpcode() == BO_LOr)
1990 FalseBlock = RHSBlock;
1991 else
1992 TrueBlock = RHSBlock;
1993
1994 // For the LHS, treat 'B' as the terminator that we want to sink
1995 // into the nested branch. The RHS always gets the top-most
1996 // terminator.
1997 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1998 }
1999
2000 // Create the block evaluating the LHS.
2001 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002002 CFGBlock *LHSBlock = createBlock(false);
2003 LHSBlock->setTerminator(B);
2004
Ted Kremeneka16436f2012-07-14 05:04:06 +00002005 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002006 CFGBlock *EntryLHSBlock = addStmt(LHS);
2007
2008 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002009 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002010
2011 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002012 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002013
2014 // Now link the LHSBlock with RHSBlock.
2015 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002016 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2017 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002018 } else {
2019 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002020 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2021 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002022 }
2023
Ted Kremenekb50e7162012-07-14 05:04:10 +00002024 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002025}
2026
2027CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2028 AddStmtChoice asc) {
2029 // && or ||
2030 if (B->isLogicalOp())
2031 return VisitLogicalOperator(B);
2032
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002033 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002034 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002035 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002036 addStmt(B->getRHS());
2037 return addStmt(B->getLHS());
2038 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002039
2040 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002041 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002042 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002043 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002044 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002045 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002046 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002047 }
Mike Stump11289f42009-09-09 15:08:12 +00002048
Ted Kremenek7c58d352011-03-10 01:14:11 +00002049 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002050 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002051 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002052 }
2053
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002054 CFGBlock *RBlock = Visit(B->getRHS());
2055 CFGBlock *LBlock = Visit(B->getLHS());
2056 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2057 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2058 // return RBlock. Otherwise we'll incorrectly return NULL.
2059 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002060}
2061
Ted Kremeneke2499842012-04-12 20:03:44 +00002062CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002063 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002064 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002065 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002066 }
2067 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002068}
2069
Ted Kremenek93668002009-07-17 22:18:43 +00002070CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2071 // "break" is a control-flow statement. Thus we stop processing the current
2072 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002073 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002074 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002075
Ted Kremenek93668002009-07-17 22:18:43 +00002076 // Now create a new block that ends with the break statement.
2077 Block = createBlock(false);
2078 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenek93668002009-07-17 22:18:43 +00002080 // If there is no target for the break, then we are looking at an incomplete
2081 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002082 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002083 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002084 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002085 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002086 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002087
Ted Kremenek9aae5132007-08-23 21:42:29 +00002088 return Block;
2089}
Mike Stump11289f42009-09-09 15:08:12 +00002090
Sebastian Redl31ad7542011-03-13 17:09:40 +00002091static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002092 QualType Ty = E->getType();
2093 if (Ty->isFunctionPointerType())
2094 Ty = Ty->getAs<PointerType>()->getPointeeType();
2095 else if (Ty->isBlockPointerType())
2096 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002097
Mike Stump04c68512010-01-21 15:20:48 +00002098 const FunctionType *FT = Ty->getAs<FunctionType>();
2099 if (FT) {
2100 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002101 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00002102 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00002103 return false;
2104 }
2105 return true;
2106}
2107
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002108CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002109 // Compute the callee type.
2110 QualType calleeType = C->getCallee()->getType();
2111 if (calleeType == Context->BoundMemberTy) {
2112 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2113
2114 // We should only get a null bound type if processing a dependent
2115 // CFG. Recover by assuming nothing.
2116 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002117 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002118
John McCallc67067f2011-05-11 07:19:11 +00002119 // If this is a call to a no-return function, this stops the block here.
2120 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2121
Mike Stump04c68512010-01-21 15:20:48 +00002122 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002123
2124 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002125 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002126 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002127 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002128 }
2129
Jordan Rose5374c072013-08-19 16:27:28 +00002130 // If this is a call to a builtin function, it might not actually evaluate
2131 // its arguments. Don't add them to the CFG if this is the case.
2132 bool OmitArguments = false;
2133
Mike Stump92244b02010-01-19 22:00:14 +00002134 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00002135 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00002136 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002137 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002138 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00002139 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2140 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002141 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002142
Sebastian Redl31ad7542011-03-13 17:09:40 +00002143 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002144 AddEHEdge = false;
2145
Jordan Rose5374c072013-08-19 16:27:28 +00002146 if (OmitArguments) {
2147 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2148 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2149 autoCreateBlock();
2150 appendStmt(Block, C);
2151 return Visit(C->getCallee());
2152 }
2153
2154 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002155 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00002156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Mike Stump92244b02010-01-19 22:00:14 +00002158 if (Block) {
2159 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002160 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002161 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002162 }
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chandler Carrutha70991b2011-09-13 09:13:49 +00002164 if (NoReturn)
2165 Block = createNoReturnBlock();
2166 else
2167 Block = createBlock();
2168
Ted Kremenek2866bab2011-03-10 01:14:08 +00002169 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002170
Mike Stump04c68512010-01-21 15:20:48 +00002171 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002172 // Add exceptional edges.
2173 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002174 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002175 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002176 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Mike Stump8c5d7992009-07-25 21:26:53 +00002179 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002180}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002181
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002182CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2183 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002184 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002185 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002186 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002187 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002188
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002189 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002190 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002191 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002192 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002193 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002194 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002195
Ted Kremenek21822592009-07-17 18:20:32 +00002196 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002197 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002198 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002199 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002200 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002201
Ted Kremenek21822592009-07-17 18:20:32 +00002202 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002203 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002204 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002205 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2206 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002207 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002208 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002209}
Mike Stump11289f42009-09-09 15:08:12 +00002210
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002211CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002212 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002213 addLocalScopeForStmt(C);
2214
Matthias Gehre09a134e2015-11-14 00:36:50 +00002215 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002216 // If the body ends with a ReturnStmt, the dtors will be added in
2217 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002218 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002219 }
2220
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002221 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002222
2223 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2224 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002225 // If we hit a segment of code just containing ';' (NullStmts), we can
2226 // get a null block back. In such cases, just use the LastBlock
2227 if (CFGBlock *newBlock = addStmt(*I))
2228 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002229
Ted Kremenekce499c22009-08-27 23:16:26 +00002230 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002231 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002232 }
Mike Stump92244b02010-01-19 22:00:14 +00002233
Ted Kremenek93668002009-07-17 22:18:43 +00002234 return LastBlock;
2235}
Mike Stump11289f42009-09-09 15:08:12 +00002236
John McCallc07a0c72011-02-17 10:25:35 +00002237CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002238 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002239 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002240 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002241
Ted Kremenek51d40b02009-07-17 18:15:54 +00002242 // Create the confluence block that will "merge" the results of the ternary
2243 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002244 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002245 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002246 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002247 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002248
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002249 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002250
Ted Kremenek51d40b02009-07-17 18:15:54 +00002251 // Create a block for the LHS expression if there is an LHS expression. A
2252 // GCC extension allows LHS to be NULL, causing the condition to be the
2253 // value that is returned instead.
2254 // e.g: x ?: y is shorthand for: x ? x : y;
2255 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002256 Block = nullptr;
2257 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002258 const Expr *trueExpr = C->getTrueExpr();
2259 if (trueExpr != opaqueValue) {
2260 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002261 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002262 return nullptr;
2263 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002264 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002265 else
2266 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Ted Kremenek51d40b02009-07-17 18:15:54 +00002268 // Create the block for the RHS expression.
2269 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002270 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002271 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002272 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002273
Richard Smithf676e452012-07-24 21:02:14 +00002274 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2275 if (BinaryOperator *Cond =
2276 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2277 if (Cond->isLogicalOp())
2278 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2279
Ted Kremenek51d40b02009-07-17 18:15:54 +00002280 // Create the block that will contain the condition.
2281 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002282
Mike Stump773582d2009-07-23 23:25:26 +00002283 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002284 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002285 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2286 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002287 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002288 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002289
Ted Kremenekd8138012011-02-24 03:09:15 +00002290 if (opaqueValue) {
2291 // Run the condition expression if it's not trivially expressed in
2292 // terms of the opaque value (or if there is no opaque value).
2293 if (condExpr != opaqueValue)
2294 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002295
Ted Kremenekd8138012011-02-24 03:09:15 +00002296 // Before that, run the common subexpression if there was one.
2297 // At least one of this or the above will be run.
2298 return addStmt(BCO->getCommon());
2299 }
2300
2301 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002302}
2303
Ted Kremenek93668002009-07-17 22:18:43 +00002304CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002305 // Check if the Decl is for an __label__. If so, elide it from the
2306 // CFG entirely.
2307 if (isa<LabelDecl>(*DS->decl_begin()))
2308 return Block;
2309
Ted Kremenek3a601142011-05-24 20:41:31 +00002310 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002311 if (DS->isSingleDecl())
2312 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002313
Craig Topper25542942014-05-20 04:30:07 +00002314 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002315
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002316 // Build an individual DeclStmt for each decl.
2317 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2318 E = DS->decl_rend();
2319 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002320 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
Benjamin Kramerc3f89252016-10-20 14:27:22 +00002321 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002322
Ted Kremenek93668002009-07-17 22:18:43 +00002323 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2324 // automatically freed with the CFG.
2325 DeclGroupRef DG(*I);
2326 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002327 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002328 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002329 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002330
Ted Kremenek93668002009-07-17 22:18:43 +00002331 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002332 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
2335 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002336}
Mike Stump11289f42009-09-09 15:08:12 +00002337
Ted Kremenek93668002009-07-17 22:18:43 +00002338/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002339/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002340CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002341 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002342 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002343
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002344 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002345 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2346 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002347 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002350 bool HasTemporaries = false;
2351
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002352 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002353 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002354
2355 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2356 // For static variables, we need to create a branch to track
2357 // whether or not they are initialized.
2358 if (Block) {
2359 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002360 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002361 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002362 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002363 }
2364 blockAfterStaticInit = Succ;
2365 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002366
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002367 // Destructors of temporaries in initialization expression should be called
2368 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002369 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002370 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002371 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002372
Jordan Rose6d671cc2012-09-05 22:55:23 +00002373 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002374 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002375 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002376 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2377 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002378 }
2379 }
2380
2381 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002382 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002383
2384 EnterConstructionContextIfNecessary(DS, Init);
2385
Ted Kremenek213d0532012-03-22 05:57:43 +00002386 // Keep track of the last non-null block, as 'Block' can be nulled out
2387 // if the initializer expression is something like a 'while' in a
2388 // statement-expression.
2389 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Ted Kremenek93668002009-07-17 22:18:43 +00002391 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002392 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002393 // For expression with temporaries go directly to subexpression to omit
2394 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002395 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2396 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2397 LastBlock = newBlock;
2398 }
2399 else {
2400 if (CFGBlock *newBlock = Visit(Init))
2401 LastBlock = newBlock;
2402 }
Ted Kremenek93668002009-07-17 22:18:43 +00002403 }
Mike Stump11289f42009-09-09 15:08:12 +00002404
Ted Kremenek93668002009-07-17 22:18:43 +00002405 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002406 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002407 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002408 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2409 LastBlock = newBlock;
2410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002412 // Remove variable from local scope.
2413 if (ScopePos && VD == *ScopePos)
2414 ++ScopePos;
2415
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002416 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002417 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002418 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002419 Block = createBlock(false);
2420 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002421 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002422 addSuccessor(Block, B);
2423 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002424 }
2425
2426 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002427}
2428
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002429CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002430 // We may see an if statement in the middle of a basic block, or it may be the
2431 // first statement we are processing. In either case, we create a new basic
2432 // block. First, we create the blocks for the then...else statements, and
2433 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002434 // middle of a block, we stop processing that block. That block is then the
2435 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002436
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002437 // Save local scope position because in case of condition variable ScopePos
2438 // won't be restored when traversing AST.
2439 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2440
Richard Smitha547eb22016-07-14 00:11:03 +00002441 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002442 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002443 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002444
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002445 // Create local scope for possible condition variable.
2446 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002447 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002448 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002449
Matthias Gehre351c2182017-07-12 07:04:19 +00002450 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002451
Chris Lattner57540c52011-04-15 05:22:18 +00002452 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002453 // block.
2454 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002455 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002456 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002457 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002458 }
Mike Stump31feda52009-07-17 01:31:16 +00002459
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002460 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002461 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002462
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002463 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002464 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002465
Ted Kremenek9aae5132007-08-23 21:42:29 +00002466 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002467 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002468 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002469
2470 // If branch is not a compound statement create implicit scope
2471 // and add destructors.
2472 if (!isa<CompoundStmt>(Else))
2473 addLocalScopeAndDtors(Else);
2474
Ted Kremenek93668002009-07-17 22:18:43 +00002475 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002476
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002477 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2478 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002479 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002480 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002481 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002482 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002483 }
Mike Stump31feda52009-07-17 01:31:16 +00002484
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002485 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002486 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002487 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002488 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002489 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002490 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002491 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002492
2493 // If branch is not a compound statement create implicit scope
2494 // and add destructors.
2495 if (!isa<CompoundStmt>(Then))
2496 addLocalScopeAndDtors(Then);
2497
Ted Kremenek93668002009-07-17 22:18:43 +00002498 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002499
Ted Kremenek1b379512009-04-01 03:52:47 +00002500 if (!ThenBlock) {
2501 // We can reach here if the "then" body has all NullStmts.
2502 // Create an empty block so we can distinguish between true and false
2503 // branches in path-sensitive analyses.
2504 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002505 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002506 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002507 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002508 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002509 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002510 }
2511
Ted Kremenekb50e7162012-07-14 05:04:10 +00002512 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2513 // having these handle the actual control-flow jump. Note that
2514 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2515 // we resort to the old control-flow behavior. This special handling
2516 // removes infeasible paths from the control-flow graph by having the
2517 // control-flow transfer of '&&' or '||' go directly into the then/else
2518 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002519 BinaryOperator *Cond =
2520 I->getConditionVariable()
2521 ? nullptr
2522 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2523 CFGBlock *LastBlock;
2524 if (Cond && Cond->isLogicalOp())
2525 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2526 else {
2527 // Now create a new block containing the if statement.
2528 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002529
Richard Smith509bbd12017-01-13 22:16:41 +00002530 // Set the terminator of the new block to the If statement.
2531 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002532
Richard Smith509bbd12017-01-13 22:16:41 +00002533 // See if this is a known constant.
2534 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002535
Richard Smith509bbd12017-01-13 22:16:41 +00002536 // Add the successors. If we know that specific branches are
2537 // unreachable, inform addSuccessor() of that knowledge.
2538 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2539 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002540
Richard Smith509bbd12017-01-13 22:16:41 +00002541 // Add the condition as the last statement in the new block. This may
2542 // create new blocks as the condition may contain control-flow. Any newly
2543 // created blocks will be pointed to be "Block".
2544 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002545
Richard Smith509bbd12017-01-13 22:16:41 +00002546 // If the IfStmt contains a condition variable, add it and its
2547 // initializer to the CFG.
2548 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2549 autoCreateBlock();
2550 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2551 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002552 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002553
Richard Smitha547eb22016-07-14 00:11:03 +00002554 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2555 if (Stmt *Init = I->getInit()) {
2556 autoCreateBlock();
2557 LastBlock = addStmt(Init);
2558 }
2559
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002560 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002561}
Mike Stump31feda52009-07-17 01:31:16 +00002562
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002563CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002564 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002565 //
Mike Stump31feda52009-07-17 01:31:16 +00002566 // NOTE: If a "return" appears in the middle of a block, this means that the
2567 // code afterwards is DEAD (unreachable). We still keep a basic block
2568 // for that code; a simple "mark-and-sweep" from the entry block will be
2569 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002570
2571 // Create the new block.
2572 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002573
Matthias Gehre351c2182017-07-12 07:04:19 +00002574 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002575
2576 // If the one of the destructors does not return, we already have the Exit
2577 // block as a successor.
2578 if (!Block->hasNoReturnElement())
2579 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002580
2581 // Add the return statement to the block. This may create new blocks if R
2582 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002583 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002584}
2585
Nico Weber699670e2017-08-23 15:33:16 +00002586CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2587 // SEHExceptStmt are treated like labels, so they are the first statement in a
2588 // block.
2589
2590 // Save local scope position because in case of exception variable ScopePos
2591 // won't be restored when traversing AST.
2592 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2593
2594 addStmt(ES->getBlock());
2595 CFGBlock *SEHExceptBlock = Block;
2596 if (!SEHExceptBlock)
2597 SEHExceptBlock = createBlock();
2598
2599 appendStmt(SEHExceptBlock, ES);
2600
2601 // Also add the SEHExceptBlock as a label, like with regular labels.
2602 SEHExceptBlock->setLabel(ES);
2603
2604 // Bail out if the CFG is bad.
2605 if (badCFG)
2606 return nullptr;
2607
2608 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2609 Block = nullptr;
2610
2611 return SEHExceptBlock;
2612}
2613
2614CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2615 return VisitCompoundStmt(FS->getBlock());
2616}
2617
2618CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2619 // "__leave" is a control-flow statement. Thus we stop processing the current
2620 // block.
2621 if (badCFG)
2622 return nullptr;
2623
2624 // Now create a new block that ends with the __leave statement.
2625 Block = createBlock(false);
2626 Block->setTerminator(LS);
2627
2628 // If there is no target for the __leave, then we are looking at an incomplete
2629 // AST. This means that the CFG cannot be constructed.
2630 if (SEHLeaveJumpTarget.block) {
2631 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2632 addSuccessor(Block, SEHLeaveJumpTarget.block);
2633 } else
2634 badCFG = true;
2635
2636 return Block;
2637}
2638
2639CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2640 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2641 // processing the current block.
2642 CFGBlock *SEHTrySuccessor = nullptr;
2643
2644 if (Block) {
2645 if (badCFG)
2646 return nullptr;
2647 SEHTrySuccessor = Block;
2648 } else SEHTrySuccessor = Succ;
2649
2650 // FIXME: Implement __finally support.
2651 if (Terminator->getFinallyHandler())
2652 return NYS();
2653
2654 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2655
2656 // Create a new block that will contain the __try statement.
2657 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2658
2659 // Add the terminator in the __try block.
2660 NewTryTerminatedBlock->setTerminator(Terminator);
2661
2662 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2663 // The code after the try is the implicit successor if there's an __except.
2664 Succ = SEHTrySuccessor;
2665 Block = nullptr;
2666 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2667 if (!ExceptBlock)
2668 return nullptr;
2669 // Add this block to the list of successors for the block with the try
2670 // statement.
2671 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2672 }
2673 if (PrevSEHTryTerminatedBlock)
2674 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2675 else
2676 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2677
2678 // The code after the try is the implicit successor.
2679 Succ = SEHTrySuccessor;
2680
2681 // Save the current "__try" context.
2682 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
2683 NewTryTerminatedBlock);
2684 cfg->addTryDispatchBlock(TryTerminatedBlock);
2685
2686 // Save the current value for the __leave target.
2687 // All __leaves should go to the code following the __try
2688 // (FIXME: or if the __try has a __finally, to the __finally.)
2689 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
2690 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
2691
2692 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
2693 Block = nullptr;
2694 return addStmt(Terminator->getTryBlock());
2695}
2696
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002697CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002698 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002699 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002700 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002701
Ted Kremenek93668002009-07-17 22:18:43 +00002702 if (!LabelBlock) // This can happen when the body is empty, i.e.
2703 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002704
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002705 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2706 "label already in map");
2707 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002708
2709 // Labels partition blocks, so this is the end of the basic block we were
2710 // processing (L is the block's label). Because this is label (and we have
2711 // already processed the substatement) there is no extra control-flow to worry
2712 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002713 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002714 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002715 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002716
2717 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002718 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002719
Ted Kremenek9aae5132007-08-23 21:42:29 +00002720 // This block is now the implicit successor of other blocks.
2721 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002722
Ted Kremenek9aae5132007-08-23 21:42:29 +00002723 return LabelBlock;
2724}
2725
Devin Coughlinb6029b72015-11-25 22:35:37 +00002726CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2727 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2728 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2729 if (Expr *CopyExpr = CI.getCopyExpr()) {
2730 CFGBlock *Tmp = Visit(CopyExpr);
2731 if (Tmp)
2732 LastBlock = Tmp;
2733 }
2734 }
2735 return LastBlock;
2736}
2737
Ted Kremenekda76a942012-04-12 20:34:52 +00002738CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2739 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2740 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2741 et = E->capture_init_end(); it != et; ++it) {
2742 if (Expr *Init = *it) {
2743 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002744 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002745 LastBlock = Tmp;
2746 }
2747 }
2748 return LastBlock;
2749}
2750
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002751CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002752 // Goto is a control-flow statement. Thus we stop processing the current
2753 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002754
Ted Kremenek9aae5132007-08-23 21:42:29 +00002755 Block = createBlock(false);
2756 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002757
2758 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002759 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002760
Ted Kremenek9aae5132007-08-23 21:42:29 +00002761 if (I == LabelMap.end())
2762 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002763 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2764 else {
2765 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00002766 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002767 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002768 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002769
Mike Stump31feda52009-07-17 01:31:16 +00002770 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002771}
2772
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002773CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002774 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002775
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002776 // Save local scope position because in case of condition variable ScopePos
2777 // won't be restored when traversing AST.
2778 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2779
2780 // Create local scope for init statement and possible condition variable.
2781 // Add destructor for init statement and condition variable.
2782 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002783 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002784 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002785 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2786
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002787 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002788 addLocalScopeForVarDecl(VD);
2789 LocalScope::const_iterator ContinueScopePos = ScopePos;
2790
Matthias Gehre351c2182017-07-12 07:04:19 +00002791 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002792
Peter Szecsi999a25f2017-08-19 11:19:16 +00002793 addLoopExit(F);
2794
Mike Stump014b3ea2009-07-21 01:12:51 +00002795 // "for" is a control-flow statement. Thus we stop processing the current
2796 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002797 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002798 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002799 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002800 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002801 } else
2802 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002803
Ted Kremenek304a9532010-05-21 20:30:15 +00002804 // Save the current value for the break targets.
2805 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002806 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002807 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002808
Craig Topper25542942014-05-20 04:30:07 +00002809 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002810
Ted Kremenek9aae5132007-08-23 21:42:29 +00002811 // Now create the loop body.
2812 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002813 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002814
Ted Kremenekb50e7162012-07-14 05:04:10 +00002815 // Save the current values for Block, Succ, continue and break targets.
2816 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2817 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002818
Ted Kremenekb50e7162012-07-14 05:04:10 +00002819 // Create an empty block to represent the transition block for looping back
2820 // to the head of the loop. If we have increment code, it will
2821 // go in this block as well.
2822 Block = Succ = TransitionBlock = createBlock(false);
2823 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002824
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002825 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002826 // Generate increment code in its own basic block. This is the target of
2827 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002828 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002829 }
Mike Stump31feda52009-07-17 01:31:16 +00002830
Ted Kremenek902393b2009-04-28 00:51:56 +00002831 // Finish up the increment (or empty) block if it hasn't been already.
2832 if (Block) {
2833 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002834 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002835 return nullptr;
2836 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002837 }
Mike Stump31feda52009-07-17 01:31:16 +00002838
Ted Kremenekb50e7162012-07-14 05:04:10 +00002839 // The starting block for the loop increment is the block that should
2840 // represent the 'loop target' for looping back to the start of the loop.
2841 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2842 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002843
Ted Kremenekb50e7162012-07-14 05:04:10 +00002844 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00002845 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002846
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002847 // If body is not a compound statement create implicit scope
2848 // and add destructors.
2849 if (!isa<CompoundStmt>(F->getBody()))
2850 addLocalScopeAndDtors(F->getBody());
2851
Mike Stump31feda52009-07-17 01:31:16 +00002852 // Now populate the body block, and in the process create new blocks as we
2853 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002854 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002855
Ted Kremenekb50e7162012-07-14 05:04:10 +00002856 if (!BodyBlock) {
2857 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2858 // Use the continue jump target as the proxy for the body.
2859 BodyBlock = ContinueJumpTarget.block;
2860 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002861 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002862 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002863 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002864
2865 // Because of short-circuit evaluation, the condition of the loop can span
2866 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2867 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002868 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002869
Ted Kremenekb50e7162012-07-14 05:04:10 +00002870 do {
2871 Expr *C = F->getCond();
2872
2873 // Specially handle logical operators, which have a slightly
2874 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002875 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002876 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002877 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002878 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002879 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2880 break;
2881 }
2882
2883 // The default case when not handling logical operators.
2884 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2885 ExitConditionBlock->setTerminator(F);
2886
2887 // See if this is a known constant.
2888 TryResult KnownVal(true);
2889
2890 if (C) {
2891 // Now add the actual condition to the condition block.
2892 // Because the condition itself may contain control-flow, new blocks may
2893 // be created. Thus we update "Succ" after adding the condition.
2894 Block = ExitConditionBlock;
2895 EntryConditionBlock = addStmt(C);
2896
2897 // If this block contains a condition variable, add both the condition
2898 // variable and initializer to the CFG.
2899 if (VarDecl *VD = F->getConditionVariable()) {
2900 if (Expr *Init = VD->getInit()) {
2901 autoCreateBlock();
2902 appendStmt(Block, F->getConditionVariableDeclStmt());
2903 EntryConditionBlock = addStmt(Init);
2904 assert(Block == EntryConditionBlock);
2905 }
2906 }
2907
2908 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002909 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002910
2911 KnownVal = tryEvaluateBool(C);
2912 }
2913
2914 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002915 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002916 // Link up the condition block with the code that follows the loop. (the
2917 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002918 addSuccessor(ExitConditionBlock,
2919 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002920 } while (false);
2921
2922 // Link up the loop-back block to the entry condition block.
2923 addSuccessor(TransitionBlock, EntryConditionBlock);
2924
2925 // The condition block is the implicit successor for any code above the loop.
2926 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002927
Ted Kremenek9aae5132007-08-23 21:42:29 +00002928 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002929 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002930 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002931 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002932 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002933 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002934
2935 // There is no loop initialization. We are thus basically a while loop.
2936 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002937 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002938 Succ = EntryConditionBlock;
2939 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002940}
2941
Ted Kremenek5868ec62010-04-11 17:02:10 +00002942CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002943 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002944 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002945 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002946 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002947 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002948}
2949
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002950CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002951 // Objective-C fast enumeration 'for' statements:
2952 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2953 //
2954 // for ( Type newVariable in collection_expression ) { statements }
2955 //
2956 // becomes:
2957 //
2958 // prologue:
2959 // 1. collection_expression
2960 // T. jump to loop_entry
2961 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002962 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002963 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2964 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2965 // TB:
2966 // statements
2967 // T. jump to loop_entry
2968 // FB:
2969 // what comes after
2970 //
2971 // and
2972 //
2973 // Type existingItem;
2974 // for ( existingItem in expression ) { statements }
2975 //
2976 // becomes:
2977 //
Mike Stump31feda52009-07-17 01:31:16 +00002978 // the same with newVariable replaced with existingItem; the binding works
2979 // the same except that for one ObjCForCollectionStmt::getElement() returns
2980 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00002981
Craig Topper25542942014-05-20 04:30:07 +00002982 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002983
Ted Kremenek9d56e642008-11-11 17:10:00 +00002984 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002985 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002986 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002987 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002988 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002989 } else
2990 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002991
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002992 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002993 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002994
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002995 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002996 ExitConditionBlock->setTerminator(S);
2997
2998 // The last statement in the block should be the ObjCForCollectionStmt, which
2999 // performs the actual binding to 'element' and determines if there are any
3000 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003001 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003002 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003003
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003004 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003005 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003006 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003007 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3008 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003009 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003010 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003011 return nullptr;
3012 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003013 }
Mike Stump31feda52009-07-17 01:31:16 +00003014
3015 // The condition block is the implicit successor for the loop body as well as
3016 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003017 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003018
Ted Kremenek9d56e642008-11-11 17:10:00 +00003019 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003020 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003021 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003022 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003023 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003024 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003025
Anna Zaks56b49752013-06-22 00:23:20 +00003026 // Add an intermediate block between the BodyBlock and the
3027 // EntryConditionBlock to represent the "loop back" transition, for looping
3028 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003029 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003030 Succ = LoopBackBlock = createBlock();
3031 LoopBackBlock->setLoopTarget(S);
3032
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003033 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003034 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003035
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003036 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003037
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003038 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003039 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003040 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003041 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003042 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003043 }
Mike Stump31feda52009-07-17 01:31:16 +00003044
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003045 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003046 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003047 }
Mike Stump31feda52009-07-17 01:31:16 +00003048
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003049 // Link up the condition block with the code that follows the loop.
3050 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003051 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003052
Ted Kremenek9d56e642008-11-11 17:10:00 +00003053 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003054 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003055 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003056}
3057
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003058CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3059 // Inline the body.
3060 return addStmt(S->getSubStmt());
3061 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3062}
3063
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003064CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003065 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003066
Ted Kremenek49805452009-05-02 01:49:13 +00003067 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003068 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003069
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003070 // The sync body starts its own basic block. This makes it a little easier
3071 // for diagnostic clients.
3072 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003073 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003074 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003075
Craig Topper25542942014-05-20 04:30:07 +00003076 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003077 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003078 }
Mike Stump31feda52009-07-17 01:31:16 +00003079
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003080 // Add the @synchronized to the CFG.
3081 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003082 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003083
Ted Kremenek49805452009-05-02 01:49:13 +00003084 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003085 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003086}
Mike Stump31feda52009-07-17 01:31:16 +00003087
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003088CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003089 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003090 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003091}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003092
John McCallfe96e0b2011-11-06 09:01:30 +00003093CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3094 autoCreateBlock();
3095
3096 // Add the PseudoObject as the last thing.
3097 appendStmt(Block, E);
3098
3099 CFGBlock *lastBlock = Block;
3100
3101 // Before that, evaluate all of the semantics in order. In
3102 // CFG-land, that means appending them in reverse order.
3103 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3104 Expr *Semantic = E->getSemanticExpr(--i);
3105
3106 // If the semantic is an opaque value, we're being asked to bind
3107 // it to its source expression.
3108 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3109 Semantic = OVE->getSourceExpr();
3110
3111 if (CFGBlock *B = Visit(Semantic))
3112 lastBlock = B;
3113 }
3114
3115 return lastBlock;
3116}
3117
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003118CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003119 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003120
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003121 // Save local scope position because in case of condition variable ScopePos
3122 // won't be restored when traversing AST.
3123 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3124
3125 // Create local scope for possible condition variable.
3126 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003127 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003128 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003129 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003130 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003131 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003132 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003133
Mike Stump014b3ea2009-07-21 01:12:51 +00003134 // "while" is a control-flow statement. Thus we stop processing the current
3135 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003136 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003137 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003138 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003139 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003140 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003141 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003142 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003143 }
Mike Stump31feda52009-07-17 01:31:16 +00003144
Craig Topper25542942014-05-20 04:30:07 +00003145 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003146
Ted Kremenek9aae5132007-08-23 21:42:29 +00003147 // Process the loop body.
3148 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003149 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003150
Ted Kremenekb50e7162012-07-14 05:04:10 +00003151 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003152 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3153 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003154 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003155
Mike Stump31feda52009-07-17 01:31:16 +00003156 // Create an empty block to represent the transition block for looping back
3157 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003158 Succ = TransitionBlock = createBlock(false);
3159 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003160 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003161
Ted Kremenek9aae5132007-08-23 21:42:29 +00003162 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003163 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003164
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003165 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003166 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003167
3168 // If body is not a compound statement create implicit scope
3169 // and add destructors.
3170 if (!isa<CompoundStmt>(W->getBody()))
3171 addLocalScopeAndDtors(W->getBody());
3172
Ted Kremenek9aae5132007-08-23 21:42:29 +00003173 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003174 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003175
Ted Kremeneke9610502007-08-30 18:39:40 +00003176 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003177 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003178 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003179 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003180 }
3181
3182 // Because of short-circuit evaluation, the condition of the loop can span
3183 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3184 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003185 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003186
3187 do {
3188 Expr *C = W->getCond();
3189
3190 // Specially handle logical operators, which have a slightly
3191 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003192 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003193 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003194 std::tie(EntryConditionBlock, ExitConditionBlock) =
3195 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003196 break;
3197 }
3198
3199 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003200 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003201 ExitConditionBlock->setTerminator(W);
3202
3203 // Now add the actual condition to the condition block.
3204 // Because the condition itself may contain control-flow, new blocks may
3205 // be created. Thus we update "Succ" after adding the condition.
3206 Block = ExitConditionBlock;
3207 Block = EntryConditionBlock = addStmt(C);
3208
3209 // If this block contains a condition variable, add both the condition
3210 // variable and initializer to the CFG.
3211 if (VarDecl *VD = W->getConditionVariable()) {
3212 if (Expr *Init = VD->getInit()) {
3213 autoCreateBlock();
3214 appendStmt(Block, W->getConditionVariableDeclStmt());
3215 EntryConditionBlock = addStmt(Init);
3216 assert(Block == EntryConditionBlock);
3217 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003218 }
Mike Stump31feda52009-07-17 01:31:16 +00003219
Ted Kremenekb50e7162012-07-14 05:04:10 +00003220 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003221 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003222
3223 // See if this is a known constant.
3224 const TryResult& KnownVal = tryEvaluateBool(C);
3225
Ted Kremenek30754282009-07-24 04:47:11 +00003226 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003227 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003228 // Link up the condition block with the code that follows the loop. (the
3229 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003230 addSuccessor(ExitConditionBlock,
3231 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003232 } while(false);
3233
3234 // Link up the loop-back block to the entry condition block.
3235 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003236
3237 // There can be no more statements in the condition block since we loop back
3238 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003239 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003240
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003241 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003242 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003243 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003244}
Mike Stump11289f42009-09-09 15:08:12 +00003245
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003246CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003247 // FIXME: For now we pretend that @catch and the code it contains does not
3248 // exit.
3249 return Block;
3250}
Mike Stump31feda52009-07-17 01:31:16 +00003251
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003252CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003253 // FIXME: This isn't complete. We basically treat @throw like a return
3254 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003255
Ted Kremenek0868eea2009-09-24 18:45:41 +00003256 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003257 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003258 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003259
Ted Kremenek93041ba2008-12-09 20:20:09 +00003260 // Create the new block.
3261 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003262
Ted Kremenek93041ba2008-12-09 20:20:09 +00003263 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003264 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003265
3266 // Add the statement to the block. This may create new blocks if S contains
3267 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003268 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003269}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003270
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003271CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003272 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003273 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003274 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003275
3276 // Create the new block.
3277 Block = createBlock(false);
3278
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003279 if (TryTerminatedBlock)
3280 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003281 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003282 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003283 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003284 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003285
3286 // Add the statement to the block. This may create new blocks if S contains
3287 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003288 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003289}
3290
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003291CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003292 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003293
Peter Szecsi999a25f2017-08-19 11:19:16 +00003294 addLoopExit(D);
3295
Mike Stump8d50b6a2009-07-21 01:27:50 +00003296 // "do...while" is a control-flow statement. Thus we stop processing the
3297 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003298 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003299 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003300 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003301 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003302 } else
3303 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003304
3305 // Because of short-circuit evaluation, the condition of the loop can span
3306 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3307 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003308 CFGBlock *ExitConditionBlock = createBlock(false);
3309 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003310
Ted Kremenek81e14852007-08-27 19:46:09 +00003311 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003312 ExitConditionBlock->setTerminator(D);
3313
3314 // Now add the actual condition to the condition block. Because the condition
3315 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003316 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003317 Block = ExitConditionBlock;
3318 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003319 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003320 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003321 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003322 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003323 }
Mike Stump31feda52009-07-17 01:31:16 +00003324
Ted Kremeneka1523a32008-02-27 07:20:00 +00003325 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003326 Succ = EntryConditionBlock;
3327
Mike Stump773582d2009-07-23 23:25:26 +00003328 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003329 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003330
Ted Kremenek9aae5132007-08-23 21:42:29 +00003331 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003332 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003333 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003334 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003335
Ted Kremenek9aae5132007-08-23 21:42:29 +00003336 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003337 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3338 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3339 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003340
Ted Kremenek9aae5132007-08-23 21:42:29 +00003341 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003342 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003343
Ted Kremenek9aae5132007-08-23 21:42:29 +00003344 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003345 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003346
Ted Kremenek9aae5132007-08-23 21:42:29 +00003347 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003348 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003349
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003350 // If body is not a compound statement create implicit scope
3351 // and add destructors.
3352 if (!isa<CompoundStmt>(D->getBody()))
3353 addLocalScopeAndDtors(D->getBody());
3354
Ted Kremenek9aae5132007-08-23 21:42:29 +00003355 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003356 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003357
Ted Kremeneke9610502007-08-30 18:39:40 +00003358 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003359 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003360 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003361 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003362 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003363 }
Mike Stump31feda52009-07-17 01:31:16 +00003364
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003365 // Add an intermediate block between the BodyBlock and the
3366 // ExitConditionBlock to represent the "loop back" transition. Create an
3367 // empty block to represent the transition block for looping back to the
3368 // head of the loop.
3369 // FIXME: Can we do this more efficiently without adding another block?
3370 Block = nullptr;
3371 Succ = BodyBlock;
3372 CFGBlock *LoopBackBlock = createBlock();
3373 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003374
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003375 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003376 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003377 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003378 else
Craig Topper25542942014-05-20 04:30:07 +00003379 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003380 }
Mike Stump31feda52009-07-17 01:31:16 +00003381
Ted Kremenek30754282009-07-24 04:47:11 +00003382 // Link up the condition block with the code that follows the loop.
3383 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003384 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003385
3386 // There can be no more statements in the body block(s) since we loop back to
3387 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003388 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003389
Ted Kremenek9aae5132007-08-23 21:42:29 +00003390 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003391 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003392 return BodyBlock;
3393}
3394
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003395CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003396 // "continue" is a control-flow statement. Thus we stop processing the
3397 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003398 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003399 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003400
Ted Kremenek9aae5132007-08-23 21:42:29 +00003401 // Now create a new block that ends with the continue statement.
3402 Block = createBlock(false);
3403 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003404
Ted Kremenek9aae5132007-08-23 21:42:29 +00003405 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003406 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003407 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003408 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003409 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003410 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003411 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003412
Ted Kremenek9aae5132007-08-23 21:42:29 +00003413 return Block;
3414}
Mike Stump11289f42009-09-09 15:08:12 +00003415
Peter Collingbournee190dee2011-03-11 19:24:49 +00003416CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3417 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003418 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003419 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003420 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003421 }
Mike Stump11289f42009-09-09 15:08:12 +00003422
Ted Kremenek93668002009-07-17 22:18:43 +00003423 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003424 CFGBlock *lastBlock = Block;
3425
Ted Kremenek93668002009-07-17 22:18:43 +00003426 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003427 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003428 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003429 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003430 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003431 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003432}
Mike Stump11289f42009-09-09 15:08:12 +00003433
Ted Kremenek93668002009-07-17 22:18:43 +00003434/// VisitStmtExpr - Utility method to handle (nested) statement
3435/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003436CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003437 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003438 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003439 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003440 }
Ted Kremenek93668002009-07-17 22:18:43 +00003441 return VisitCompoundStmt(SE->getSubStmt());
3442}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003443
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003444CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003445 // "switch" is a control-flow statement. Thus we stop processing the current
3446 // block.
Craig Topper25542942014-05-20 04:30:07 +00003447 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003448
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003449 // Save local scope position because in case of condition variable ScopePos
3450 // won't be restored when traversing AST.
3451 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3452
Richard Smitha547eb22016-07-14 00:11:03 +00003453 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003454 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003455 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003456
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003457 // Create local scope for possible condition variable.
3458 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003459 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003460 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003461
Matthias Gehre351c2182017-07-12 07:04:19 +00003462 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003463
Ted Kremenek9aae5132007-08-23 21:42:29 +00003464 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003465 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003466 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003467 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003468 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003469
3470 // Save the current "switch" context.
3471 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003472 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003473 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003474
Mike Stump31feda52009-07-17 01:31:16 +00003475 // Set the "default" case to be the block after the switch statement. If the
3476 // switch statement contains a "default:", this value will be overwritten with
3477 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003478 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003479
Ted Kremenek9aae5132007-08-23 21:42:29 +00003480 // Create a new block that will contain the switch statement.
3481 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003482
Ted Kremenek9aae5132007-08-23 21:42:29 +00003483 // Now process the switch body. The code after the switch is the implicit
3484 // successor.
3485 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003486 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003487
3488 // When visiting the body, the case statements should automatically get linked
3489 // up to the switch. We also don't keep a pointer to the body, since all
3490 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003491 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003492 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003493
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003494 // For pruning unreachable case statements, save the current state
3495 // for tracking the condition value.
3496 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3497 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003498
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003499 // Determine if the switch condition can be explicitly evaluated.
3500 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003501 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003502 bool b = tryEvaluate(Terminator->getCond(), result);
3503 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003504 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003505
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003506 // If body is not a compound statement create implicit scope
3507 // and add destructors.
3508 if (!isa<CompoundStmt>(Terminator->getBody()))
3509 addLocalScopeAndDtors(Terminator->getBody());
3510
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003511 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003512 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003513 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003514 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003515 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003516
Mike Stump31feda52009-07-17 01:31:16 +00003517 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003518 // following the switch body. Moreover, take into account if all the
3519 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003520 //
3521 // Note: We add a successor to a switch that is considered covered yet has no
3522 // case statements if the enumeration has no enumerators.
3523 bool SwitchAlwaysHasSuccessor = false;
3524 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3525 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3526 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003527 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3528 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003529
Ted Kremenek81e14852007-08-27 19:46:09 +00003530 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003531 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003532 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003533 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003534
Richard Smitha547eb22016-07-14 00:11:03 +00003535 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003536 // SwitchStmt and the condition variable initialization to the CFG.
3537 if (VarDecl *VD = Terminator->getConditionVariable()) {
3538 if (Expr *Init = VD->getInit()) {
3539 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003540 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003541 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003542 }
3543 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003544
Richard Smitha547eb22016-07-14 00:11:03 +00003545 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3546 if (Stmt *Init = Terminator->getInit()) {
3547 autoCreateBlock();
3548 LastBlock = addStmt(Init);
3549 }
3550
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003551 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003552}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003553
3554static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003555 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003556 const CaseStmt *CS,
3557 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003558 if (!switchCond)
3559 return true;
3560
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003561 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003562
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003563 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003564 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003565 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003566 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003567 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003568
3569 if (condInt == lhsInt) {
3570 addCase = true;
3571 switchExclusivelyCovered = true;
3572 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003573 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003574 if (const Expr *RHS = CS->getRHS()) {
3575 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003576 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003577 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003578 addCase = true;
3579 switchExclusivelyCovered = true;
3580 }
3581 }
3582 }
3583 }
3584 else
3585 addCase = true;
3586 }
3587 return addCase;
3588}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003589
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003590CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003591 // CaseStmts are essentially labels, so they are the first statement in a
3592 // block.
Craig Topper25542942014-05-20 04:30:07 +00003593 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003594
Ted Kremenek60fa6572010-08-04 23:54:30 +00003595 if (Stmt *Sub = CS->getSubStmt()) {
3596 // For deeply nested chains of CaseStmts, instead of doing a recursion
3597 // (which can blow out the stack), manually unroll and create blocks
3598 // along the way.
3599 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003600 CFGBlock *currentBlock = createBlock(false);
3601 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003602
Ted Kremenek60fa6572010-08-04 23:54:30 +00003603 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003604 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003605 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003606 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003607
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003608 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003609 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003610 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003611 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003612
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003613 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003614 CS = cast<CaseStmt>(Sub);
3615 Sub = CS->getSubStmt();
3616 }
3617
3618 addStmt(Sub);
3619 }
Mike Stump11289f42009-09-09 15:08:12 +00003620
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003621 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003622 if (!CaseBlock)
3623 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003624
3625 // Cases statements partition blocks, so this is the top of the basic block we
3626 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003627 CaseBlock->setLabel(CS);
3628
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003629 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003630 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003631
3632 // Add this block to the list of successors for the block with the switch
3633 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003634 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003635 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003636 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003637 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003638
Ted Kremenek9aae5132007-08-23 21:42:29 +00003639 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003640 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003641
Ted Kremenek60fa6572010-08-04 23:54:30 +00003642 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003643 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003644 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003645 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003646 // This block is now the implicit successor of other blocks.
3647 Succ = CaseBlock;
3648 }
Mike Stump31feda52009-07-17 01:31:16 +00003649
Ted Kremenek60fa6572010-08-04 23:54:30 +00003650 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003651}
Mike Stump31feda52009-07-17 01:31:16 +00003652
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003653CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003654 if (Terminator->getSubStmt())
3655 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003656
Ted Kremenek654c78f2008-02-13 22:05:39 +00003657 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003658
3659 if (!DefaultCaseBlock)
3660 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003661
3662 // Default statements partition blocks, so this is the top of the basic block
3663 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003664 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003665
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003666 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003667 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003668
Mike Stump31feda52009-07-17 01:31:16 +00003669 // Unlike case statements, we don't add the default block to the successors
3670 // for the switch statement immediately. This is done when we finish
3671 // processing the switch statement. This allows for the default case
3672 // (including a fall-through to the code after the switch statement) to always
3673 // be the last successor of a switch-terminated block.
3674
Ted Kremenek654c78f2008-02-13 22:05:39 +00003675 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003676 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003677
Ted Kremenek654c78f2008-02-13 22:05:39 +00003678 // This block is now the implicit successor of other blocks.
3679 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003680
3681 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003682}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003683
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003684CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3685 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3686 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003687 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003688
3689 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003690 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003691 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003692 TrySuccessor = Block;
3693 } else TrySuccessor = Succ;
3694
Mike Stump0bdba6c2010-01-20 01:15:34 +00003695 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003696
3697 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003698 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003699 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003700 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003701
Mike Stump0bdba6c2010-01-20 01:15:34 +00003702 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003703 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3704 // The code after the try is the implicit successor.
3705 Succ = TrySuccessor;
3706 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003707 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003708 HasCatchAll = true;
3709 }
Craig Topper25542942014-05-20 04:30:07 +00003710 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003711 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003712 if (!CatchBlock)
3713 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003714 // Add this block to the list of successors for the block with the try
3715 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003716 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003717 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003718 if (!HasCatchAll) {
3719 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003720 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003721 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003722 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003723 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003724
3725 // The code after the try is the implicit successor.
3726 Succ = TrySuccessor;
3727
Mike Stump845384a2010-01-20 01:30:58 +00003728 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003729 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3730 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003731
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003732 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003733 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003734 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003735}
3736
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003737CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003738 // CXXCatchStmt are treated like labels, so they are the first statement in a
3739 // block.
3740
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003741 // Save local scope position because in case of exception variable ScopePos
3742 // won't be restored when traversing AST.
3743 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3744
3745 // Create local scope for possible exception variable.
3746 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003747 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003748 LocalScope::const_iterator BeginScopePos = ScopePos;
3749 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003750 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003751 }
3752
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003753 if (CS->getHandlerBlock())
3754 addStmt(CS->getHandlerBlock());
3755
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003756 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003757 if (!CatchBlock)
3758 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003759
3760 // CXXCatchStmt is more than just a label. They have semantic meaning
3761 // as well, as they implicitly "initialize" the catch variable. Add
3762 // it to the CFG as a CFGElement so that the control-flow of these
3763 // semantics gets captured.
3764 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003765
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003766 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3767 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003768 CatchBlock->setLabel(CS);
3769
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003770 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003771 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003772 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003773
3774 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003775 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003776
3777 return CatchBlock;
3778}
3779
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003780CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003781 // C++0x for-range statements are specified as [stmt.ranged]:
3782 //
3783 // {
3784 // auto && __range = range-init;
3785 // for ( auto __begin = begin-expr,
3786 // __end = end-expr;
3787 // __begin != __end;
3788 // ++__begin ) {
3789 // for-range-declaration = *__begin;
3790 // statement
3791 // }
3792 // }
3793
3794 // Save local scope position before the addition of the implicit variables.
3795 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3796
3797 // Create local scopes and destructors for range, begin and end variables.
3798 if (Stmt *Range = S->getRangeStmt())
3799 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00003800 if (Stmt *Begin = S->getBeginStmt())
3801 addLocalScopeForStmt(Begin);
3802 if (Stmt *End = S->getEndStmt())
3803 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00003804 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00003805
3806 LocalScope::const_iterator ContinueScopePos = ScopePos;
3807
3808 // "for" is a control-flow statement. Thus we stop processing the current
3809 // block.
Craig Topper25542942014-05-20 04:30:07 +00003810 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003811 if (Block) {
3812 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003813 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003814 LoopSuccessor = Block;
3815 } else
3816 LoopSuccessor = Succ;
3817
3818 // Save the current value for the break targets.
3819 // All breaks should go to the code following the loop.
3820 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3821 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3822
3823 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003824 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003825 ConditionBlock->setTerminator(S);
3826
3827 // Now add the actual condition to the condition block.
3828 if (Expr *C = S->getCond()) {
3829 Block = ConditionBlock;
3830 CFGBlock *BeginConditionBlock = addStmt(C);
3831 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003832 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003833 assert(BeginConditionBlock == ConditionBlock &&
3834 "condition block in for-range was unexpectedly complex");
3835 (void)BeginConditionBlock;
3836 }
3837
3838 // The condition block is the implicit successor for the loop body as well as
3839 // any code above the loop.
3840 Succ = ConditionBlock;
3841
3842 // See if this is a known constant.
3843 TryResult KnownVal(true);
3844
3845 if (S->getCond())
3846 KnownVal = tryEvaluateBool(S->getCond());
3847
3848 // Now create the loop body.
3849 {
3850 assert(S->getBody());
3851
3852 // Save the current values for Block, Succ, and continue targets.
3853 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3854 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3855
3856 // Generate increment code in its own basic block. This is the target of
3857 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003858 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003859 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00003860 if (badCFG)
3861 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003862 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3863
3864 // The starting block for the loop increment is the block that should
3865 // represent the 'loop target' for looping back to the start of the loop.
3866 ContinueJumpTarget.block->setLoopTarget(S);
3867
3868 // Finish up the increment block and prepare to start the loop body.
3869 assert(Block);
3870 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003871 return nullptr;
3872 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003873
3874 // Add implicit scope and dtors for loop variable.
3875 addLocalScopeAndDtors(S->getLoopVarStmt());
3876
3877 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003878 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003879 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003880 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003881 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003882 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003883 return nullptr;
3884
Richard Smith02e85f32011-04-14 22:09:26 +00003885 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003886 addSuccessor(ConditionBlock,
3887 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003888 }
3889
3890 // Link up the condition block with the code that follows the loop (the
3891 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003892 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003893
3894 // Add the initialization statements.
3895 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00003896 addStmt(S->getBeginStmt());
3897 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00003898 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003899}
3900
John McCall5d413782010-12-06 08:20:24 +00003901CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003902 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003903 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003904 // If adding implicit destructors visit the full expression for adding
3905 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003906 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003907 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003908
3909 // Full expression has to be added as CFGStmt so it will be sequenced
3910 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003911 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003912 }
3913 return Visit(E->getSubExpr(), asc);
3914}
3915
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003916CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3917 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003918 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003919 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003920 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003921
3922 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003923 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003924 }
3925 return Visit(E->getSubExpr(), asc);
3926}
3927
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003928CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3929 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003930 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00003931 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003932
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003933 return VisitChildren(C);
3934}
3935
Jordan Rosec9176072014-01-13 17:59:19 +00003936CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3937 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00003938 autoCreateBlock();
3939 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003940
Artem Dergachev41ffb302018-02-08 22:58:15 +00003941 EnterConstructionContextIfNecessary(
3942 NE, const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
3943
Jordan Rosec9176072014-01-13 17:59:19 +00003944 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003945 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003946
Jordan Rosec9176072014-01-13 17:59:19 +00003947 if (BuildOpts.AddCXXNewAllocator)
3948 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003949
Jordan Rosec9176072014-01-13 17:59:19 +00003950 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003951 Block = Visit(NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003952
Jordan Rosec9176072014-01-13 17:59:19 +00003953 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3954 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003955 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003956
Jordan Rosec9176072014-01-13 17:59:19 +00003957 return Block;
3958}
Jordan Rosed2f40792013-09-03 17:00:57 +00003959
3960CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3961 AddStmtChoice asc) {
3962 autoCreateBlock();
3963 appendStmt(Block, DE);
3964 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00003965 if (!DTy.isNull()) {
3966 DTy = DTy.getNonReferenceType();
3967 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3968 if (RD) {
3969 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
3970 appendDeleteDtor(Block, RD, DE);
3971 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003972 }
3973
3974 return VisitChildren(DE);
3975}
3976
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003977CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3978 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003979 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003980 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003981 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003982 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003983 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003984 }
3985 return Visit(E->getSubExpr(), asc);
3986}
3987
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003988CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3989 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003990 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003991 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003992 return VisitChildren(C);
3993}
3994
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003995CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3996 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003997 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003998 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003999 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004000 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004001 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004002}
4003
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004004CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004005 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004006 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004007
Ted Kremenekeda180e22007-08-28 19:26:49 +00004008 if (!IBlock) {
4009 IBlock = createBlock(false);
4010 cfg->setIndirectGotoBlock(IBlock);
4011 }
Mike Stump31feda52009-07-17 01:31:16 +00004012
Ted Kremenekeda180e22007-08-28 19:26:49 +00004013 // IndirectGoto is a control-flow statement. Thus we stop processing the
4014 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004015 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004016 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004017
Ted Kremenekeda180e22007-08-28 19:26:49 +00004018 Block = createBlock(false);
4019 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004020 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004021 return addStmt(I->getTarget());
4022}
4023
Manuel Klimekb5616c92014-08-07 10:42:17 +00004024CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4025 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004026 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4027
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004028tryAgain:
4029 if (!E) {
4030 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004031 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004032 }
4033 switch (E->getStmtClass()) {
4034 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004035 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004036
4037 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004038 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4039 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004040
4041 case Stmt::CXXBindTemporaryExprClass:
4042 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004043 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004044
John McCallc07a0c72011-02-17 10:25:35 +00004045 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004046 case Stmt::ConditionalOperatorClass:
4047 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004048 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004049
4050 case Stmt::ImplicitCastExprClass:
4051 // For implicit cast we want BindToTemporary to be passed further.
4052 E = cast<CastExpr>(E)->getSubExpr();
4053 goto tryAgain;
4054
Manuel Klimekb0042c42014-07-30 08:34:42 +00004055 case Stmt::CXXFunctionalCastExprClass:
4056 // For functional cast we want BindToTemporary to be passed further.
4057 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4058 goto tryAgain;
4059
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004060 case Stmt::ParenExprClass:
4061 E = cast<ParenExpr>(E)->getSubExpr();
4062 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004063
Manuel Klimekb0042c42014-07-30 08:34:42 +00004064 case Stmt::MaterializeTemporaryExprClass: {
4065 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4066 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4067 SmallVector<const Expr *, 2> CommaLHSs;
4068 SmallVector<SubobjectAdjustment, 2> Adjustments;
4069 // Find the expression whose lifetime needs to be extended.
4070 E = const_cast<Expr *>(
4071 cast<MaterializeTemporaryExpr>(E)
4072 ->GetTemporaryExpr()
4073 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4074 // Visit the skipped comma operator left-hand sides for other temporaries.
4075 for (const Expr *CommaLHS : CommaLHSs) {
4076 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004077 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004078 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004079 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004080 }
Richard Smith4137af22014-07-27 05:12:49 +00004081
4082 case Stmt::BlockExprClass:
4083 // Don't recurse into blocks; their subexpressions don't get evaluated
4084 // here.
4085 return Block;
4086
4087 case Stmt::LambdaExprClass: {
4088 // For lambda expressions, only recurse into the capture initializers,
4089 // and not the body.
4090 auto *LE = cast<LambdaExpr>(E);
4091 CFGBlock *B = Block;
4092 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004093 if (CFGBlock *R = VisitForTemporaryDtors(
4094 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00004095 B = R;
4096 }
4097 return B;
4098 }
4099
4100 case Stmt::CXXDefaultArgExprClass:
4101 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4102 goto tryAgain;
4103
4104 case Stmt::CXXDefaultInitExprClass:
4105 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4106 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004107 }
4108}
4109
Manuel Klimekb5616c92014-08-07 10:42:17 +00004110CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4111 TempDtorContext &Context) {
4112 if (isa<LambdaExpr>(E)) {
4113 // Do not visit the children of lambdas; they have their own CFGs.
4114 return Block;
4115 }
4116
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004117 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004118 // order that they will appear in the CFG. Because the CFG is built
4119 // bottom-up, this means we visit them in their natural order, which
4120 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004121 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004122 for (Stmt *Child : E->children())
4123 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004124 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004125 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004126
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004127 return B;
4128}
4129
Manuel Klimekb5616c92014-08-07 10:42:17 +00004130CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4131 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004132 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004133 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004134 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4135 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4136 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004137
Manuel Klimekedf925b92014-08-07 18:44:19 +00004138 // We do not know at CFG-construction time whether the right-hand-side was
4139 // executed, thus we add a branch node that depends on the temporary
4140 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004141 TempDtorContext RHSContext(
4142 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004143 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004144 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004145
Manuel Klimekb5616c92014-08-07 10:42:17 +00004146 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004147 }
4148
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004149 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004150 // For assignment operator (=) LHS expression is visited
4151 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004152 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4153 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004154 return LHSBlock ? LHSBlock : RHSBlock;
4155 }
4156
4157 // For any other binary operator RHS expression is visited before
4158 // LHS expression (order of children). For destructors visit them in reverse
4159 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004160 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4161 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004162 return RHSBlock ? RHSBlock : LHSBlock;
4163}
4164
4165CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004166 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004167 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004168 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004169 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004170 // If lifetime of temporary is not prolonged (by assigning to constant
4171 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004172
Chandler Carruthad747252011-09-13 06:09:01 +00004173 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004174
Richard Trieu95a192a2015-05-28 00:14:02 +00004175 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004176 // If the destructor is marked as a no-return destructor, we need to
4177 // create a new block for the destructor which does not have as a
4178 // successor anything built thus far. Control won't flow out of this
4179 // block.
4180 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004181 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004182 } else if (Context.needsTempDtorBranch()) {
4183 // If we need to introduce a branch, we add a new block that we will hook
4184 // up to a decision block later.
4185 if (B) Succ = B;
4186 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004187 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004188 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004189 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004190 if (Context.needsTempDtorBranch()) {
4191 Context.setDecisionPoint(Succ, E);
4192 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004193 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004194
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004195 B = Block;
4196 }
4197 return B;
4198}
4199
Manuel Klimekb5616c92014-08-07 10:42:17 +00004200void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4201 CFGBlock *FalseSucc) {
4202 if (!Context.TerminatorExpr) {
4203 // If no temporary was found, we do not need to insert a decision point.
4204 return;
4205 }
4206 assert(Context.TerminatorExpr);
4207 CFGBlock *Decision = createBlock(false);
4208 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004209 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004210 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004211 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004212 Block = Decision;
4213}
4214
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004215CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004216 AbstractConditionalOperator *E, bool BindToTemporary,
4217 TempDtorContext &Context) {
4218 VisitForTemporaryDtors(E->getCond(), false, Context);
4219 CFGBlock *ConditionBlock = Block;
4220 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004221 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004222 TryResult NegatedVal = ConditionVal;
4223 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004224
Manuel Klimekdeb02622014-08-08 07:37:13 +00004225 TempDtorContext TrueContext(
4226 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004227 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004228 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004229
Manuel Klimekb5616c92014-08-07 10:42:17 +00004230 Block = ConditionBlock;
4231 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004232 TempDtorContext FalseContext(
4233 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004234 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004235
Manuel Klimekb5616c92014-08-07 10:42:17 +00004236 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004237 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004238 } else if (TrueContext.TerminatorExpr) {
4239 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004240 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004241 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004242 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004243 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004244 return Block;
4245}
4246
Mike Stump31feda52009-07-17 01:31:16 +00004247/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4248/// no successors or predecessors. If this is the first block created in the
4249/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004250CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004251 bool first_block = begin() == end();
4252
4253 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004254 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004255 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004256 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004257
4258 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004259 if (first_block)
4260 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004261
4262 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004263 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004264}
4265
David Blaikiee90195c2014-08-29 18:53:26 +00004266/// buildCFG - Constructs a CFG from an AST.
4267std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4268 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004269 CFGBuilder Builder(C, BO);
4270 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004271}
4272
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004273const CXXDestructorDecl *
4274CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004275 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004276 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004277 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004278 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004279 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004280 case CFGElement::Statement:
4281 case CFGElement::Constructor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004282 llvm_unreachable("getDestructorDecl should only be used with "
4283 "ImplicitDtors");
4284 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004285 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004286 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004287
4288 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4289 //
4290 // Lifetime-extending constructs are handled here. This works for a single
4291 // temporary in an initializer expression.
4292 if (ty->isReferenceType()) {
4293 if (const Expr *Init = var->getInit()) {
4294 ty = getReferenceInitTemporaryType(astContext, Init);
4295 }
4296 }
4297
Ted Kremeneke7d78882012-03-19 23:48:41 +00004298 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004299 ty = arrayType->getElementType();
4300 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004301 const RecordType *recordType = ty->getAs<RecordType>();
4302 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004303 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004304 return classDecl->getDestructor();
4305 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004306 case CFGElement::DeleteDtor: {
4307 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4308 QualType DTy = DE->getDestroyedType();
4309 DTy = DTy.getNonReferenceType();
4310 const CXXRecordDecl *classDecl =
4311 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4312 return classDecl->getDestructor();
4313 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004314 case CFGElement::TemporaryDtor: {
4315 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004316 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004317 const CXXTemporary *temp = bindExpr->getTemporary();
4318 return temp->getDestructor();
4319 }
4320 case CFGElement::BaseDtor:
4321 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004322 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004323 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004324 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004325 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004326}
4327
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004328bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004329 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4330 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004331 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004332}
4333
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004334//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004335// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004336//===----------------------------------------------------------------------===//
4337
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004338CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004339 : ReachableBlock(IsReachable ? B : nullptr),
4340 UnreachableBlock(!IsReachable ? B : nullptr,
4341 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004342
4343CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004344 : ReachableBlock(B),
4345 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4346 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004347
4348void CFGBlock::addSuccessor(AdjacentBlock Succ,
4349 BumpVectorContext &C) {
4350 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004351 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004352
4353 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004354 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004355
4356 Succs.push_back(Succ, C);
4357}
4358
Ted Kremenekb0371852010-09-09 00:06:04 +00004359bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004360 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004361 if (F.IgnoreNullPredecessors && !From)
4362 return true;
4363
4364 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004365 // If the 'To' has no label or is labeled but the label isn't a
4366 // CaseStmt then filter this edge.
4367 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00004368 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004369 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004370 const Stmt *L = To->getLabel();
4371 if (!L || !isa<CaseStmt>(L))
4372 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004373 }
4374 }
4375 }
4376
4377 return false;
4378}
4379
4380//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004381// CFG pretty printing
4382//===----------------------------------------------------------------------===//
4383
Ted Kremenek7e776b12007-08-22 18:22:34 +00004384namespace {
4385
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004386class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004387 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4388 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4389
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004390 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004391 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004392 signed currentBlock = 0;
4393 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004394 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004395
Eugene Zelenko38c70522017-12-07 21:55:09 +00004396public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004397 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004398 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004399 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4400 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004401 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004402 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004403 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4404 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004405 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004406 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004407
Ted Kremenek96a7a592011-03-01 03:15:10 +00004408 switch (stmt->getStmtClass()) {
4409 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004410 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4411 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004412 case Stmt::IfStmtClass: {
4413 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4414 if (var)
4415 DeclMap[var] = P;
4416 break;
4417 }
4418 case Stmt::ForStmtClass: {
4419 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4420 if (var)
4421 DeclMap[var] = P;
4422 break;
4423 }
4424 case Stmt::WhileStmtClass: {
4425 const VarDecl *var =
4426 cast<WhileStmt>(stmt)->getConditionVariable();
4427 if (var)
4428 DeclMap[var] = P;
4429 break;
4430 }
4431 case Stmt::SwitchStmtClass: {
4432 const VarDecl *var =
4433 cast<SwitchStmt>(stmt)->getConditionVariable();
4434 if (var)
4435 DeclMap[var] = P;
4436 break;
4437 }
4438 case Stmt::CXXCatchStmtClass: {
4439 const VarDecl *var =
4440 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4441 if (var)
4442 DeclMap[var] = P;
4443 break;
4444 }
4445 default:
4446 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004447 }
4448 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004449 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004450 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004451 }
Mike Stump31feda52009-07-17 01:31:16 +00004452
Eugene Zelenko38c70522017-12-07 21:55:09 +00004453 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004454
Chris Lattnerc61089a2009-06-30 01:26:17 +00004455 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004456 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004457 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004458
Craig Topperb45acb82014-03-14 06:02:07 +00004459 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004460 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004461
4462 if (I == StmtMap.end())
4463 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004464
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004465 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004466 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004467 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004468 }
Mike Stump31feda52009-07-17 01:31:16 +00004469
Ted Kremenek60983dc2010-01-19 20:52:05 +00004470 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004471 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004472 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004473
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004474 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004475 DeclMapTy::iterator I = DeclMap.find(D);
4476
4477 if (I == DeclMap.end())
4478 return false;
4479
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004480 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004481 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004482 return false;
4483 }
4484
4485 OS << "[B" << I->second.first << "." << I->second.second << "]";
4486 return true;
4487 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004488};
4489
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004490class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00004491 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004492 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004493 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004494 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004495
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004496public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004497 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004498 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004499 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004500 this->Policy.IncludeNewlines = false;
4501 }
Mike Stump31feda52009-07-17 01:31:16 +00004502
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004503 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004504 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004505 if (Stmt *C = I->getCond())
4506 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004507 }
Mike Stump31feda52009-07-17 01:31:16 +00004508
Ted Kremenek9aae5132007-08-23 21:42:29 +00004509 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004510 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004511 Terminator->printPretty(OS, Helper, Policy);
4512 }
4513
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004514 void VisitDeclStmt(DeclStmt *DS) {
4515 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4516 OS << "static init " << VD->getName();
4517 }
4518
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004519 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004520 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004521 if (F->getInit())
4522 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004523 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004524 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004525 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004526 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004527 if (F->getInc())
4528 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004529 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004530 }
Mike Stump31feda52009-07-17 01:31:16 +00004531
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004532 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004533 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004534 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004535 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004536 }
Mike Stump31feda52009-07-17 01:31:16 +00004537
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004538 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004539 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004540 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004541 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004542 }
Mike Stump31feda52009-07-17 01:31:16 +00004543
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004544 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004545 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004546 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004547 }
Mike Stump31feda52009-07-17 01:31:16 +00004548
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004549 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004550 OS << "try ...";
4551 }
4552
Nico Weber699670e2017-08-23 15:33:16 +00004553 void VisitSEHTryStmt(SEHTryStmt *CS) {
4554 OS << "__try ...";
4555 }
4556
John McCallc07a0c72011-02-17 10:25:35 +00004557 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004558 if (Stmt *Cond = C->getCond())
4559 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004560 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004561 }
Mike Stump31feda52009-07-17 01:31:16 +00004562
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004563 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004564 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004565 if (Stmt *Cond = C->getCond())
4566 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004567 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004568 }
Mike Stump31feda52009-07-17 01:31:16 +00004569
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004570 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004571 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004572 if (Stmt *T = I->getTarget())
4573 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004574 }
Mike Stump31feda52009-07-17 01:31:16 +00004575
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004576 void VisitBinaryOperator(BinaryOperator* B) {
4577 if (!B->isLogicalOp()) {
4578 VisitExpr(B);
4579 return;
4580 }
Mike Stump31feda52009-07-17 01:31:16 +00004581
Richard Trieuddd01ce2014-06-09 22:53:25 +00004582 if (B->getLHS())
4583 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004584
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004585 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004586 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004587 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004588 return;
John McCalle3027922010-08-25 11:45:40 +00004589 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004590 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004591 return;
4592 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004593 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004594 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004595 }
Mike Stump31feda52009-07-17 01:31:16 +00004596
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004597 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004598 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004599 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004600
4601public:
4602 void print(CFGTerminator T) {
4603 if (T.isTemporaryDtorsBranch())
4604 OS << "(Temp Dtor) ";
4605 Visit(T.getStmt());
4606 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004607};
Eugene Zelenko38c70522017-12-07 21:55:09 +00004608
4609} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00004610
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004611static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
4612 const CXXCtorInitializer *I) {
4613 if (I->isBaseInitializer())
4614 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4615 else if (I->isDelegatingInitializer())
4616 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4617 else
4618 OS << I->getAnyMember()->getName();
4619 OS << "(";
4620 if (Expr *IE = I->getInit())
4621 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4622 OS << ")";
4623
4624 if (I->isBaseInitializer())
4625 OS << " (Base initializer)";
4626 else if (I->isDelegatingInitializer())
4627 OS << " (Delegating initializer)";
4628 else
4629 OS << " (Member initializer)";
4630}
4631
Aaron Ballmanff924b02013-11-18 20:11:50 +00004632static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004633 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004634 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4635 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004636 assert(S != nullptr && "Expecting non-null Stmt");
4637
Aaron Ballmanff924b02013-11-18 20:11:50 +00004638 // special printing for statement-expressions.
4639 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4640 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004641
Benjamin Kramer5733e352015-07-18 17:09:36 +00004642 auto Children = Sub->children();
4643 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004644 OS << "({ ... ; ";
4645 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4646 OS << " })\n";
4647 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004648 }
4649 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004650 // special printing for comma expressions.
4651 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4652 if (B->getOpcode() == BO_Comma) {
4653 OS << "... , ";
4654 Helper.handledStmt(B->getRHS(),OS);
4655 OS << '\n';
4656 return;
4657 }
4658 }
4659 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004660
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004661 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004662 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004663 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004664 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004665 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4666 OS << " (CXXConstructExpr, ";
4667 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
4668 if (const Stmt *S = CE->getTriggerStmt())
4669 Helper.handledStmt((const_cast<Stmt *>(S)), OS);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004670 else if (const CXXCtorInitializer *I = CE->getTriggerInit())
4671 print_initializer(OS, Helper, I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004672 else
4673 llvm_unreachable("Unexpected trigger kind!");
4674 OS << ", ";
4675 }
4676 OS << CCE->getType().getAsString() << ")";
4677 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00004678 OS << " (" << CE->getStmtClassName() << ", "
4679 << CE->getCastKindName()
4680 << ", " << CE->getType().getAsString()
4681 << ")";
4682 }
Mike Stump31feda52009-07-17 01:31:16 +00004683
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004684 // Expressions need a newline.
4685 if (isa<Expr>(S))
4686 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004687 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004688 print_initializer(OS, Helper, IE->getInitializer());
4689 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004690 } else if (Optional<CFGAutomaticObjDtor> DE =
4691 E.getAs<CFGAutomaticObjDtor>()) {
4692 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004693 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004694
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004695 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004696 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4697 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004698 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004699
4700 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4701 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00004702 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4703 const VarDecl *VD = DE->getVarDecl();
4704 Helper.handleDecl(VD, OS);
4705
4706 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00004707 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
4708 const Stmt *LoopStmt = LE->getLoopStmt();
4709 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Jordan Rosec9176072014-01-13 17:59:19 +00004710 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4711 OS << "CFGNewAllocator(";
4712 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4713 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4714 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004715 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4716 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4717 if (!RD)
4718 return;
4719 CXXDeleteExpr *DelExpr =
4720 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004721 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004722 OS << "->~" << RD->getName().str() << "()";
4723 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004724 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4725 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004726 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004727 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004728 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4729 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004730 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004731 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004732 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004733 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004734 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4735 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004736 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004737 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004738 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004739 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004740}
Mike Stump31feda52009-07-17 01:31:16 +00004741
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004742static void print_block(raw_ostream &OS, const CFG* cfg,
4743 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004744 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004745 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004746 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004747
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004748 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004749 if (ShowColors)
4750 OS.changeColor(raw_ostream::YELLOW, true);
4751
4752 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004753
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004754 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004755 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004756 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004757 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004758 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004759 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004760 else if (B.hasNoReturnElement())
4761 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004762 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004763 OS << "]\n";
4764
4765 if (ShowColors)
4766 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004767
Ted Kremenek71eca012007-08-29 23:20:49 +00004768 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004769 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004770 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004771 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004772
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004773 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004774 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004775 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004776 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004777 if (C->getLHS())
4778 C->getLHS()->printPretty(OS, &Helper,
4779 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004780 if (C->getRHS()) {
4781 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004782 C->getRHS()->printPretty(OS, &Helper,
4783 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004784 }
Mike Stump92244b02010-01-19 22:00:14 +00004785 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004786 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004787 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004788 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004789 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004790 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004791 0);
4792 else
4793 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004794 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00004795 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
4796 OS << "__except (";
4797 ES->getFilterExpr()->printPretty(OS, &Helper,
4798 PrintingPolicy(Helper.getLangOpts()), 0);
4799 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004800 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004801 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004802
Ted Kremenek71eca012007-08-29 23:20:49 +00004803 OS << ":\n";
4804 }
Mike Stump31feda52009-07-17 01:31:16 +00004805
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004806 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004807 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004808
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004809 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4810 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004811 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004812 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004813 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004814
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004815 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004816
Aaron Ballmanff924b02013-11-18 20:11:50 +00004817 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004818
Ted Kremenek72be32a2011-12-22 23:33:52 +00004819 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004820 }
Mike Stump31feda52009-07-17 01:31:16 +00004821
Ted Kremenek71eca012007-08-29 23:20:49 +00004822 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004823 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004824 if (ShowColors)
4825 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004826
Ted Kremenek72be32a2011-12-22 23:33:52 +00004827 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004828
Aaron Ballmanff924b02013-11-18 20:11:50 +00004829 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004830
Aaron Ballmanff924b02013-11-18 20:11:50 +00004831 PrintingPolicy PP(Helper.getLangOpts());
4832 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004833 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004834 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004835
4836 if (ShowColors)
4837 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004838 }
Mike Stump31feda52009-07-17 01:31:16 +00004839
Ted Kremenek71eca012007-08-29 23:20:49 +00004840 if (print_edges) {
4841 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004842 if (!B.pred_empty()) {
4843 const raw_ostream::Colors Color = raw_ostream::BLUE;
4844 if (ShowColors)
4845 OS.changeColor(Color);
4846 OS << " Preds " ;
4847 if (ShowColors)
4848 OS.resetColor();
4849 OS << '(' << B.pred_size() << "):";
4850 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004851
Ted Kremenek72be32a2011-12-22 23:33:52 +00004852 if (ShowColors)
4853 OS.changeColor(Color);
4854
4855 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4856 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004857 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004858 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004859
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004860 CFGBlock *B = *I;
4861 bool Reachable = true;
4862 if (!B) {
4863 Reachable = false;
4864 B = I->getPossiblyUnreachableBlock();
4865 }
4866
4867 OS << " B" << B->getBlockID();
4868 if (!Reachable)
4869 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004870 }
4871
4872 if (ShowColors)
4873 OS.resetColor();
4874
4875 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004876 }
Mike Stump31feda52009-07-17 01:31:16 +00004877
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004878 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004879 if (!B.succ_empty()) {
4880 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4881 if (ShowColors)
4882 OS.changeColor(Color);
4883 OS << " Succs ";
4884 if (ShowColors)
4885 OS.resetColor();
4886 OS << '(' << B.succ_size() << "):";
4887 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004888
Ted Kremenek72be32a2011-12-22 23:33:52 +00004889 if (ShowColors)
4890 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004891
Ted Kremenek72be32a2011-12-22 23:33:52 +00004892 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4893 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004894 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004895 OS << "\n ";
4896
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004897 CFGBlock *B = *I;
4898
4899 bool Reachable = true;
4900 if (!B) {
4901 Reachable = false;
4902 B = I->getPossiblyUnreachableBlock();
4903 }
4904
4905 if (B) {
4906 OS << " B" << B->getBlockID();
4907 if (!Reachable)
4908 OS << "(Unreachable)";
4909 }
4910 else {
4911 OS << " NULL";
4912 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004913 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004914
Ted Kremenek72be32a2011-12-22 23:33:52 +00004915 if (ShowColors)
4916 OS.resetColor();
4917 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004918 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004919 }
Mike Stump31feda52009-07-17 01:31:16 +00004920}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004921
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004922/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004923void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4924 print(llvm::errs(), LO, ShowColors);
4925}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004926
4927/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004928void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004929 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004930
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004931 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004932 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004933
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004934 // Iterate through the CFGBlocks and print them one by one.
4935 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4936 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004937 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004938 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004939
Aaron Ballmanff924b02013-11-18 20:11:50 +00004940 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004941 }
Mike Stump31feda52009-07-17 01:31:16 +00004942
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004943 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004944 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004945 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004946 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004947}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004948
4949/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004950void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4951 bool ShowColors) const {
4952 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004953}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004954
Yaron Kerencdae9412016-01-29 19:38:18 +00004955LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00004956 dump(getParent(), LangOptions(), false);
4957}
4958
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004959/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4960/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004961void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004962 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004963 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004964 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004965 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004966}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004967
Ted Kremenek15647632008-01-30 23:02:42 +00004968/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004969void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004970 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004971 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004972 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004973}
4974
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004975Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004976 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004977 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004978 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004979
Craig Topper25542942014-05-20 04:30:07 +00004980 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004981
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004982 switch (Terminator->getStmtClass()) {
4983 default:
4984 break;
Mike Stump31feda52009-07-17 01:31:16 +00004985
Jordan Rosecf10ea82013-06-06 21:53:45 +00004986 case Stmt::CXXForRangeStmtClass:
4987 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4988 break;
4989
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004990 case Stmt::ForStmtClass:
4991 E = cast<ForStmt>(Terminator)->getCond();
4992 break;
Mike Stump31feda52009-07-17 01:31:16 +00004993
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004994 case Stmt::WhileStmtClass:
4995 E = cast<WhileStmt>(Terminator)->getCond();
4996 break;
Mike Stump31feda52009-07-17 01:31:16 +00004997
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004998 case Stmt::DoStmtClass:
4999 E = cast<DoStmt>(Terminator)->getCond();
5000 break;
Mike Stump31feda52009-07-17 01:31:16 +00005001
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005002 case Stmt::IfStmtClass:
5003 E = cast<IfStmt>(Terminator)->getCond();
5004 break;
Mike Stump31feda52009-07-17 01:31:16 +00005005
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005006 case Stmt::ChooseExprClass:
5007 E = cast<ChooseExpr>(Terminator)->getCond();
5008 break;
Mike Stump31feda52009-07-17 01:31:16 +00005009
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005010 case Stmt::IndirectGotoStmtClass:
5011 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5012 break;
Mike Stump31feda52009-07-17 01:31:16 +00005013
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005014 case Stmt::SwitchStmtClass:
5015 E = cast<SwitchStmt>(Terminator)->getCond();
5016 break;
Mike Stump31feda52009-07-17 01:31:16 +00005017
John McCallc07a0c72011-02-17 10:25:35 +00005018 case Stmt::BinaryConditionalOperatorClass:
5019 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5020 break;
5021
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005022 case Stmt::ConditionalOperatorClass:
5023 E = cast<ConditionalOperator>(Terminator)->getCond();
5024 break;
Mike Stump31feda52009-07-17 01:31:16 +00005025
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005026 case Stmt::BinaryOperatorClass: // '&&' and '||'
5027 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005028 break;
Mike Stump31feda52009-07-17 01:31:16 +00005029
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005030 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00005031 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005032 }
Mike Stump31feda52009-07-17 01:31:16 +00005033
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005034 if (!StripParens)
5035 return E;
5036
Craig Topper25542942014-05-20 04:30:07 +00005037 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005038}
5039
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005040//===----------------------------------------------------------------------===//
5041// CFG Graphviz Visualization
5042//===----------------------------------------------------------------------===//
5043
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005044#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005045static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005046#endif
5047
Chris Lattnerc61089a2009-06-30 01:26:17 +00005048void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005049#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005050 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005051 GraphHelper = &H;
5052 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005053 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005054#endif
5055}
5056
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005057namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005058
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005059template<>
5060struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005061 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005062
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005063 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005064#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005065 std::string OutSStr;
5066 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005067 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005068 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005069
5070 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5071
5072 // Process string output to make it nicer...
5073 for (unsigned i = 0; i != OutStr.length(); ++i)
5074 if (OutStr[i] == '\n') { // Left justify
5075 OutStr[i] = '\\';
5076 OutStr.insert(OutStr.begin()+i+1, 'l');
5077 }
Mike Stump31feda52009-07-17 01:31:16 +00005078
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005079 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005080#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005081 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005082#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005083 }
5084};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005085
5086} // namespace llvm