blob: cef75e91f43410a06117410fc3aea2534035474a [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"
Artem Dergachev40684812018-02-27 20:03:35 +000032#include "clang/Analysis/ConstructionContext.h"
Jordan Rose5374c072013-08-19 16:27:28 +000033#include "clang/Basic/Builtins.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000034#include "clang/Basic/ExceptionSpecificationType.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/APSInt.h"
41#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000042#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000043#include "llvm/ADT/Optional.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SetVector.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000046#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000047#include "llvm/ADT/SmallVector.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000048#include "llvm/Support/Allocator.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000049#include "llvm/Support/Casting.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/DOTGraphTraits.h"
52#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000053#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000054#include "llvm/Support/GraphWriter.h"
55#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000056#include "llvm/Support/raw_ostream.h"
57#include <cassert>
58#include <memory>
59#include <string>
60#include <tuple>
61#include <utility>
62#include <vector>
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000063
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000064using namespace clang;
65
Ted Kremenek5ef32db2011-08-12 23:37:29 +000066static SourceLocation GetEndLoc(Decl *D) {
67 if (VarDecl *VD = dyn_cast<VarDecl>(D))
68 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000069 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000070 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000071}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000072
George Burgess IVced56e62015-10-01 18:47:52 +000073/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
74/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
Eugene Zelenko38c70522017-12-07 21:55:09 +000075static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
George Burgess IVced56e62015-10-01 18:47:52 +000076 E = E->IgnoreParens();
77 if (isa<IntegerLiteral>(E))
78 return E;
79 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
80 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
81 return nullptr;
82}
83
84/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
85/// an integer literal or an enum constant.
86///
87/// If this fails, at least one of the returned DeclRefExpr or Expr will be
88/// null.
89static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
90tryNormalizeBinaryOperator(const BinaryOperator *B) {
91 BinaryOperatorKind Op = B->getOpcode();
92
93 const Expr *MaybeDecl = B->getLHS();
94 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
95 // Expr looked like `0 == Foo` instead of `Foo == 0`
96 if (Constant == nullptr) {
97 // Flip the operator
98 if (Op == BO_GT)
99 Op = BO_LT;
100 else if (Op == BO_GE)
101 Op = BO_LE;
102 else if (Op == BO_LT)
103 Op = BO_GT;
104 else if (Op == BO_LE)
105 Op = BO_GE;
106
107 MaybeDecl = B->getRHS();
108 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
109 }
110
111 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
112 return std::make_tuple(D, Op, Constant);
113}
114
115/// For an expression `x == Foo && x == Bar`, this determines whether the
116/// `Foo` and `Bar` are either of the same enumeration type, or both integer
117/// literals.
118///
119/// It's an error to pass this arguments that are not either IntegerLiterals
120/// or DeclRefExprs (that have decls of type EnumConstantDecl)
121static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
122 // User intent isn't clear if they're mixing int literals with enum
123 // constants.
124 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
125 return false;
126
127 // Integer literal comparisons, regardless of literal type, are acceptable.
128 if (isa<IntegerLiteral>(E1))
129 return true;
130
131 // IntegerLiterals are handled above and only EnumConstantDecls are expected
132 // beyond this point
133 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
134 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
135 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
136
137 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
138 const DeclContext *DC1 = Decl1->getDeclContext();
139 const DeclContext *DC2 = Decl2->getDeclContext();
140
141 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
142 return DC1 == DC2;
143}
144
Eugene Zelenko38c70522017-12-07 21:55:09 +0000145namespace {
146
Ted Kremenek7c58d352011-03-10 01:14:11 +0000147class CFGBuilder;
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000149/// The CFG builder uses a recursive algorithm to build the CFG. When
150/// we process an expression, sometimes we know that we must add the
151/// subexpressions as block-level expressions. For example:
152///
153/// exp1 || exp2
154///
155/// When processing the '||' expression, we know that exp1 and exp2
156/// need to be added as block-level expressions, even though they
157/// might not normally need to be. AddStmtChoice records this
158/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
159/// the builder has an option not to add a subexpression as a
160/// block-level expression.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000161class AddStmtChoice {
162public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000163 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000164
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000165 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000166
Ted Kremenek7c58d352011-03-10 01:14:11 +0000167 bool alwaysAdd(CFGBuilder &builder,
168 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000169
170 /// Return a copy of this object, except with the 'always-add' bit
171 /// set as specified.
172 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000173 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000174 }
175
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000176private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000177 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000178};
Mike Stump31feda52009-07-17 01:31:16 +0000179
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000180/// LocalScope - Node in tree of local scopes created for C++ implicit
181/// destructor calls generation. It contains list of automatic variables
182/// declared in the scope and link to position in previous scope this scope
183/// began in.
184///
185/// The process of creating local scopes is as follows:
186/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
187/// - Before processing statements in scope (e.g. CompoundStmt) create
188/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
189/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000190/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000191/// at this VarDecl,
192/// - For every normal (without jump) end of scope add to CFGBlock destructors
193/// for objects in the current scope,
194/// - For every jump add to CFGBlock destructors for objects
195/// between CFGBuilder::ScopePos and local scope position saved for jump
196/// target. Thanks to C++ restrictions on goto jumps we can be sure that
197/// jump target position will be on the path to root from CFGBuilder::ScopePos
198/// (adding any variable that doesn't need constructor to be called to
199/// LocalScope can break this assumption),
200///
201class LocalScope {
202public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000203 friend class const_iterator;
204
205 using AutomaticVarsTy = BumpVector<VarDecl *>;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000206
207 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000208 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209 class const_iterator {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000210 const LocalScope* Scope = nullptr;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000211
212 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
213 /// Invalid iterator (with null Scope) has VarIter equal to 0.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000214 unsigned VarIter = 0;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000215
216 public:
217 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
218 /// Incrementing invalid iterator is allowed and will result in invalid
219 /// iterator.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000220 const_iterator() = default;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000221
222 /// Create valid iterator. In case when S.Prev is an invalid iterator and
223 /// I is equal to 0, this will create invalid iterator.
224 const_iterator(const LocalScope& S, unsigned I)
225 : Scope(&S), VarIter(I) {
226 // Iterator to "end" of scope is not allowed. Handle it by going up
227 // in scopes tree possibly up to invalid iterator in the root.
228 if (VarIter == 0 && Scope)
229 *this = Scope->Prev;
230 }
231
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000232 VarDecl *const* operator->() const {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000233 assert(Scope && "Dereferencing invalid iterator is not allowed");
234 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000235 return &Scope->Vars[VarIter - 1];
236 }
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000237
238 const VarDecl *getFirstVarInScope() const {
239 assert(Scope && "Dereferencing invalid iterator is not allowed");
240 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
241 return Scope->Vars[0];
242 }
243
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000244 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000245 return *this->operator->();
246 }
247
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000248 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000249 if (!Scope)
250 return *this;
251
Eugene Zelenko38c70522017-12-07 21:55:09 +0000252 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000253 --VarIter;
254 if (VarIter == 0)
255 *this = Scope->Prev;
256 return *this;
257 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000258 const_iterator operator++(int) {
259 const_iterator P = *this;
260 ++*this;
261 return P;
262 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000263
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000264 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000265 return Scope == rhs.Scope && VarIter == rhs.VarIter;
266 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000267 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000268 return !(*this == rhs);
269 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000270
Aaron Ballman67347662015-02-15 22:00:28 +0000271 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000272 return *this != const_iterator();
273 }
274
275 int distance(const_iterator L);
Matthias Gehre351c2182017-07-12 07:04:19 +0000276 const_iterator shared_parent(const_iterator L);
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000277 bool pointsToFirstDeclaredVar() { return VarIter == 1; }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000278 };
279
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000280private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000281 BumpVectorContext ctx;
Fangrui Song6907ce22018-07-30 19:24:48 +0000282
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000283 /// Automatic variables in order of declaration.
284 AutomaticVarsTy Vars;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000285
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000286 /// Iterator to variable in previous scope that was declared just before
287 /// begin of this scope.
288 const_iterator Prev;
289
290public:
291 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000292 LocalScope(BumpVectorContext ctx, const_iterator P)
293 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000294
295 /// Begin of scope in direction of CFG building (backwards).
296 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000297
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000298 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000299 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000300 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000301};
302
Eugene Zelenko38c70522017-12-07 21:55:09 +0000303} // namespace
304
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000305/// distance - Calculates distance from this to L. L must be reachable from this
306/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
307/// number of scopes between this and L.
308int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
309 int D = 0;
310 const_iterator F = *this;
311 while (F.Scope != L.Scope) {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000312 assert(F != const_iterator() &&
313 "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000314 D += F.VarIter;
315 F = F.Scope->Prev;
316 }
317 D += F.VarIter - L.VarIter;
318 return D;
319}
320
Matthias Gehre351c2182017-07-12 07:04:19 +0000321/// Calculates the closest parent of this iterator
322/// that is in a scope reachable through the parents of L.
323/// I.e. when using 'goto' from this to L, the lifetime of all variables
324/// between this and shared_parent(L) end.
325LocalScope::const_iterator
326LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
327 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
328 while (true) {
329 ScopesOfL.insert(L.Scope);
330 if (L == const_iterator())
331 break;
332 L = L.Scope->Prev;
333 }
334
335 const_iterator F = *this;
336 while (true) {
337 if (ScopesOfL.count(F.Scope))
338 return F;
339 assert(F != const_iterator() &&
340 "L iterator is not reachable from F iterator.");
341 F = F.Scope->Prev;
342 }
343}
344
Eugene Zelenko38c70522017-12-07 21:55:09 +0000345namespace {
346
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000347/// Structure for specifying position in CFG during its build process. It
348/// consists of CFGBlock that specifies position in CFG and
349/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000350struct BlockScopePosPair {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000351 CFGBlock *block = nullptr;
352 LocalScope::const_iterator scopePosition;
353
354 BlockScopePosPair() = default;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000355 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000356 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000357};
358
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000359/// TryResult - a class representing a variant over the values
360/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
361/// and is used by the CFGBuilder to decide if a branch condition
362/// can be decided up front during CFG construction.
363class TryResult {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000364 int X = -1;
365
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000366public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000367 TryResult() = default;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000368 TryResult(bool b) : X(b ? 1 : 0) {}
Fangrui Song6907ce22018-07-30 19:24:48 +0000369
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000370 bool isTrue() const { return X == 1; }
371 bool isFalse() const { return X == 0; }
372 bool isKnown() const { return X >= 0; }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000373
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000374 void negate() {
375 assert(isKnown());
376 X ^= 0x1;
377 }
378};
379
Eugene Zelenko38c70522017-12-07 21:55:09 +0000380} // namespace
381
382static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000383 if (!R1.isKnown() || !R2.isKnown())
384 return TryResult();
385 return TryResult(R1.isTrue() && R2.isTrue());
386}
387
Eugene Zelenko38c70522017-12-07 21:55:09 +0000388namespace {
389
Ted Kremenek8ae67872013-02-05 22:00:19 +0000390class reverse_children {
391 llvm::SmallVector<Stmt *, 12> childrenBuf;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000392 ArrayRef<Stmt *> children;
393
Ted Kremenek8ae67872013-02-05 22:00:19 +0000394public:
395 reverse_children(Stmt *S);
396
Eugene Zelenko38c70522017-12-07 21:55:09 +0000397 using iterator = ArrayRef<Stmt *>::reverse_iterator;
398
Ted Kremenek8ae67872013-02-05 22:00:19 +0000399 iterator begin() const { return children.rbegin(); }
400 iterator end() const { return children.rend(); }
401};
402
Eugene Zelenko38c70522017-12-07 21:55:09 +0000403} // namespace
Ted Kremenek8ae67872013-02-05 22:00:19 +0000404
405reverse_children::reverse_children(Stmt *S) {
406 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
407 children = CE->getRawSubExprs();
408 return;
409 }
410 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000411 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000412 case Stmt::InitListExprClass: {
413 InitListExpr *IE = cast<InitListExpr>(S);
414 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
415 IE->getNumInits());
416 return;
417 }
418 default:
419 break;
420 }
421
422 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000423 for (Stmt *SubStmt : S->children())
424 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000425
426 // This needs to be done *after* childrenBuf has been populated.
427 children = childrenBuf;
428}
429
Eugene Zelenko38c70522017-12-07 21:55:09 +0000430namespace {
431
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000432/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000433/// The builder is stateful: an instance of the builder should be used to only
434/// construct a single CFG.
435///
436/// Example usage:
437///
438/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000439/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000440///
Mike Stump31feda52009-07-17 01:31:16 +0000441/// CFG construction is done via a recursive walk of an AST. We actually parse
442/// the AST in reverse order so that the successor of a basic block is
443/// constructed prior to its predecessor. This allows us to nicely capture
444/// implicit fall-throughs without extra basic blocks.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000445class CFGBuilder {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000446 using JumpTarget = BlockScopePosPair;
447 using JumpSource = BlockScopePosPair;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000448
Mike Stump0d76d072009-07-20 23:24:15 +0000449 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000450 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000451
Eugene Zelenko38c70522017-12-07 21:55:09 +0000452 // Current block.
453 CFGBlock *Block = nullptr;
454
455 // Block after the current block.
456 CFGBlock *Succ = nullptr;
457
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000458 JumpTarget ContinueJumpTarget;
459 JumpTarget BreakJumpTarget;
Nico Weber699670e2017-08-23 15:33:16 +0000460 JumpTarget SEHLeaveJumpTarget;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000461 CFGBlock *SwitchTerminatedBlock = nullptr;
462 CFGBlock *DefaultCaseBlock = nullptr;
Nico Weber699670e2017-08-23 15:33:16 +0000463
464 // This can point either to a try or a __try block. The frontend forbids
465 // mixing both kinds in one function, so having one for both is enough.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000466 CFGBlock *TryTerminatedBlock = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000467
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000468 // Current position in local scope.
469 LocalScope::const_iterator ScopePos;
470
471 // LabelMap records the mapping from Label expressions to their jump targets.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000472 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000473 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000474
475 // A list of blocks that end with a "goto" that must be backpatched to their
476 // resolved targets upon completion of CFG construction.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000477 using BackpatchBlocksTy = std::vector<JumpSource>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000478 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000479
Ted Kremenekeda180e22007-08-28 19:26:49 +0000480 // A list of labels whose address has been taken (for indirect gotos).
Eugene Zelenko38c70522017-12-07 21:55:09 +0000481 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000482 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000483
Artem Dergachev41ffb302018-02-08 22:58:15 +0000484 // Information about the currently visited C++ object construction site.
485 // This is set in the construction trigger and read when the constructor
Artem Dergachev1527dec2018-03-12 23:12:40 +0000486 // or a function that returns an object by value is being visited.
487 llvm::DenseMap<Expr *, const ConstructionContextLayer *>
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000488 ConstructionContextMap;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000489
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000490 using DeclsWithEndedScopeSetTy = llvm::SmallSetVector<VarDecl *, 16>;
491 DeclsWithEndedScopeSetTy DeclsWithEndedScope;
492
Eugene Zelenko38c70522017-12-07 21:55:09 +0000493 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000494 const CFG::BuildOptions &BuildOpts;
Fangrui Song6907ce22018-07-30 19:24:48 +0000495
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000496 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000497 bool switchExclusivelyCovered = false;
498 Expr::EvalResult *switchCond = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000499
Eugene Zelenko38c70522017-12-07 21:55:09 +0000500 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
501 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000502
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000503 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
504 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000505 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000506 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000507
Mike Stump31feda52009-07-17 01:31:16 +0000508public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000509 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000510 const CFG::BuildOptions &buildOpts)
511 : Context(astContext), cfg(new CFG()), // crew a new CFG
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000512 ConstructionContextMap(), BuildOpts(buildOpts) {}
513
Mike Stump31feda52009-07-17 01:31:16 +0000514
Ted Kremenek9aae5132007-08-23 21:42:29 +0000515 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000516 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000517
Ted Kremeneka099c592011-03-10 03:50:34 +0000518 bool alwaysAdd(const Stmt *stmt);
Fangrui Song6907ce22018-07-30 19:24:48 +0000519
Ted Kremenek93668002009-07-17 22:18:43 +0000520private:
521 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000522 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
523 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000524 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000525 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000526 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000527 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000528 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000529 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
530 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000531 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000532 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
533 AddStmtChoice asc);
534 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
535 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000536 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000537 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000538 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
539 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
540 AddStmtChoice asc);
541 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
542 AddStmtChoice asc);
543 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
544 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000545 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000546 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000547 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
548 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000549 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000550 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000551 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000552 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000553 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000554 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
555 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000556 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000557 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000558 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000559 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
560 Stmt *Term,
561 CFGBlock *TrueBlock,
562 CFGBlock *FalseBlock);
Artem Dergachevf43ac4c2018-02-24 02:00:30 +0000563 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
564 AddStmtChoice asc);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000565 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000566 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
567 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
568 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
569 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000570 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000571 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000572 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
John McCallfe96e0b2011-11-06 09:01:30 +0000573 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000574 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Nico Weber699670e2017-08-23 15:33:16 +0000575 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
576 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
577 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
578 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000579 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000580 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000581 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
582 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000583 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000584 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000585
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000586 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
587 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000588 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000589 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000590
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000591 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
592 const Stmt *S) {
593 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
594 appendScopeBegin(B, VD, S);
595 }
596
Manuel Klimekb5616c92014-08-07 10:42:17 +0000597 /// When creating the CFG for temporary destructors, we want to mirror the
598 /// branch structure of the corresponding constructor calls.
599 /// Thus, while visiting a statement for temporary destructors, we keep a
600 /// context to keep track of the following information:
601 /// - whether a subexpression is executed unconditionally
602 /// - if a subexpression is executed conditionally, the first
603 /// CXXBindTemporaryExpr we encounter in that subexpression (which
604 /// corresponds to the last temporary destructor we have to call for this
605 /// subexpression) and the CFG block at that point (which will become the
606 /// successor block when inserting the decision point).
607 ///
608 /// That way, we can build the branch structure for temporary destructors as
609 /// follows:
610 /// 1. If a subexpression is executed unconditionally, we add the temporary
611 /// destructor calls to the current block.
612 /// 2. If a subexpression is executed conditionally, when we encounter a
613 /// CXXBindTemporaryExpr:
614 /// a) If it is the first temporary destructor call in the subexpression,
615 /// we remember the CXXBindTemporaryExpr and the current block in the
616 /// TempDtorContext; we start a new block, and insert the temporary
617 /// destructor call.
618 /// b) Otherwise, add the temporary destructor call to the current block.
619 /// 3. When we finished visiting a conditionally executed subexpression,
620 /// and we found at least one temporary constructor during the visitation
621 /// (2.a has executed), we insert a decision block that uses the
622 /// CXXBindTemporaryExpr as terminator, and branches to the current block
623 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
624 /// branches to the stored successor.
625 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000626 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000627 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000628 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000629
630 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000631 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000632 /// conditionally executed, and it is the first one we encounter while
633 /// visiting a subexpression - other temporary destructors at the same level
634 /// will be added to the same block and are executed under the same
635 /// condition.
636 bool needsTempDtorBranch() const {
637 return IsConditional && !TerminatorExpr;
638 }
639
640 /// Remember the successor S of a temporary destructor decision branch for
641 /// the corresponding CXXBindTemporaryExpr E.
642 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
643 Succ = S;
644 TerminatorExpr = E;
645 }
646
Eugene Zelenko38c70522017-12-07 21:55:09 +0000647 const bool IsConditional = false;
648 const TryResult KnownExecuted = true;
649 CFGBlock *Succ = nullptr;
650 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000651 };
652
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000653 // Visitors to walk an AST and generate destructors of temporaries in
654 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000655 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
656 TempDtorContext &Context);
657 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
658 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
659 TempDtorContext &Context);
660 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
661 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
662 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
663 AbstractConditionalOperator *E, bool BindToTemporary,
664 TempDtorContext &Context);
665 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
666 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000667
Ted Kremenek6065ef62008-04-28 18:00:46 +0000668 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000669 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000670 badCFG = true;
671 return Block;
672 }
Mike Stump31feda52009-07-17 01:31:16 +0000673
Artem Dergachev40684812018-02-27 20:03:35 +0000674 // Remember to apply the construction context based on the current \p Layer
675 // when constructing the CFG element for \p CE.
676 void consumeConstructionContext(const ConstructionContextLayer *Layer,
Artem Dergachev1527dec2018-03-12 23:12:40 +0000677 Expr *E);
Artem Dergachevc1b07bd2018-02-23 23:38:41 +0000678
Artem Dergachev40684812018-02-27 20:03:35 +0000679 // Scan \p Child statement to find constructors in it, while keeping in mind
680 // that its parent statement is providing a partial construction context
681 // described by \p Layer. If a constructor is found, it would be assigned
682 // the context based on the layer. If an additional construction context layer
683 // is found, the function recurses into that.
684 void findConstructionContexts(const ConstructionContextLayer *Layer,
Artem Dergachev783a4572018-02-23 22:20:39 +0000685 Stmt *Child);
Artem Dergachev40684812018-02-27 20:03:35 +0000686
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000687 // Scan all arguments of a call expression for a construction context.
688 // These sorts of call expressions don't have a common superclass,
689 // hence strict duck-typing.
690 template <typename CallLikeExpr,
691 typename = typename std::enable_if<
692 std::is_same<CallLikeExpr, CallExpr>::value ||
693 std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
694 std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
695 void findConstructionContextsForArguments(CallLikeExpr *E) {
696 // A stub for the code that'll eventually be used for finding construction
697 // contexts for constructors of C++ object-type arguments passed into
698 // call-like expression E.
699 // FIXME: Once actually implemented, this construction context layer should
700 // include the index of the argument as well.
701 for (auto Arg : E->arguments())
702 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
703 findConstructionContexts(
704 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
705 Arg);
706 }
707
Artem Dergachev41ffb302018-02-08 22:58:15 +0000708 // Unset the construction context after consuming it. This is done immediately
Artem Dergachev1527dec2018-03-12 23:12:40 +0000709 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
710 // there's no need to do this manually in every Visit... function.
711 void cleanupConstructionContext(Expr *E);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000712
Ted Kremenek93668002009-07-17 22:18:43 +0000713 void autoCreateBlock() { if (!Block) Block = createBlock(); }
714 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000715 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000716
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000717 CFGBlock *addStmt(Stmt *S) {
718 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000719 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000720
Alexis Hunt1d792652011-01-08 20:30:50 +0000721 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000722 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000723 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000724 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000725 void addLifetimeEnds(LocalScope::const_iterator B,
726 LocalScope::const_iterator E, Stmt *S);
727 void addAutomaticObjHandling(LocalScope::const_iterator B,
728 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000729 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000730 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
731 Stmt *S);
732
733 void getDeclsWithEndedScope(LocalScope::const_iterator B,
734 LocalScope::const_iterator E, Stmt *S);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000735
Marcin Swiderski5e415732010-09-30 23:05:00 +0000736 // Local scopes creation.
737 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
738
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000739 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000740 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
741 LocalScope* Scope = nullptr);
742 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000743
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000744 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000745
Artem Dergacheve1f30622018-07-31 19:46:14 +0000746 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
747 if (!BuildOpts.AddRichCXXConstructors)
748 return nullptr;
749
750 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
751 if (!Layer)
752 return nullptr;
753
754 cleanupConstructionContext(E);
755 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
756 Layer);
757 }
758
Marcin Swiderski5e415732010-09-30 23:05:00 +0000759 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000760
Ted Kremenek37881932011-04-04 23:29:12 +0000761 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000762 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000763 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000764
Jordy Rose17347372011-06-10 08:49:37 +0000765 // All block-level expressions should have already been IgnoreParens()ed.
766 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000767 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000768 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000769
Artem Dergachev41ffb302018-02-08 22:58:15 +0000770 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
Artem Dergacheve1f30622018-07-31 19:46:14 +0000771 if (const ConstructionContext *CC =
772 retrieveAndCleanupConstructionContext(CE)) {
773 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
774 return;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000775 }
776
777 // No valid construction context found. Fall back to statement.
778 B->appendStmt(CE, cfg->getBumpVectorContext());
779 }
780
Artem Dergachev1527dec2018-03-12 23:12:40 +0000781 void appendCall(CFGBlock *B, CallExpr *CE) {
Richard Trieuf4a0e9a2018-03-15 00:09:26 +0000782 if (alwaysAdd(CE) && cachedEntry)
783 cachedEntry->second = B;
784
Artem Dergacheve1f30622018-07-31 19:46:14 +0000785 if (const ConstructionContext *CC =
786 retrieveAndCleanupConstructionContext(CE)) {
787 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
788 return;
Artem Dergachev1527dec2018-03-12 23:12:40 +0000789 }
790
791 // No valid construction context found. Fall back to statement.
792 B->appendStmt(CE, cfg->getBumpVectorContext());
793 }
794
Alexis Hunt1d792652011-01-08 20:30:50 +0000795 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000796 B->appendInitializer(I, cfg->getBumpVectorContext());
797 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000798
Jordan Rosec9176072014-01-13 17:59:19 +0000799 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
800 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
801 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000802
Marcin Swiderski20b88732010-10-05 05:37:00 +0000803 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
804 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
805 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000806
Marcin Swiderski20b88732010-10-05 05:37:00 +0000807 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
808 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
809 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000810
Artem Dergacheve1f30622018-07-31 19:46:14 +0000811 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
812 if (alwaysAdd(ME) && cachedEntry)
813 cachedEntry->second = B;
814
815 if (const ConstructionContext *CC =
816 retrieveAndCleanupConstructionContext(ME)) {
817 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
818 return;
819 }
820
821 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
822 cfg->getBumpVectorContext());
823 }
824
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000825 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
826 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
827 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000828
Chandler Carruthad747252011-09-13 06:09:01 +0000829 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
830 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
831 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000832
Matthias Gehre351c2182017-07-12 07:04:19 +0000833 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
834 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
835 }
836
Peter Szecsi999a25f2017-08-19 11:19:16 +0000837 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
838 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
839 }
840
Jordan Rosed2f40792013-09-03 17:00:57 +0000841 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
842 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
843 }
844
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000845 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000846 LocalScope::const_iterator B, LocalScope::const_iterator E);
847
Matthias Gehre351c2182017-07-12 07:04:19 +0000848 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
849 LocalScope::const_iterator B,
850 LocalScope::const_iterator E);
851
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000852 const VarDecl *
853 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
854 LocalScope::const_iterator B,
855 LocalScope::const_iterator E);
856
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000857 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
858 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
859 cfg->getBumpVectorContext());
860 }
861
862 /// Add a reachable successor to a block, with the alternate variant that is
863 /// unreachable.
864 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
865 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
866 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000869 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
870 if (BuildOpts.AddScopes)
871 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
872 }
873
874 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
875 if (BuildOpts.AddScopes)
876 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
877 }
878
879 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
880 if (BuildOpts.AddScopes)
881 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
882 }
883
884 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
885 if (BuildOpts.AddScopes)
886 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
887 }
888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000889 /// Find a relational comparison with an expression evaluating to a
Richard Trieuf935b562014-04-05 05:17:01 +0000890 /// boolean and a constant other than 0 and 1.
891 /// e.g. if ((x < y) == 10)
892 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
893 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
894 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
895
896 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
897 const Expr *BoolExpr = RHSExpr;
898 bool IntFirst = true;
899 if (!IntLiteral) {
900 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
901 BoolExpr = LHSExpr;
902 IntFirst = false;
903 }
904
905 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
906 return TryResult();
907
908 llvm::APInt IntValue = IntLiteral->getValue();
909 if ((IntValue == 1) || (IntValue == 0))
910 return TryResult();
911
912 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
913 !IntValue.isNegative();
914
915 BinaryOperatorKind Bok = B->getOpcode();
916 if (Bok == BO_GT || Bok == BO_GE) {
917 // Always true for 10 > bool and bool > -1
918 // Always false for -1 > bool and bool > 10
919 return TryResult(IntFirst == IntLarger);
920 } else {
921 // Always true for -1 < bool and bool < 10
922 // Always false for 10 < bool and bool < -1
923 return TryResult(IntFirst != IntLarger);
924 }
925 }
926
Jordan Rose7afd71e2014-05-20 17:31:11 +0000927 /// Find an incorrect equality comparison. Either with an expression
928 /// evaluating to a boolean and a constant other than 0 and 1.
929 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
930 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000931 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
932 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
933 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
934
935 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
936 const Expr *BoolExpr = RHSExpr;
937
938 if (!IntLiteral) {
939 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
940 BoolExpr = LHSExpr;
941 }
942
Jordan Rose7afd71e2014-05-20 17:31:11 +0000943 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000944 return TryResult();
945
Jordan Rose7afd71e2014-05-20 17:31:11 +0000946 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
947 if (BitOp && (BitOp->getOpcode() == BO_And ||
948 BitOp->getOpcode() == BO_Or)) {
949 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
950 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
951
952 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
953
954 if (!IntLiteral2)
955 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
956
957 if (!IntLiteral2)
958 return TryResult();
959
960 llvm::APInt L1 = IntLiteral->getValue();
961 llvm::APInt L2 = IntLiteral2->getValue();
962 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
963 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
964 if (BuildOpts.Observer)
965 BuildOpts.Observer->compareBitwiseEquality(B,
966 B->getOpcode() != BO_EQ);
967 TryResult(B->getOpcode() != BO_EQ);
968 }
969 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
970 llvm::APInt IntValue = IntLiteral->getValue();
971 if ((IntValue == 1) || (IntValue == 0)) {
972 return TryResult();
973 }
974 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000975 }
976
Jordan Rose7afd71e2014-05-20 17:31:11 +0000977 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000978 }
979
980 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
981 const llvm::APSInt &Value1,
982 const llvm::APSInt &Value2) {
983 assert(Value1.isSigned() == Value2.isSigned());
984 switch (Relation) {
985 default:
986 return TryResult();
987 case BO_EQ:
988 return TryResult(Value1 == Value2);
989 case BO_NE:
990 return TryResult(Value1 != Value2);
991 case BO_LT:
992 return TryResult(Value1 < Value2);
993 case BO_LE:
994 return TryResult(Value1 <= Value2);
995 case BO_GT:
996 return TryResult(Value1 > Value2);
997 case BO_GE:
998 return TryResult(Value1 >= Value2);
999 }
1000 }
1001
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001002 /// Find a pair of comparison expressions with or without parentheses
Richard Trieuf935b562014-04-05 05:17:01 +00001003 /// with a shared variable and constants and a logical operator between them
1004 /// that always evaluates to either true or false.
1005 /// e.g. if (x != 3 || x != 4)
1006 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1007 assert(B->isLogicalOp());
1008 const BinaryOperator *LHS =
1009 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
1010 const BinaryOperator *RHS =
1011 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
1012 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001013 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001014
1015 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001016 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001017
George Burgess IVced56e62015-10-01 18:47:52 +00001018 const DeclRefExpr *Decl1;
1019 const Expr *Expr1;
1020 BinaryOperatorKind BO1;
1021 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001022
George Burgess IVced56e62015-10-01 18:47:52 +00001023 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001024 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001025
George Burgess IVced56e62015-10-01 18:47:52 +00001026 const DeclRefExpr *Decl2;
1027 const Expr *Expr2;
1028 BinaryOperatorKind BO2;
1029 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001030
George Burgess IVced56e62015-10-01 18:47:52 +00001031 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001032 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001033
1034 // Check that it is the same variable on both sides.
1035 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001036 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001037
George Burgess IVced56e62015-10-01 18:47:52 +00001038 // Make sure the user's intent is clear (e.g. they're comparing against two
1039 // int literals, or two things from the same enum)
1040 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +00001041 return {};
George Burgess IVced56e62015-10-01 18:47:52 +00001042
Richard Trieuf935b562014-04-05 05:17:01 +00001043 llvm::APSInt L1, L2;
1044
George Burgess IVced56e62015-10-01 18:47:52 +00001045 if (!Expr1->EvaluateAsInt(L1, *Context) ||
1046 !Expr2->EvaluateAsInt(L2, *Context))
Eugene Zelenko38c70522017-12-07 21:55:09 +00001047 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001048
1049 // Can't compare signed with unsigned or with different bit width.
1050 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001051 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001052
1053 // Values that will be used to determine if result of logical
1054 // operator is always true/false
1055 const llvm::APSInt Values[] = {
1056 // Value less than both Value1 and Value2
1057 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1058 // L1
1059 L1,
1060 // Value between Value1 and Value2
1061 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1062 L1.isUnsigned()),
1063 // L2
1064 L2,
1065 // Value greater than both Value1 and Value2
1066 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1067 };
1068
1069 // Check whether expression is always true/false by evaluating the following
1070 // * variable x is less than the smallest literal.
1071 // * variable x is equal to the smallest literal.
1072 // * Variable x is between smallest and largest literal.
1073 // * Variable x is equal to the largest literal.
1074 // * Variable x is greater than largest literal.
1075 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001076 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +00001077 TryResult Res1, Res2;
1078 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1079 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1080
1081 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001082 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001083
1084 if (B->getOpcode() == BO_LAnd) {
1085 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1086 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1087 } else {
1088 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1089 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1090 }
1091 }
1092
1093 if (AlwaysTrue || AlwaysFalse) {
1094 if (BuildOpts.Observer)
1095 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1096 return TryResult(AlwaysTrue);
1097 }
Eugene Zelenko38c70522017-12-07 21:55:09 +00001098 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001099 }
1100
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001101 /// Try and evaluate an expression to an integer constant.
1102 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1103 if (!BuildOpts.PruneTriviallyFalseEdges)
1104 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001105 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +00001106 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +00001107 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001108 }
Mike Stump11289f42009-09-09 15:08:12 +00001109
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001110 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +00001111 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001112 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +00001113 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001114 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001115 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001116
1117 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1118 if (Bop->isLogicalOp()) {
1119 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001120 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1121 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001122 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001123
1124 // Retrieve result at first, or the map might be updated.
1125 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1126 CachedBoolEvals[S] = Result; // update or insert
1127 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001128 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001129 else {
1130 switch (Bop->getOpcode()) {
1131 default: break;
1132 // For 'x & 0' and 'x * 0', we can determine that
1133 // the value is always false.
1134 case BO_Mul:
1135 case BO_And: {
1136 // If either operand is zero, we know the value
1137 // must be false.
1138 llvm::APSInt IntVal;
1139 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001140 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001141 return TryResult(false);
1142 }
1143 }
1144 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001145 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001146 return TryResult(false);
1147 }
1148 }
1149 }
1150 break;
1151 }
1152 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001153 }
1154
1155 return evaluateAsBooleanConditionNoCache(S);
1156 }
1157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001158 /// Evaluate as boolean \param E without using the cache.
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001159 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1160 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1161 if (Bop->isLogicalOp()) {
1162 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1163 if (LHS.isKnown()) {
1164 // We were able to evaluate the LHS, see if we can get away with not
1165 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1166 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1167 return LHS.isTrue();
1168
1169 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1170 if (RHS.isKnown()) {
1171 if (Bop->getOpcode() == BO_LOr)
1172 return LHS.isTrue() || RHS.isTrue();
1173 else
1174 return LHS.isTrue() && RHS.isTrue();
1175 }
1176 } else {
1177 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1178 if (RHS.isKnown()) {
1179 // We can't evaluate the LHS; however, sometimes the result
1180 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1181 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1182 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001183 } else {
1184 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1185 if (BopRes.isKnown())
1186 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001187 }
1188 }
1189
Eugene Zelenko38c70522017-12-07 21:55:09 +00001190 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001191 } else if (Bop->isEqualityOp()) {
1192 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1193 if (BopRes.isKnown())
1194 return BopRes.isTrue();
1195 } else if (Bop->isRelationalOp()) {
1196 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1197 if (BopRes.isKnown())
1198 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001199 }
1200 }
1201
1202 bool Result;
1203 if (E->EvaluateAsBooleanCondition(Result, *Context))
1204 return Result;
1205
Eugene Zelenko38c70522017-12-07 21:55:09 +00001206 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001207 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001208
1209 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001210};
Mike Stump31feda52009-07-17 01:31:16 +00001211
Eugene Zelenko38c70522017-12-07 21:55:09 +00001212} // namespace
1213
Ted Kremeneka099c592011-03-10 03:50:34 +00001214inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1215 const Stmt *stmt) const {
1216 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1217}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001218
Ted Kremeneka099c592011-03-10 03:50:34 +00001219bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001220 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
Fangrui Song6907ce22018-07-30 19:24:48 +00001221
Ted Kremeneka099c592011-03-10 03:50:34 +00001222 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001223 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001224
Fangrui Song6907ce22018-07-30 19:24:48 +00001225 if (lastLookup == stmt) {
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001226 if (cachedEntry) {
1227 assert(cachedEntry->first == stmt);
1228 return true;
1229 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001230 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001231 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001232
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001233 lastLookup = stmt;
1234
1235 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001236 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1237
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001238 if (!fb) {
1239 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001240 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001241 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001242 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001243
1244 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001245 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001246 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001247 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001248 }
1249
Ted Kremeneka099c592011-03-10 03:50:34 +00001250 cachedEntry = &*itr;
1251 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001252}
Fangrui Song6907ce22018-07-30 19:24:48 +00001253
Douglas Gregor4619e432008-12-05 23:32:09 +00001254// FIXME: Add support for dependent-sized array types in C++?
1255// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001256static const VariableArrayType *FindVA(const Type *t) {
1257 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1258 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001259 if (vat->getSizeExpr())
1260 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001261
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001262 t = vt->getElementType().getTypePtr();
1263 }
Mike Stump31feda52009-07-17 01:31:16 +00001264
Craig Topper25542942014-05-20 04:30:07 +00001265 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001266}
Mike Stump31feda52009-07-17 01:31:16 +00001267
Artem Dergachev40684812018-02-27 20:03:35 +00001268void CFGBuilder::consumeConstructionContext(
Artem Dergachev1527dec2018-03-12 23:12:40 +00001269 const ConstructionContextLayer *Layer, Expr *E) {
Artem Dergacheve1f30622018-07-31 19:46:14 +00001270 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1271 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
Artem Dergachev40684812018-02-27 20:03:35 +00001272 if (const ConstructionContextLayer *PreviouslyStoredLayer =
Artem Dergachev1527dec2018-03-12 23:12:40 +00001273 ConstructionContextMap.lookup(E)) {
George Burgess IVa47e1b72018-03-06 07:45:11 +00001274 (void)PreviouslyStoredLayer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001275 // We might have visited this child when we were finding construction
1276 // contexts within its parents.
Artem Dergachev40684812018-02-27 20:03:35 +00001277 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001278 "Already within a different construction context!");
1279 } else {
Artem Dergachev1527dec2018-03-12 23:12:40 +00001280 ConstructionContextMap[E] = Layer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001281 }
1282}
1283
Artem Dergachev783a4572018-02-23 22:20:39 +00001284void CFGBuilder::findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001285 const ConstructionContextLayer *Layer, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001286 if (!BuildOpts.AddRichCXXConstructors)
1287 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001288
Artem Dergachev41ffb302018-02-08 22:58:15 +00001289 if (!Child)
1290 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001291
Artem Dergachevff267df2018-06-28 00:04:54 +00001292 auto withExtraLayer = [this, Layer](Stmt *S) {
1293 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), S,
1294 Layer);
1295 };
1296
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001297 switch(Child->getStmtClass()) {
1298 case Stmt::CXXConstructExprClass:
1299 case Stmt::CXXTemporaryObjectExprClass: {
Artem Dergachevff267df2018-06-28 00:04:54 +00001300 // Support pre-C++17 copy elision AST.
1301 auto *CE = cast<CXXConstructExpr>(Child);
1302 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
Artem Dergachevff267df2018-06-28 00:04:54 +00001303 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1304 }
1305
1306 consumeConstructionContext(Layer, CE);
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001307 break;
1308 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00001309 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1310 // FIXME: An isa<> would look much better but this whole switch is a
1311 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1312 case Stmt::CallExprClass:
1313 case Stmt::CXXMemberCallExprClass:
1314 case Stmt::CXXOperatorCallExprClass:
Artem Dergacheve1f30622018-07-31 19:46:14 +00001315 case Stmt::UserDefinedLiteralClass:
1316 case Stmt::ObjCMessageExprClass: {
1317 auto *E = cast<Expr>(Child);
1318 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1319 consumeConstructionContext(Layer, E);
Artem Dergachev1527dec2018-03-12 23:12:40 +00001320 break;
1321 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001322 case Stmt::ExprWithCleanupsClass: {
1323 auto *Cleanups = cast<ExprWithCleanups>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001324 findConstructionContexts(Layer, Cleanups->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001325 break;
1326 }
1327 case Stmt::CXXFunctionalCastExprClass: {
1328 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001329 findConstructionContexts(Layer, Cast->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001330 break;
1331 }
1332 case Stmt::ImplicitCastExprClass: {
1333 auto *Cast = cast<ImplicitCastExpr>(Child);
Artem Dergachev317291e2018-03-22 21:37:39 +00001334 // Should we support other implicit cast kinds?
Artem Dergachev13f96642018-03-09 01:39:59 +00001335 switch (Cast->getCastKind()) {
1336 case CK_NoOp:
1337 case CK_ConstructorConversion:
Artem Dergachev66030522018-03-01 01:09:24 +00001338 findConstructionContexts(Layer, Cast->getSubExpr());
Artem Dergachev13f96642018-03-09 01:39:59 +00001339 default:
1340 break;
1341 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001342 break;
1343 }
1344 case Stmt::CXXBindTemporaryExprClass: {
1345 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
Artem Dergachevff267df2018-06-28 00:04:54 +00001346 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1347 break;
1348 }
1349 case Stmt::MaterializeTemporaryExprClass: {
1350 // Normally we don't want to search in MaterializeTemporaryExpr because
1351 // it indicates the beginning of a temporary object construction context,
1352 // so it shouldn't be found in the middle. However, if it is the beginning
1353 // of an elidable copy or move construction context, we need to include it.
1354 if (const auto *CE =
1355 dyn_cast_or_null<CXXConstructExpr>(Layer->getTriggerStmt())) {
1356 if (CE->isElidable()) {
1357 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1358 findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr());
1359 }
1360 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001361 break;
1362 }
1363 case Stmt::ConditionalOperatorClass: {
1364 auto *CO = cast<ConditionalOperator>(Child);
Artem Dergachev9d3a7d82018-03-30 19:21:18 +00001365 if (!dyn_cast_or_null<MaterializeTemporaryExpr>(Layer->getTriggerStmt())) {
1366 // If the object returned by the conditional operator is not going to be a
1367 // temporary object that needs to be immediately materialized, then
1368 // it must be C++17 with its mandatory copy elision. Do not yet promise
1369 // to support this case.
1370 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1371 Context->getLangOpts().CPlusPlus17);
1372 break;
1373 }
Artem Dergachev40684812018-02-27 20:03:35 +00001374 findConstructionContexts(Layer, CO->getLHS());
1375 findConstructionContexts(Layer, CO->getRHS());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001376 break;
1377 }
1378 default:
1379 break;
Artem Dergachev41ffb302018-02-08 22:58:15 +00001380 }
1381}
1382
Artem Dergachev1527dec2018-03-12 23:12:40 +00001383void CFGBuilder::cleanupConstructionContext(Expr *E) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001384 assert(BuildOpts.AddRichCXXConstructors &&
1385 "We should not be managing construction contexts!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001386 assert(ConstructionContextMap.count(E) &&
Artem Dergachev41ffb302018-02-08 22:58:15 +00001387 "Cannot exit construction context without the context!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001388 ConstructionContextMap.erase(E);
Artem Dergachev41ffb302018-02-08 22:58:15 +00001389}
1390
1391
Mike Stump31feda52009-07-17 01:31:16 +00001392/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1393/// arbitrary statement. Examples include a single expression or a function
1394/// body (compound statement). The ownership of the returned CFG is
1395/// transferred to the caller. If CFG construction fails, this method returns
1396/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001397std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001398 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001399 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001400 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001401
Mike Stump31feda52009-07-17 01:31:16 +00001402 // Create an empty block that will serve as the exit block for the CFG. Since
1403 // this is the first block added to the CFG, it will be implicitly registered
1404 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001405 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001406 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001407 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001408
Matthias Gehre351c2182017-07-12 07:04:19 +00001409 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1410 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1411
Marcin Swiderski20b88732010-10-05 05:37:00 +00001412 if (BuildOpts.AddImplicitDtors)
1413 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1414 addImplicitDtorsForDestructor(DD);
1415
Ted Kremenek9aae5132007-08-23 21:42:29 +00001416 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001417 CFGBlock *B = addStmt(Statement);
1418
1419 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001420 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001421
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001422 // For C++ constructor add initializers to CFG.
1423 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001424 for (auto *I : llvm::reverse(CD->inits())) {
1425 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001426 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001427 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001428 }
1429 }
1430
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001431 if (B)
1432 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001433
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001434 // Backpatch the gotos whose label -> block mappings we didn't know when we
1435 // encountered them.
1436 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1437 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001438
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001439 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001440 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001441 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001442
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001443 // If there is no target for the goto, then we are looking at an
1444 // incomplete AST. Handle this by not registering a successor.
1445 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001446
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001447 JumpTarget JT = LI->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00001448 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1449 JT.scopePosition);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001450 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1451 JT.scopePosition);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001452 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
1453 B, I->scopePosition, JT.scopePosition);
1454 appendScopeBegin(JT.block, VD, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001455 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001456 }
1457
1458 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001459 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001460 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1461 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001462 // Lookup the target block.
1463 LabelMapTy::iterator LI = LabelMap.find(*I);
1464
1465 // If there is no target block that contains label, then we are looking
1466 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001467 if (LI == LabelMap.end()) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001468
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001469 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001470 }
Mike Stump31feda52009-07-17 01:31:16 +00001471
Mike Stump31feda52009-07-17 01:31:16 +00001472 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001473 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001474
Artem Dergachev783a4572018-02-23 22:20:39 +00001475 if (BuildOpts.AddRichCXXConstructors)
1476 assert(ConstructionContextMap.empty() &&
1477 "Not all construction contexts were cleaned up!");
1478
David Blaikiee90195c2014-08-29 18:53:26 +00001479 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001480}
Mike Stump31feda52009-07-17 01:31:16 +00001481
Ted Kremenek9aae5132007-08-23 21:42:29 +00001482/// createBlock - Used to lazily create blocks that are connected
1483/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001484CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1485 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001486 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001487 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001488 return B;
1489}
Mike Stump31feda52009-07-17 01:31:16 +00001490
Chandler Carrutha70991b2011-09-13 09:13:49 +00001491/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1492/// CFG. It is *not* connected to the current (global) successor, and instead
1493/// directly tied to the exit block in order to be reachable.
1494CFGBlock *CFGBuilder::createNoReturnBlock() {
1495 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001496 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001497 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001498 return B;
1499}
1500
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001501/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001502CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001503 if (!BuildOpts.AddInitializers)
1504 return Block;
1505
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001506 bool HasTemporaries = false;
1507
1508 // Destructors of temporaries in initialization expression should be called
1509 // after initialization finishes.
1510 Expr *Init = I->getInit();
1511 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001512 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001513
Jordan Rose6d671cc2012-09-05 22:55:23 +00001514 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001515 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001516 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001517 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1518 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001519 }
1520 }
1521
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001522 autoCreateBlock();
1523 appendInitializer(Block, I);
1524
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001525 if (Init) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001526 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001527 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
Artem Dergachev783a4572018-02-23 22:20:39 +00001528 Init);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001529
Ted Kremenek8219b822010-12-16 07:46:53 +00001530 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001531 // For expression with temporaries go directly to subexpression to omit
1532 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001533 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1534 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001535 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1536 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1537 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1538 // may cause the same Expr to appear more than once in the CFG. Doing it
1539 // here is safe because there's only one initializer per field.
1540 autoCreateBlock();
1541 appendStmt(Block, Default);
1542 if (Stmt *Child = Default->getExpr())
1543 if (CFGBlock *R = Visit(Child))
1544 Block = R;
1545 return Block;
1546 }
1547 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001548 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001549 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001550
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001551 return Block;
1552}
1553
Fangrui Song6907ce22018-07-30 19:24:48 +00001554/// Retrieve the type of the temporary object whose lifetime was
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001555/// extended by a local reference with the given initializer.
Artem Dergacheva25809f2018-06-04 18:56:25 +00001556static QualType getReferenceInitTemporaryType(const Expr *Init,
Richard Smithb8c0f552016-12-09 18:49:13 +00001557 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001558 while (true) {
1559 // Skip parentheses.
1560 Init = Init->IgnoreParens();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001561
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001562 // Skip through cleanups.
1563 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1564 Init = EWC->getSubExpr();
1565 continue;
1566 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001567
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001568 // Skip through the temporary-materialization expression.
1569 if (const MaterializeTemporaryExpr *MTE
1570 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1571 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001572 if (FoundMTE)
1573 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001574 continue;
1575 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001576
1577 // Skip sub-object accesses into rvalues.
1578 SmallVector<const Expr *, 2> CommaLHSs;
1579 SmallVector<SubobjectAdjustment, 2> Adjustments;
1580 const Expr *SkippedInit =
1581 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1582 if (SkippedInit != Init) {
1583 Init = SkippedInit;
1584 continue;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001585 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001586
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001587 break;
1588 }
1589
1590 return Init->getType();
1591}
Matthias Gehre351c2182017-07-12 07:04:19 +00001592
Peter Szecsi999a25f2017-08-19 11:19:16 +00001593// TODO: Support adding LoopExit element to the CFG in case where the loop is
1594// ended by ReturnStmt, GotoStmt or ThrowExpr.
1595void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1596 if(!BuildOpts.AddLoopExit)
1597 return;
1598 autoCreateBlock();
1599 appendLoopExit(Block, LoopStmt);
1600}
1601
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001602void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
1603 LocalScope::const_iterator E, Stmt *S) {
1604 if (!BuildOpts.AddScopes)
1605 return;
1606
1607 if (B == E)
1608 return;
1609
1610 // To go from B to E, one first goes up the scopes from B to P
1611 // then sideways in one scope from P to P' and then down
1612 // the scopes from P' to E.
1613 // The lifetime of all objects between B and P end.
1614 LocalScope::const_iterator P = B.shared_parent(E);
1615 int Dist = B.distance(P);
1616 if (Dist <= 0)
1617 return;
1618
1619 for (LocalScope::const_iterator I = B; I != P; ++I)
1620 if (I.pointsToFirstDeclaredVar())
1621 DeclsWithEndedScope.insert(*I);
1622}
1623
Matthias Gehre351c2182017-07-12 07:04:19 +00001624void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1625 LocalScope::const_iterator E,
1626 Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001627 getDeclsWithEndedScope(B, E, S);
1628 if (BuildOpts.AddScopes)
1629 addScopesEnd(B, E, S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001630 if (BuildOpts.AddImplicitDtors)
1631 addAutomaticObjDtors(B, E, S);
1632 if (BuildOpts.AddLifetime)
1633 addLifetimeEnds(B, E, S);
1634}
1635
1636/// Add to current block automatic objects that leave the scope.
1637void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1638 LocalScope::const_iterator E, Stmt *S) {
1639 if (!BuildOpts.AddLifetime)
1640 return;
1641
1642 if (B == E)
1643 return;
1644
1645 // To go from B to E, one first goes up the scopes from B to P
1646 // then sideways in one scope from P to P' and then down
1647 // the scopes from P' to E.
1648 // The lifetime of all objects between B and P end.
1649 LocalScope::const_iterator P = B.shared_parent(E);
1650 int dist = B.distance(P);
1651 if (dist <= 0)
1652 return;
1653
1654 // We need to perform the scope leaving in reverse order
1655 SmallVector<VarDecl *, 10> DeclsTrivial;
1656 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1657 DeclsTrivial.reserve(dist);
1658 DeclsNonTrivial.reserve(dist);
1659
1660 for (LocalScope::const_iterator I = B; I != P; ++I)
1661 if (hasTrivialDestructor(*I))
1662 DeclsTrivial.push_back(*I);
1663 else
1664 DeclsNonTrivial.push_back(*I);
1665
1666 autoCreateBlock();
1667 // object with trivial destructor end their lifetime last (when storage
1668 // duration ends)
1669 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1670 E = DeclsTrivial.rend();
1671 I != E; ++I)
1672 appendLifetimeEnds(Block, *I, S);
1673
1674 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1675 I = DeclsNonTrivial.rbegin(),
1676 E = DeclsNonTrivial.rend();
1677 I != E; ++I)
1678 appendLifetimeEnds(Block, *I, S);
1679}
1680
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001681/// Add to current block markers for ending scopes.
1682void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
1683 LocalScope::const_iterator E, Stmt *S) {
1684 // If implicit destructors are enabled, we'll add scope ends in
1685 // addAutomaticObjDtors.
1686 if (BuildOpts.AddImplicitDtors)
1687 return;
1688
1689 autoCreateBlock();
1690
1691 for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
1692 I != E; ++I)
1693 appendScopeEnd(Block, *I, S);
1694
1695 return;
1696}
1697
Marcin Swiderski5e415732010-09-30 23:05:00 +00001698/// addAutomaticObjDtors - Add to current block automatic objects destructors
1699/// for objects in range of local scope positions. Use S as trigger statement
1700/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001701void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001702 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001703 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001704 return;
1705
Marcin Swiderski5e415732010-09-30 23:05:00 +00001706 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001707 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001708
Chandler Carruthad747252011-09-13 06:09:01 +00001709 // We need to append the destructors in reverse order, but any one of them
1710 // may be a no-return destructor which changes the CFG. As a result, buffer
1711 // this sequence up and replay them in reverse order when appending onto the
1712 // CFGBlock(s).
1713 SmallVector<VarDecl*, 10> Decls;
1714 Decls.reserve(B.distance(E));
1715 for (LocalScope::const_iterator I = B; I != E; ++I)
1716 Decls.push_back(*I);
1717
1718 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1719 E = Decls.rend();
1720 I != E; ++I) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001721 if (hasTrivialDestructor(*I)) {
1722 // If AddScopes is enabled and *I is a first variable in a scope, add a
1723 // ScopeEnd marker in a Block.
1724 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
1725 autoCreateBlock();
1726 appendScopeEnd(Block, *I, S);
1727 }
1728 continue;
1729 }
Chandler Carruthad747252011-09-13 06:09:01 +00001730 // If this destructor is marked as a no-return destructor, we need to
1731 // create a new block for the destructor which does not have as a successor
1732 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001733 QualType Ty = (*I)->getType();
1734 if (Ty->isReferenceType()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00001735 Ty = getReferenceInitTemporaryType((*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001736 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001737 Ty = Context->getBaseElementType(Ty);
1738
Richard Trieu95a192a2015-05-28 00:14:02 +00001739 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001740 Block = createNoReturnBlock();
1741 else
Chandler Carruthad747252011-09-13 06:09:01 +00001742 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001743
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001744 // Add ScopeEnd just after automatic obj destructor.
1745 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
1746 appendScopeEnd(Block, *I, S);
Chandler Carruthad747252011-09-13 06:09:01 +00001747 appendAutomaticObjDtor(Block, *I, S);
1748 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001749}
1750
Marcin Swiderski20b88732010-10-05 05:37:00 +00001751/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1752/// base and member objects in destructor.
1753void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001754 assert(BuildOpts.AddImplicitDtors &&
1755 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001756 const CXXRecordDecl *RD = DD->getParent();
1757
1758 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001759 for (const auto &VI : RD->vbases()) {
1760 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001761 if (!CD->hasTrivialDestructor()) {
1762 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001763 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001764 }
1765 }
1766
1767 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001768 for (const auto &BI : RD->bases()) {
1769 if (!BI.isVirtual()) {
1770 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001771 if (!CD->hasTrivialDestructor()) {
1772 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001773 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001774 }
1775 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001776 }
1777
1778 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001779 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001780 // Check for constant size array. Set type to array element type.
1781 QualType QT = FI->getType();
1782 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1783 if (AT->getSize() == 0)
1784 continue;
1785 QT = AT->getElementType();
1786 }
1787
1788 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001789 if (!CD->hasTrivialDestructor()) {
1790 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001791 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001792 }
1793 }
1794}
1795
Marcin Swiderski5e415732010-09-30 23:05:00 +00001796/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1797/// way return valid LocalScope object.
1798LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001799 if (Scope)
1800 return Scope;
1801 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1802 return new (alloc.Allocate<LocalScope>())
1803 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001804}
1805
1806/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Fangrui Song6907ce22018-07-30 19:24:48 +00001807/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001808void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001809 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1810 !BuildOpts.AddScopes)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001811 return;
1812
Craig Topper25542942014-05-20 04:30:07 +00001813 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001814
1815 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001816 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001817 for (auto *BI : CS->body()) {
1818 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001819 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001820 Scope = addLocalScopeForDeclStmt(DS, Scope);
1821 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001822 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001823 }
1824
1825 // For any other statement scope will be implicit and as such will be
1826 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001827 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001828 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001829}
1830
1831/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1832/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001833LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001834 LocalScope* Scope) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001835 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1836 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001837 return Scope;
1838
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001839 for (auto *DI : DS->decls())
1840 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001841 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001842 return Scope;
1843}
1844
Matthias Gehre351c2182017-07-12 07:04:19 +00001845bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1846 // Check for const references bound to temporary. Set type to pointee.
1847 QualType QT = VD->getType();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001848 if (QT->isReferenceType()) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001849 // Attempt to determine whether this declaration lifetime-extends a
1850 // temporary.
1851 //
1852 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1853 // temporaries, and a single declaration can extend multiple temporaries.
1854 // We should look at the storage duration on each nested
1855 // MaterializeTemporaryExpr instead.
1856
1857 const Expr *Init = VD->getInit();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001858 if (!Init) {
1859 // Probably an exception catch-by-reference variable.
1860 // FIXME: It doesn't really mean that the object has a trivial destructor.
1861 // Also are there other cases?
Matthias Gehre351c2182017-07-12 07:04:19 +00001862 return true;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001863 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001864
Artem Dergacheva25809f2018-06-04 18:56:25 +00001865 // Lifetime-extending a temporary?
Matthias Gehre351c2182017-07-12 07:04:19 +00001866 bool FoundMTE = false;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001867 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
Matthias Gehre351c2182017-07-12 07:04:19 +00001868 if (!FoundMTE)
1869 return true;
1870 }
1871
1872 // Check for constant size array. Set type to array element type.
1873 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1874 if (AT->getSize() == 0)
1875 return true;
1876 QT = AT->getElementType();
1877 }
1878
1879 // Check if type is a C++ class with non-trivial destructor.
1880 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1881 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1882 return true;
1883}
1884
Marcin Swiderski5e415732010-09-30 23:05:00 +00001885/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1886/// create add scope for automatic objects and temporary objects bound to
1887/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001888LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001889 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001890 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1891 "AddImplicitDtors and AddLifetime cannot be used at the same time");
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001892 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1893 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001894 return Scope;
1895
1896 // Check if variable is local.
1897 switch (VD->getStorageClass()) {
1898 case SC_None:
1899 case SC_Auto:
1900 case SC_Register:
1901 break;
1902 default: return Scope;
1903 }
1904
Matthias Gehre351c2182017-07-12 07:04:19 +00001905 if (BuildOpts.AddImplicitDtors) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001906 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001907 // Add the variable to scope
1908 Scope = createOrReuseLocalScope(Scope);
1909 Scope->addVar(VD);
1910 ScopePos = Scope->begin();
1911 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001912 return Scope;
1913 }
1914
1915 assert(BuildOpts.AddLifetime);
1916 // Add the variable to scope
1917 Scope = createOrReuseLocalScope(Scope);
1918 Scope->addVar(VD);
1919 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001920 return Scope;
1921}
1922
1923/// addLocalScopeAndDtors - For given statement add local scope for it and
1924/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001925void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001926 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001927 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001928 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001929}
1930
Marcin Swiderski321a7072010-09-30 22:54:37 +00001931/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1932/// variables with automatic storage duration to CFGBlock's elements vector.
1933/// Elements will be prepended to physical beginning of the vector which
1934/// happens to be logical end. Use blocks terminator as statement that specifies
1935/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001936/// FIXME: This mechanism for adding automatic destructors doesn't handle
1937/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001938void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001939 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001940 if (!BuildOpts.AddImplicitDtors)
1941 return;
Chandler Carruthad747252011-09-13 06:09:01 +00001942 BumpVectorContext &C = cfg->getBumpVectorContext();
1943 CFGBlock::iterator InsertPos
1944 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1945 for (LocalScope::const_iterator I = B; I != E; ++I)
1946 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1947 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001948}
1949
Matthias Gehre351c2182017-07-12 07:04:19 +00001950/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1951/// variables with automatic storage duration to CFGBlock's elements vector.
1952/// Elements will be prepended to physical beginning of the vector which
1953/// happens to be logical end. Use blocks terminator as statement that specifies
1954/// where lifetime ends.
1955void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1956 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1957 if (!BuildOpts.AddLifetime)
1958 return;
1959 BumpVectorContext &C = cfg->getBumpVectorContext();
1960 CFGBlock::iterator InsertPos =
1961 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1962 for (LocalScope::const_iterator I = B; I != E; ++I)
1963 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1964}
Eugene Zelenko38c70522017-12-07 21:55:09 +00001965
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001966/// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
1967/// variables with automatic storage duration to CFGBlock's elements vector.
1968/// Elements will be prepended to physical beginning of the vector which
1969/// happens to be logical end. Use blocks terminator as statement that specifies
1970/// where scope ends.
1971const VarDecl *
1972CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
1973 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1974 if (!BuildOpts.AddScopes)
1975 return nullptr;
1976 BumpVectorContext &C = cfg->getBumpVectorContext();
1977 CFGBlock::iterator InsertPos =
1978 Blk->beginScopeEndInsert(Blk->end(), 1, C);
1979 LocalScope::const_iterator PlaceToInsert = B;
1980 for (LocalScope::const_iterator I = B; I != E; ++I)
1981 PlaceToInsert = I;
1982 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminator());
1983 return *PlaceToInsert;
1984}
1985
Ted Kremenek93668002009-07-17 22:18:43 +00001986/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001987/// blocks for ternary operators, &&, and ||. We also process "," and
1988/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001989CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001990 if (!S) {
1991 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001992 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001993 }
Jordy Rose17347372011-06-10 08:49:37 +00001994
1995 if (Expr *E = dyn_cast<Expr>(S))
1996 S = E->IgnoreParens();
1997
Ted Kremenek93668002009-07-17 22:18:43 +00001998 switch (S->getStmtClass()) {
1999 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002000 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002001
2002 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002003 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002004
John McCallc07a0c72011-02-17 10:25:35 +00002005 case Stmt::BinaryConditionalOperatorClass:
2006 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2007
Ted Kremenek93668002009-07-17 22:18:43 +00002008 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002009 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002010
Ted Kremenek93668002009-07-17 22:18:43 +00002011 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00002012 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002013
Ted Kremenek93668002009-07-17 22:18:43 +00002014 case Stmt::BreakStmtClass:
2015 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002016
Ted Kremenek93668002009-07-17 22:18:43 +00002017 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00002018 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00002019 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002020 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002021 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Ted Kremenek93668002009-07-17 22:18:43 +00002023 case Stmt::CaseStmtClass:
2024 return VisitCaseStmt(cast<CaseStmt>(S));
2025
2026 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002027 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002028
Ted Kremenek93668002009-07-17 22:18:43 +00002029 case Stmt::CompoundStmtClass:
2030 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002031
Ted Kremenek93668002009-07-17 22:18:43 +00002032 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002033 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002034
Ted Kremenek93668002009-07-17 22:18:43 +00002035 case Stmt::ContinueStmtClass:
2036 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002037
Ted Kremenekb27378c2010-01-19 20:40:33 +00002038 case Stmt::CXXCatchStmtClass:
2039 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2040
John McCall5d413782010-12-06 08:20:24 +00002041 case Stmt::ExprWithCleanupsClass:
2042 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00002043
Jordan Rosee5d53932012-08-23 18:10:53 +00002044 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00002045 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00002046 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2047 // called function's declaration, not by the caller. If we simply add
2048 // this expression to the CFG, we could end up with the same Expr
2049 // appearing multiple times.
2050 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00002051 //
2052 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2053 // expression to be used in the same function (through aggregate
2054 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00002055 return VisitStmt(S, asc);
2056
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002057 case Stmt::CXXBindTemporaryExprClass:
2058 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2059
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002060 case Stmt::CXXConstructExprClass:
2061 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2062
Jordan Rosec9176072014-01-13 17:59:19 +00002063 case Stmt::CXXNewExprClass:
2064 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2065
Jordan Rosed2f40792013-09-03 17:00:57 +00002066 case Stmt::CXXDeleteExprClass:
2067 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2068
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002069 case Stmt::CXXFunctionalCastExprClass:
2070 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2071
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002072 case Stmt::CXXTemporaryObjectExprClass:
2073 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2074
Ted Kremenekb27378c2010-01-19 20:40:33 +00002075 case Stmt::CXXThrowExprClass:
2076 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002077
Ted Kremenekb27378c2010-01-19 20:40:33 +00002078 case Stmt::CXXTryStmtClass:
2079 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002080
Richard Smith02e85f32011-04-14 22:09:26 +00002081 case Stmt::CXXForRangeStmtClass:
2082 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2083
Ted Kremenek93668002009-07-17 22:18:43 +00002084 case Stmt::DeclStmtClass:
2085 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002086
Ted Kremenek93668002009-07-17 22:18:43 +00002087 case Stmt::DefaultStmtClass:
2088 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002089
Ted Kremenek93668002009-07-17 22:18:43 +00002090 case Stmt::DoStmtClass:
2091 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002092
Ted Kremenek93668002009-07-17 22:18:43 +00002093 case Stmt::ForStmtClass:
2094 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002095
Ted Kremenek93668002009-07-17 22:18:43 +00002096 case Stmt::GotoStmtClass:
2097 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002098
Ted Kremenek93668002009-07-17 22:18:43 +00002099 case Stmt::IfStmtClass:
2100 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002101
Ted Kremenek8219b822010-12-16 07:46:53 +00002102 case Stmt::ImplicitCastExprClass:
2103 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002104
Ted Kremenek93668002009-07-17 22:18:43 +00002105 case Stmt::IndirectGotoStmtClass:
2106 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002107
Ted Kremenek93668002009-07-17 22:18:43 +00002108 case Stmt::LabelStmtClass:
2109 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002110
Ted Kremenekda76a942012-04-12 20:34:52 +00002111 case Stmt::LambdaExprClass:
2112 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2113
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00002114 case Stmt::MaterializeTemporaryExprClass:
2115 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2116 asc);
2117
Ted Kremenek5868ec62010-04-11 17:02:10 +00002118 case Stmt::MemberExprClass:
2119 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2120
Ted Kremenek04268232011-11-05 00:10:15 +00002121 case Stmt::NullStmtClass:
2122 return Block;
2123
Ted Kremenek93668002009-07-17 22:18:43 +00002124 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00002125 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2126
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002127 case Stmt::ObjCAutoreleasePoolStmtClass:
2128 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2129
Ted Kremenek93668002009-07-17 22:18:43 +00002130 case Stmt::ObjCAtSynchronizedStmtClass:
2131 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002132
Ted Kremenek93668002009-07-17 22:18:43 +00002133 case Stmt::ObjCAtThrowStmtClass:
2134 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002135
Ted Kremenek93668002009-07-17 22:18:43 +00002136 case Stmt::ObjCAtTryStmtClass:
2137 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002138
Ted Kremenek93668002009-07-17 22:18:43 +00002139 case Stmt::ObjCForCollectionStmtClass:
2140 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002141
Artem Dergachevbd880fe2018-07-31 19:39:37 +00002142 case Stmt::ObjCMessageExprClass:
2143 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2144
Ted Kremenek04268232011-11-05 00:10:15 +00002145 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00002146 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00002147
John McCallfe96e0b2011-11-06 09:01:30 +00002148 case Stmt::PseudoObjectExprClass:
2149 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2150
Ted Kremenek93668002009-07-17 22:18:43 +00002151 case Stmt::ReturnStmtClass:
2152 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002153
Nico Weber699670e2017-08-23 15:33:16 +00002154 case Stmt::SEHExceptStmtClass:
2155 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2156
2157 case Stmt::SEHFinallyStmtClass:
2158 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2159
2160 case Stmt::SEHLeaveStmtClass:
2161 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2162
2163 case Stmt::SEHTryStmtClass:
2164 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2165
Peter Collingbournee190dee2011-03-11 19:24:49 +00002166 case Stmt::UnaryExprOrTypeTraitExprClass:
2167 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2168 asc);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Ted Kremenek93668002009-07-17 22:18:43 +00002170 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002171 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002172
Ted Kremenek93668002009-07-17 22:18:43 +00002173 case Stmt::SwitchStmtClass:
2174 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002175
Zhanyong Wan6dace612010-11-22 08:45:56 +00002176 case Stmt::UnaryOperatorClass:
2177 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2178
Ted Kremenek93668002009-07-17 22:18:43 +00002179 case Stmt::WhileStmtClass:
2180 return VisitWhileStmt(cast<WhileStmt>(S));
2181 }
2182}
Mike Stump11289f42009-09-09 15:08:12 +00002183
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002184CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002185 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002186 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002187 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00002188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Ted Kremenek93668002009-07-17 22:18:43 +00002190 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00002191}
Mike Stump31feda52009-07-17 01:31:16 +00002192
Ted Kremenek93668002009-07-17 22:18:43 +00002193/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00002194CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2195 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00002196
Ted Kremenek8ae67872013-02-05 22:00:19 +00002197 // Visit the children in their reverse order so that they appear in
2198 // left-to-right (natural) order in the CFG.
2199 reverse_children RChildren(S);
2200 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
2201 I != E; ++I) {
2202 if (Stmt *Child = *I)
2203 if (CFGBlock *R = Visit(Child))
2204 B = R;
2205 }
2206 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00002207}
Mike Stump11289f42009-09-09 15:08:12 +00002208
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002209CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2210 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00002211 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00002212
Ted Kremenek7c58d352011-03-10 01:14:11 +00002213 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002214 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002215 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00002216 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002217
Ted Kremenek9aae5132007-08-23 21:42:29 +00002218 return Block;
2219}
Mike Stump11289f42009-09-09 15:08:12 +00002220
Zhanyong Wan6dace612010-11-22 08:45:56 +00002221CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00002222 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002223 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00002224 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002225 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00002226 }
2227
Ted Kremenek8219b822010-12-16 07:46:53 +00002228 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00002229}
2230
Ted Kremeneka16436f2012-07-14 05:04:06 +00002231CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2232 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2233 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00002234
Ted Kremeneka16436f2012-07-14 05:04:06 +00002235 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002236 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00002237
Craig Topper25542942014-05-20 04:30:07 +00002238 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2239 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002240}
2241
2242std::pair<CFGBlock*, CFGBlock*>
2243CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2244 Stmt *Term,
2245 CFGBlock *TrueBlock,
2246 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00002247 // Introspect the RHS. If it is a nested logical operation, we recursively
2248 // build the CFG using this function. Otherwise, resort to default
2249 // CFG construction behavior.
2250 Expr *RHS = B->getRHS()->IgnoreParens();
2251 CFGBlock *RHSBlock, *ExitBlock;
2252
2253 do {
2254 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2255 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002256 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002257 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2258 break;
2259 }
2260
2261 // The RHS is not a nested logical operation. Don't push the terminator
2262 // down further, but instead visit RHS and construct the respective
2263 // pieces of the CFG, and link up the RHSBlock with the terminator
2264 // we have been provided.
2265 ExitBlock = RHSBlock = createBlock(false);
2266
Richard Trieu6a6af522017-01-04 00:46:30 +00002267 // Even though KnownVal is only used in the else branch of the next
2268 // conditional, tryEvaluateBool performs additional checking on the
2269 // Expr, so it should be called unconditionally.
2270 TryResult KnownVal = tryEvaluateBool(RHS);
2271 if (!KnownVal.isKnown())
2272 KnownVal = tryEvaluateBool(B);
2273
Ted Kremenekb50e7162012-07-14 05:04:10 +00002274 if (!Term) {
2275 assert(TrueBlock == FalseBlock);
2276 addSuccessor(RHSBlock, TrueBlock);
2277 }
2278 else {
2279 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00002280 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2281 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00002282 }
2283
2284 Block = RHSBlock;
2285 RHSBlock = addStmt(RHS);
2286 }
2287 while (false);
2288
2289 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002290 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002291
2292 // Generate the blocks for evaluating the LHS.
2293 Expr *LHS = B->getLHS()->IgnoreParens();
2294
2295 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2296 if (B_LHS->isLogicalOp()) {
2297 if (B->getOpcode() == BO_LOr)
2298 FalseBlock = RHSBlock;
2299 else
2300 TrueBlock = RHSBlock;
2301
2302 // For the LHS, treat 'B' as the terminator that we want to sink
2303 // into the nested branch. The RHS always gets the top-most
2304 // terminator.
2305 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2306 }
2307
2308 // Create the block evaluating the LHS.
2309 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002310 CFGBlock *LHSBlock = createBlock(false);
2311 LHSBlock->setTerminator(B);
2312
Ted Kremeneka16436f2012-07-14 05:04:06 +00002313 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002314 CFGBlock *EntryLHSBlock = addStmt(LHS);
2315
2316 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002317 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002318
2319 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002320 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002321
2322 // Now link the LHSBlock with RHSBlock.
2323 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002324 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2325 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002326 } else {
2327 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002328 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2329 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002330 }
2331
Ted Kremenekb50e7162012-07-14 05:04:10 +00002332 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002333}
2334
2335CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2336 AddStmtChoice asc) {
2337 // && or ||
2338 if (B->isLogicalOp())
2339 return VisitLogicalOperator(B);
2340
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002341 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002342 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002343 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002344 addStmt(B->getRHS());
2345 return addStmt(B->getLHS());
2346 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002347
2348 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002349 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002350 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002351 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002352 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002353 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002354 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002355 }
Mike Stump11289f42009-09-09 15:08:12 +00002356
Ted Kremenek7c58d352011-03-10 01:14:11 +00002357 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002358 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002359 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002360 }
2361
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002362 CFGBlock *RBlock = Visit(B->getRHS());
2363 CFGBlock *LBlock = Visit(B->getLHS());
2364 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2365 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2366 // return RBlock. Otherwise we'll incorrectly return NULL.
2367 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002368}
2369
Ted Kremeneke2499842012-04-12 20:03:44 +00002370CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002371 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002372 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002373 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002374 }
2375 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002376}
2377
Ted Kremenek93668002009-07-17 22:18:43 +00002378CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2379 // "break" is a control-flow statement. Thus we stop processing the current
2380 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002381 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002382 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002383
Ted Kremenek93668002009-07-17 22:18:43 +00002384 // Now create a new block that ends with the break statement.
2385 Block = createBlock(false);
2386 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002387
Ted Kremenek93668002009-07-17 22:18:43 +00002388 // If there is no target for the break, then we are looking at an incomplete
2389 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002390 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002391 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002392 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002393 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002394 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002395
Ted Kremenek9aae5132007-08-23 21:42:29 +00002396 return Block;
2397}
Mike Stump11289f42009-09-09 15:08:12 +00002398
Sebastian Redl31ad7542011-03-13 17:09:40 +00002399static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002400 QualType Ty = E->getType();
2401 if (Ty->isFunctionPointerType())
2402 Ty = Ty->getAs<PointerType>()->getPointeeType();
2403 else if (Ty->isBlockPointerType())
2404 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002405
Mike Stump04c68512010-01-21 15:20:48 +00002406 const FunctionType *FT = Ty->getAs<FunctionType>();
2407 if (FT) {
2408 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002409 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smitheaf11ad2018-05-03 03:58:32 +00002410 Proto->isNothrow())
Mike Stump04c68512010-01-21 15:20:48 +00002411 return false;
2412 }
2413 return true;
2414}
2415
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002416CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002417 // Compute the callee type.
2418 QualType calleeType = C->getCallee()->getType();
2419 if (calleeType == Context->BoundMemberTy) {
2420 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2421
2422 // We should only get a null bound type if processing a dependent
2423 // CFG. Recover by assuming nothing.
2424 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002425 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002426
Artem Dergachevbd880fe2018-07-31 19:39:37 +00002427 findConstructionContextsForArguments(C);
Artem Dergachev72da02f2018-04-19 23:09:22 +00002428
John McCallc67067f2011-05-11 07:19:11 +00002429 // If this is a call to a no-return function, this stops the block here.
2430 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2431
Mike Stump04c68512010-01-21 15:20:48 +00002432 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002433
2434 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002435 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002436 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002437 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002438 }
2439
Jordan Rose5374c072013-08-19 16:27:28 +00002440 // If this is a call to a builtin function, it might not actually evaluate
2441 // its arguments. Don't add them to the CFG if this is the case.
2442 bool OmitArguments = false;
2443
Mike Stump92244b02010-01-19 22:00:14 +00002444 if (FunctionDecl *FD = C->getDirectCallee()) {
Nico Weber758fbac2018-02-13 21:31:47 +00002445 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
Mike Stump8c5d7992009-07-25 21:26:53 +00002446 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002447 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002448 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00002449 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2450 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002451 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002452
Sebastian Redl31ad7542011-03-13 17:09:40 +00002453 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002454 AddEHEdge = false;
2455
Jordan Rose5374c072013-08-19 16:27:28 +00002456 if (OmitArguments) {
2457 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2458 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2459 autoCreateBlock();
2460 appendStmt(Block, C);
2461 return Visit(C->getCallee());
2462 }
2463
2464 if (!NoReturn && !AddEHEdge) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00002465 autoCreateBlock();
2466 appendCall(Block, C);
2467
2468 return VisitChildren(C);
Jordan Rose5374c072013-08-19 16:27:28 +00002469 }
Mike Stump11289f42009-09-09 15:08:12 +00002470
Mike Stump92244b02010-01-19 22:00:14 +00002471 if (Block) {
2472 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002473 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002474 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002475 }
Mike Stump11289f42009-09-09 15:08:12 +00002476
Chandler Carrutha70991b2011-09-13 09:13:49 +00002477 if (NoReturn)
2478 Block = createNoReturnBlock();
2479 else
2480 Block = createBlock();
2481
Artem Dergachev1527dec2018-03-12 23:12:40 +00002482 appendCall(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002483
Mike Stump04c68512010-01-21 15:20:48 +00002484 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002485 // Add exceptional edges.
2486 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002487 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002488 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002489 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002490 }
Mike Stump11289f42009-09-09 15:08:12 +00002491
Mike Stump8c5d7992009-07-25 21:26:53 +00002492 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002493}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002494
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002495CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2496 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002497 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002498 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002499 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002500 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002501
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002502 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002503 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002504 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002505 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002506 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002507 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Ted Kremenek21822592009-07-17 18:20:32 +00002509 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002510 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002511 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002512 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002513 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002514
Ted Kremenek21822592009-07-17 18:20:32 +00002515 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002516 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002517 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002518 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2519 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002520 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002521 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002522}
Mike Stump11289f42009-09-09 15:08:12 +00002523
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002524CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002525 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002526 addLocalScopeForStmt(C);
2527
Matthias Gehre09a134e2015-11-14 00:36:50 +00002528 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002529 // If the body ends with a ReturnStmt, the dtors will be added in
2530 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002531 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002532 }
2533
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002534 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002535
2536 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2537 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002538 // If we hit a segment of code just containing ';' (NullStmts), we can
2539 // get a null block back. In such cases, just use the LastBlock
2540 if (CFGBlock *newBlock = addStmt(*I))
2541 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002542
Ted Kremenekce499c22009-08-27 23:16:26 +00002543 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002544 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002545 }
Mike Stump92244b02010-01-19 22:00:14 +00002546
Ted Kremenek93668002009-07-17 22:18:43 +00002547 return LastBlock;
2548}
Mike Stump11289f42009-09-09 15:08:12 +00002549
John McCallc07a0c72011-02-17 10:25:35 +00002550CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002551 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002552 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002553 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002554
Ted Kremenek51d40b02009-07-17 18:15:54 +00002555 // Create the confluence block that will "merge" the results of the ternary
2556 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002557 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002558 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002559 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002560 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002561
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002562 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002563
Ted Kremenek51d40b02009-07-17 18:15:54 +00002564 // Create a block for the LHS expression if there is an LHS expression. A
2565 // GCC extension allows LHS to be NULL, causing the condition to be the
2566 // value that is returned instead.
2567 // e.g: x ?: y is shorthand for: x ? x : y;
2568 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002569 Block = nullptr;
2570 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002571 const Expr *trueExpr = C->getTrueExpr();
2572 if (trueExpr != opaqueValue) {
2573 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002574 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002575 return nullptr;
2576 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002577 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002578 else
2579 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002580
Ted Kremenek51d40b02009-07-17 18:15:54 +00002581 // Create the block for the RHS expression.
2582 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002583 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002584 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002585 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002586
Richard Smithf676e452012-07-24 21:02:14 +00002587 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2588 if (BinaryOperator *Cond =
2589 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2590 if (Cond->isLogicalOp())
2591 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2592
Ted Kremenek51d40b02009-07-17 18:15:54 +00002593 // Create the block that will contain the condition.
2594 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002595
Mike Stump773582d2009-07-23 23:25:26 +00002596 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002597 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002598 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2599 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002600 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002601 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002602
Ted Kremenekd8138012011-02-24 03:09:15 +00002603 if (opaqueValue) {
2604 // Run the condition expression if it's not trivially expressed in
2605 // terms of the opaque value (or if there is no opaque value).
2606 if (condExpr != opaqueValue)
2607 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002608
Ted Kremenekd8138012011-02-24 03:09:15 +00002609 // Before that, run the common subexpression if there was one.
2610 // At least one of this or the above will be run.
2611 return addStmt(BCO->getCommon());
2612 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002613
Ted Kremenekd8138012011-02-24 03:09:15 +00002614 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002615}
2616
Ted Kremenek93668002009-07-17 22:18:43 +00002617CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002618 // Check if the Decl is for an __label__. If so, elide it from the
2619 // CFG entirely.
2620 if (isa<LabelDecl>(*DS->decl_begin()))
2621 return Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00002622
Ted Kremenek3a601142011-05-24 20:41:31 +00002623 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002624 if (DS->isSingleDecl())
2625 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002626
Craig Topper25542942014-05-20 04:30:07 +00002627 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002628
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002629 // Build an individual DeclStmt for each decl.
2630 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2631 E = DS->decl_rend();
2632 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002633 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
Benjamin Kramerc3f89252016-10-20 14:27:22 +00002634 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002635
Ted Kremenek93668002009-07-17 22:18:43 +00002636 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2637 // automatically freed with the CFG.
2638 DeclGroupRef DG(*I);
2639 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002640 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002641 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002642 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002643
Ted Kremenek93668002009-07-17 22:18:43 +00002644 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002645 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002646 }
Mike Stump11289f42009-09-09 15:08:12 +00002647
2648 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002649}
Mike Stump11289f42009-09-09 15:08:12 +00002650
Ted Kremenek93668002009-07-17 22:18:43 +00002651/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002652/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002653CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002654 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002655 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002656
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002657 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002658 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2659 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002660 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002661 }
Mike Stump11289f42009-09-09 15:08:12 +00002662
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002663 bool HasTemporaries = false;
2664
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002665 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002666 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002667
2668 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2669 // For static variables, we need to create a branch to track
2670 // whether or not they are initialized.
2671 if (Block) {
2672 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002673 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002674 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002675 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002676 }
2677 blockAfterStaticInit = Succ;
2678 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002679
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002680 // Destructors of temporaries in initialization expression should be called
2681 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002682 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002683 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002684 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002685
Jordan Rose6d671cc2012-09-05 22:55:23 +00002686 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002687 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002688 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002689 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2690 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002691 }
2692 }
2693
2694 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002695 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002696
Artem Dergachev783a4572018-02-23 22:20:39 +00002697 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00002698 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Artem Dergachev783a4572018-02-23 22:20:39 +00002699 Init);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002700
Ted Kremenek213d0532012-03-22 05:57:43 +00002701 // Keep track of the last non-null block, as 'Block' can be nulled out
2702 // if the initializer expression is something like a 'while' in a
2703 // statement-expression.
2704 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002705
Ted Kremenek93668002009-07-17 22:18:43 +00002706 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002707 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002708 // For expression with temporaries go directly to subexpression to omit
2709 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002710 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2711 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2712 LastBlock = newBlock;
2713 }
2714 else {
2715 if (CFGBlock *newBlock = Visit(Init))
2716 LastBlock = newBlock;
2717 }
Ted Kremenek93668002009-07-17 22:18:43 +00002718 }
Mike Stump11289f42009-09-09 15:08:12 +00002719
Ted Kremenek93668002009-07-17 22:18:43 +00002720 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002721 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002722 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002723 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2724 LastBlock = newBlock;
2725 }
Mike Stump11289f42009-09-09 15:08:12 +00002726
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002727 maybeAddScopeBeginForVarDecl(Block, VD, DS);
2728
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002729 // Remove variable from local scope.
2730 if (ScopePos && VD == *ScopePos)
2731 ++ScopePos;
2732
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002733 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002734 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002735 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002736 Block = createBlock(false);
2737 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002738 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002739 addSuccessor(Block, B);
2740 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002741 }
2742
2743 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002744}
2745
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002746CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002747 // We may see an if statement in the middle of a basic block, or it may be the
2748 // first statement we are processing. In either case, we create a new basic
2749 // block. First, we create the blocks for the then...else statements, and
2750 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002751 // middle of a block, we stop processing that block. That block is then the
2752 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002753
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002754 // Save local scope position because in case of condition variable ScopePos
2755 // won't be restored when traversing AST.
2756 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2757
Richard Smitha547eb22016-07-14 00:11:03 +00002758 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002759 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002760 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002761
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002762 // Create local scope for possible condition variable.
2763 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002764 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002765 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002766
Matthias Gehre351c2182017-07-12 07:04:19 +00002767 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002768
Chris Lattner57540c52011-04-15 05:22:18 +00002769 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002770 // block.
2771 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002772 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002773 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002774 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002775 }
Mike Stump31feda52009-07-17 01:31:16 +00002776
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002777 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002778 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002779
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002780 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002781 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002782
Ted Kremenek9aae5132007-08-23 21:42:29 +00002783 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002784 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002785 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002786
2787 // If branch is not a compound statement create implicit scope
2788 // and add destructors.
2789 if (!isa<CompoundStmt>(Else))
2790 addLocalScopeAndDtors(Else);
2791
Ted Kremenek93668002009-07-17 22:18:43 +00002792 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002793
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002794 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2795 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002796 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002797 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002798 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002799 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002800 }
Mike Stump31feda52009-07-17 01:31:16 +00002801
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002802 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002803 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002804 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002805 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002806 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002807 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002808 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002809
2810 // If branch is not a compound statement create implicit scope
2811 // and add destructors.
2812 if (!isa<CompoundStmt>(Then))
2813 addLocalScopeAndDtors(Then);
2814
Ted Kremenek93668002009-07-17 22:18:43 +00002815 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002816
Ted Kremenek1b379512009-04-01 03:52:47 +00002817 if (!ThenBlock) {
2818 // We can reach here if the "then" body has all NullStmts.
2819 // Create an empty block so we can distinguish between true and false
2820 // branches in path-sensitive analyses.
2821 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002822 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002823 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002824 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002825 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002826 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002827 }
2828
Ted Kremenekb50e7162012-07-14 05:04:10 +00002829 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2830 // having these handle the actual control-flow jump. Note that
2831 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2832 // we resort to the old control-flow behavior. This special handling
2833 // removes infeasible paths from the control-flow graph by having the
2834 // control-flow transfer of '&&' or '||' go directly into the then/else
2835 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002836 BinaryOperator *Cond =
2837 I->getConditionVariable()
2838 ? nullptr
2839 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2840 CFGBlock *LastBlock;
2841 if (Cond && Cond->isLogicalOp())
2842 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2843 else {
2844 // Now create a new block containing the if statement.
2845 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002846
Richard Smith509bbd12017-01-13 22:16:41 +00002847 // Set the terminator of the new block to the If statement.
2848 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002849
Richard Smith509bbd12017-01-13 22:16:41 +00002850 // See if this is a known constant.
2851 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002852
Richard Smith509bbd12017-01-13 22:16:41 +00002853 // Add the successors. If we know that specific branches are
2854 // unreachable, inform addSuccessor() of that knowledge.
2855 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2856 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002857
Richard Smith509bbd12017-01-13 22:16:41 +00002858 // Add the condition as the last statement in the new block. This may
2859 // create new blocks as the condition may contain control-flow. Any newly
2860 // created blocks will be pointed to be "Block".
2861 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002862
Richard Smith509bbd12017-01-13 22:16:41 +00002863 // If the IfStmt contains a condition variable, add it and its
2864 // initializer to the CFG.
2865 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2866 autoCreateBlock();
2867 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2868 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002869 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002870
Richard Smitha547eb22016-07-14 00:11:03 +00002871 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2872 if (Stmt *Init = I->getInit()) {
2873 autoCreateBlock();
2874 LastBlock = addStmt(Init);
2875 }
2876
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002877 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002878}
Mike Stump31feda52009-07-17 01:31:16 +00002879
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002880CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002881 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002882 //
Mike Stump31feda52009-07-17 01:31:16 +00002883 // NOTE: If a "return" appears in the middle of a block, this means that the
2884 // code afterwards is DEAD (unreachable). We still keep a basic block
2885 // for that code; a simple "mark-and-sweep" from the entry block will be
2886 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002887
2888 // Create the new block.
2889 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002890
Matthias Gehre351c2182017-07-12 07:04:19 +00002891 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002892
Artem Dergachev783a4572018-02-23 22:20:39 +00002893 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00002894 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
Artem Dergachev783a4572018-02-23 22:20:39 +00002895 R->getRetValue());
Artem Dergachev9ac2e112018-02-12 22:36:36 +00002896
Pavel Labath921e7652013-09-06 08:12:48 +00002897 // If the one of the destructors does not return, we already have the Exit
2898 // block as a successor.
2899 if (!Block->hasNoReturnElement())
2900 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002901
2902 // Add the return statement to the block. This may create new blocks if R
2903 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002904 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002905}
2906
Nico Weber699670e2017-08-23 15:33:16 +00002907CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2908 // SEHExceptStmt are treated like labels, so they are the first statement in a
2909 // block.
2910
2911 // Save local scope position because in case of exception variable ScopePos
2912 // won't be restored when traversing AST.
2913 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2914
2915 addStmt(ES->getBlock());
2916 CFGBlock *SEHExceptBlock = Block;
2917 if (!SEHExceptBlock)
2918 SEHExceptBlock = createBlock();
2919
2920 appendStmt(SEHExceptBlock, ES);
2921
2922 // Also add the SEHExceptBlock as a label, like with regular labels.
2923 SEHExceptBlock->setLabel(ES);
2924
2925 // Bail out if the CFG is bad.
2926 if (badCFG)
2927 return nullptr;
2928
2929 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2930 Block = nullptr;
2931
2932 return SEHExceptBlock;
2933}
2934
2935CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2936 return VisitCompoundStmt(FS->getBlock());
2937}
2938
2939CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2940 // "__leave" is a control-flow statement. Thus we stop processing the current
2941 // block.
2942 if (badCFG)
2943 return nullptr;
2944
2945 // Now create a new block that ends with the __leave statement.
2946 Block = createBlock(false);
2947 Block->setTerminator(LS);
2948
2949 // If there is no target for the __leave, then we are looking at an incomplete
2950 // AST. This means that the CFG cannot be constructed.
2951 if (SEHLeaveJumpTarget.block) {
2952 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2953 addSuccessor(Block, SEHLeaveJumpTarget.block);
2954 } else
2955 badCFG = true;
2956
2957 return Block;
2958}
2959
2960CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2961 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2962 // processing the current block.
2963 CFGBlock *SEHTrySuccessor = nullptr;
2964
2965 if (Block) {
2966 if (badCFG)
2967 return nullptr;
2968 SEHTrySuccessor = Block;
2969 } else SEHTrySuccessor = Succ;
2970
2971 // FIXME: Implement __finally support.
2972 if (Terminator->getFinallyHandler())
2973 return NYS();
2974
2975 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2976
2977 // Create a new block that will contain the __try statement.
2978 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2979
2980 // Add the terminator in the __try block.
2981 NewTryTerminatedBlock->setTerminator(Terminator);
2982
2983 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2984 // The code after the try is the implicit successor if there's an __except.
2985 Succ = SEHTrySuccessor;
2986 Block = nullptr;
2987 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2988 if (!ExceptBlock)
2989 return nullptr;
2990 // Add this block to the list of successors for the block with the try
2991 // statement.
2992 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2993 }
2994 if (PrevSEHTryTerminatedBlock)
2995 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2996 else
2997 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2998
2999 // The code after the try is the implicit successor.
3000 Succ = SEHTrySuccessor;
3001
3002 // Save the current "__try" context.
3003 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
3004 NewTryTerminatedBlock);
3005 cfg->addTryDispatchBlock(TryTerminatedBlock);
3006
3007 // Save the current value for the __leave target.
3008 // All __leaves should go to the code following the __try
3009 // (FIXME: or if the __try has a __finally, to the __finally.)
3010 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
3011 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3012
3013 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3014 Block = nullptr;
3015 return addStmt(Terminator->getTryBlock());
3016}
3017
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003018CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003019 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00003020 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003021 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003022
Ted Kremenek93668002009-07-17 22:18:43 +00003023 if (!LabelBlock) // This can happen when the body is empty, i.e.
3024 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00003025
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003026 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
3027 "label already in map");
3028 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003029
3030 // Labels partition blocks, so this is the end of the basic block we were
3031 // processing (L is the block's label). Because this is label (and we have
3032 // already processed the substatement) there is no extra control-flow to worry
3033 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00003034 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003035 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003036 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003037
3038 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00003039 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003040
Ted Kremenek9aae5132007-08-23 21:42:29 +00003041 // This block is now the implicit successor of other blocks.
3042 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003043
Ted Kremenek9aae5132007-08-23 21:42:29 +00003044 return LabelBlock;
3045}
3046
Devin Coughlinb6029b72015-11-25 22:35:37 +00003047CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3048 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3049 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3050 if (Expr *CopyExpr = CI.getCopyExpr()) {
3051 CFGBlock *Tmp = Visit(CopyExpr);
3052 if (Tmp)
3053 LastBlock = Tmp;
3054 }
3055 }
3056 return LastBlock;
3057}
3058
Ted Kremenekda76a942012-04-12 20:34:52 +00003059CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3060 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3061 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3062 et = E->capture_init_end(); it != et; ++it) {
3063 if (Expr *Init = *it) {
3064 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00003065 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00003066 LastBlock = Tmp;
3067 }
3068 }
3069 return LastBlock;
3070}
Fangrui Song6907ce22018-07-30 19:24:48 +00003071
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003072CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00003073 // Goto is a control-flow statement. Thus we stop processing the current
3074 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00003075
Ted Kremenek9aae5132007-08-23 21:42:29 +00003076 Block = createBlock(false);
3077 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00003078
3079 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003080 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00003081
Ted Kremenek9aae5132007-08-23 21:42:29 +00003082 if (I == LabelMap.end())
3083 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003084 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3085 else {
3086 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00003087 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003088 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003089 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00003090
Mike Stump31feda52009-07-17 01:31:16 +00003091 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003092}
3093
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003094CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00003095 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003096
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003097 // Save local scope position because in case of condition variable ScopePos
3098 // won't be restored when traversing AST.
3099 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3100
3101 // Create local scope for init statement and possible condition variable.
3102 // Add destructor for init statement and condition variable.
3103 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003104 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003105 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003106 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3107
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003108 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003109 addLocalScopeForVarDecl(VD);
3110 LocalScope::const_iterator ContinueScopePos = ScopePos;
3111
Matthias Gehre351c2182017-07-12 07:04:19 +00003112 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003113
Peter Szecsi999a25f2017-08-19 11:19:16 +00003114 addLoopExit(F);
3115
Mike Stump014b3ea2009-07-21 01:12:51 +00003116 // "for" is a control-flow statement. Thus we stop processing the current
3117 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003118 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003119 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003120 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003121 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003122 } else
3123 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003124
Ted Kremenek304a9532010-05-21 20:30:15 +00003125 // Save the current value for the break targets.
3126 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003127 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003128 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00003129
Craig Topper25542942014-05-20 04:30:07 +00003130 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003131
Ted Kremenek9aae5132007-08-23 21:42:29 +00003132 // Now create the loop body.
3133 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003134 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003135
Ted Kremenekb50e7162012-07-14 05:04:10 +00003136 // Save the current values for Block, Succ, continue and break targets.
3137 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3138 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003139
Ted Kremenekb50e7162012-07-14 05:04:10 +00003140 // Create an empty block to represent the transition block for looping back
3141 // to the head of the loop. If we have increment code, it will
3142 // go in this block as well.
3143 Block = Succ = TransitionBlock = createBlock(false);
3144 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003145
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003146 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00003147 // Generate increment code in its own basic block. This is the target of
3148 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00003149 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00003150 }
Mike Stump31feda52009-07-17 01:31:16 +00003151
Ted Kremenek902393b2009-04-28 00:51:56 +00003152 // Finish up the increment (or empty) block if it hasn't been already.
3153 if (Block) {
3154 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003155 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003156 return nullptr;
3157 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00003158 }
Mike Stump31feda52009-07-17 01:31:16 +00003159
Ted Kremenekb50e7162012-07-14 05:04:10 +00003160 // The starting block for the loop increment is the block that should
3161 // represent the 'loop target' for looping back to the start of the loop.
3162 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3163 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003164
Ted Kremenekb50e7162012-07-14 05:04:10 +00003165 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003166 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00003167
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003168 // If body is not a compound statement create implicit scope
3169 // and add destructors.
3170 if (!isa<CompoundStmt>(F->getBody()))
3171 addLocalScopeAndDtors(F->getBody());
3172
Mike Stump31feda52009-07-17 01:31:16 +00003173 // Now populate the body block, and in the process create new blocks as we
3174 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003175 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00003176
Ted Kremenekb50e7162012-07-14 05:04:10 +00003177 if (!BodyBlock) {
3178 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3179 // Use the continue jump target as the proxy for the body.
3180 BodyBlock = ContinueJumpTarget.block;
3181 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003182 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003183 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003184 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003185
Ted Kremenekb50e7162012-07-14 05:04:10 +00003186 // Because of short-circuit evaluation, the condition of the loop can span
3187 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3188 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003189 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003190
Ted Kremenekb50e7162012-07-14 05:04:10 +00003191 do {
3192 Expr *C = F->getCond();
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003193 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003194
3195 // Specially handle logical operators, which have a slightly
3196 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003197 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00003198 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003199 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003200 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00003201 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3202 break;
3203 }
3204
3205 // The default case when not handling logical operators.
3206 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3207 ExitConditionBlock->setTerminator(F);
3208
3209 // See if this is a known constant.
3210 TryResult KnownVal(true);
3211
3212 if (C) {
3213 // Now add the actual condition to the condition block.
3214 // Because the condition itself may contain control-flow, new blocks may
3215 // be created. Thus we update "Succ" after adding the condition.
3216 Block = ExitConditionBlock;
3217 EntryConditionBlock = addStmt(C);
3218
3219 // If this block contains a condition variable, add both the condition
3220 // variable and initializer to the CFG.
3221 if (VarDecl *VD = F->getConditionVariable()) {
3222 if (Expr *Init = VD->getInit()) {
3223 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003224 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3225 assert(DS->isSingleDecl());
3226 findConstructionContexts(
3227 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3228 const_cast<DeclStmt *>(DS)),
3229 Init);
3230 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003231 EntryConditionBlock = addStmt(Init);
3232 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003233 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003234 }
3235 }
3236
3237 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003238 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003239
3240 KnownVal = tryEvaluateBool(C);
3241 }
3242
3243 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003244 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003245 // Link up the condition block with the code that follows the loop. (the
3246 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003247 addSuccessor(ExitConditionBlock,
3248 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003249 } while (false);
3250
3251 // Link up the loop-back block to the entry condition block.
3252 addSuccessor(TransitionBlock, EntryConditionBlock);
Fangrui Song6907ce22018-07-30 19:24:48 +00003253
Ted Kremenekb50e7162012-07-14 05:04:10 +00003254 // The condition block is the implicit successor for any code above the loop.
3255 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003256
Ted Kremenek9aae5132007-08-23 21:42:29 +00003257 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00003258 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003259 if (Stmt *I = F->getInit()) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003260 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3261 ScopePos = LoopBeginScopePos;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003262 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00003263 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003264 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003265
3266 // There is no loop initialization. We are thus basically a while loop.
3267 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00003268 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003269 Succ = EntryConditionBlock;
3270 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003271}
3272
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003273CFGBlock *
3274CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3275 AddStmtChoice asc) {
3276 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00003277 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003278 MTE->getTemporary());
3279
3280 return VisitStmt(MTE, asc);
3281}
3282
Ted Kremenek5868ec62010-04-11 17:02:10 +00003283CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003284 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00003285 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003286 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00003287 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003288 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00003289}
3290
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003291CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00003292 // Objective-C fast enumeration 'for' statements:
3293 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3294 //
3295 // for ( Type newVariable in collection_expression ) { statements }
3296 //
3297 // becomes:
3298 //
3299 // prologue:
3300 // 1. collection_expression
3301 // T. jump to loop_entry
3302 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003303 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00003304 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3305 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3306 // TB:
3307 // statements
3308 // T. jump to loop_entry
3309 // FB:
3310 // what comes after
3311 //
3312 // and
3313 //
3314 // Type existingItem;
3315 // for ( existingItem in expression ) { statements }
3316 //
3317 // becomes:
3318 //
Mike Stump31feda52009-07-17 01:31:16 +00003319 // the same with newVariable replaced with existingItem; the binding works
3320 // the same except that for one ObjCForCollectionStmt::getElement() returns
3321 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00003322
Craig Topper25542942014-05-20 04:30:07 +00003323 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003324
Ted Kremenek9d56e642008-11-11 17:10:00 +00003325 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003326 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003327 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00003328 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003329 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003330 } else
3331 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003332
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003333 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003334 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003335
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003336 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003337 ExitConditionBlock->setTerminator(S);
3338
3339 // The last statement in the block should be the ObjCForCollectionStmt, which
3340 // performs the actual binding to 'element' and determines if there are any
3341 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003342 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003343 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003344
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003345 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003346 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003347 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003348 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3349 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003350 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003351 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003352 return nullptr;
3353 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003354 }
Mike Stump31feda52009-07-17 01:31:16 +00003355
3356 // The condition block is the implicit successor for the loop body as well as
3357 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003358 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003359
Ted Kremenek9d56e642008-11-11 17:10:00 +00003360 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003361 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003362 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003363 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003364 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003365 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003366
Anna Zaks56b49752013-06-22 00:23:20 +00003367 // Add an intermediate block between the BodyBlock and the
3368 // EntryConditionBlock to represent the "loop back" transition, for looping
3369 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003370 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003371 Succ = LoopBackBlock = createBlock();
3372 LoopBackBlock->setLoopTarget(S);
Fangrui Song6907ce22018-07-30 19:24:48 +00003373
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003374 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003375 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003376
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003377 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003378
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003379 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003380 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003381 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003382 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003383 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003384 }
Mike Stump31feda52009-07-17 01:31:16 +00003385
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003386 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003387 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003388 }
Mike Stump31feda52009-07-17 01:31:16 +00003389
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003390 // Link up the condition block with the code that follows the loop.
3391 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003392 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003393
Ted Kremenek9d56e642008-11-11 17:10:00 +00003394 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003395 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003396 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003397}
3398
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003399CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3400 // Inline the body.
3401 return addStmt(S->getSubStmt());
3402 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3403}
3404
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003405CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003406 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003407
Ted Kremenek49805452009-05-02 01:49:13 +00003408 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003409 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003410
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003411 // The sync body starts its own basic block. This makes it a little easier
3412 // for diagnostic clients.
3413 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003414 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003415 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003416
Craig Topper25542942014-05-20 04:30:07 +00003417 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003418 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003419 }
Mike Stump31feda52009-07-17 01:31:16 +00003420
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003421 // Add the @synchronized to the CFG.
3422 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003423 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003424
Ted Kremenek49805452009-05-02 01:49:13 +00003425 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003426 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003427}
Mike Stump31feda52009-07-17 01:31:16 +00003428
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003429CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003430 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003431 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003432}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003433
John McCallfe96e0b2011-11-06 09:01:30 +00003434CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3435 autoCreateBlock();
3436
3437 // Add the PseudoObject as the last thing.
3438 appendStmt(Block, E);
3439
Fangrui Song6907ce22018-07-30 19:24:48 +00003440 CFGBlock *lastBlock = Block;
John McCallfe96e0b2011-11-06 09:01:30 +00003441
3442 // Before that, evaluate all of the semantics in order. In
3443 // CFG-land, that means appending them in reverse order.
3444 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3445 Expr *Semantic = E->getSemanticExpr(--i);
3446
3447 // If the semantic is an opaque value, we're being asked to bind
3448 // it to its source expression.
3449 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3450 Semantic = OVE->getSourceExpr();
3451
3452 if (CFGBlock *B = Visit(Semantic))
3453 lastBlock = B;
3454 }
3455
3456 return lastBlock;
3457}
3458
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003459CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003460 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003461
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003462 // Save local scope position because in case of condition variable ScopePos
3463 // won't be restored when traversing AST.
3464 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3465
3466 // Create local scope for possible condition variable.
3467 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003468 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003469 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003470 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003471 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003472 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003473 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003474
Mike Stump014b3ea2009-07-21 01:12:51 +00003475 // "while" is a control-flow statement. Thus we stop processing the current
3476 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003477 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003478 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003479 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003480 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003481 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003482 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003483 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003484 }
Mike Stump31feda52009-07-17 01:31:16 +00003485
Craig Topper25542942014-05-20 04:30:07 +00003486 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003487
Ted Kremenek9aae5132007-08-23 21:42:29 +00003488 // Process the loop body.
3489 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003490 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003491
Ted Kremenekb50e7162012-07-14 05:04:10 +00003492 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003493 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3494 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003495 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003496
Mike Stump31feda52009-07-17 01:31:16 +00003497 // Create an empty block to represent the transition block for looping back
3498 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003499 Succ = TransitionBlock = createBlock(false);
3500 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003501 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003502
Ted Kremenek9aae5132007-08-23 21:42:29 +00003503 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003504 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003505
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003506 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003507 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003508
3509 // If body is not a compound statement create implicit scope
3510 // and add destructors.
3511 if (!isa<CompoundStmt>(W->getBody()))
3512 addLocalScopeAndDtors(W->getBody());
3513
Ted Kremenek9aae5132007-08-23 21:42:29 +00003514 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003515 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003516
Ted Kremeneke9610502007-08-30 18:39:40 +00003517 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003518 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003519 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003520 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003521 }
3522
3523 // Because of short-circuit evaluation, the condition of the loop can span
3524 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3525 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003526 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003527
3528 do {
3529 Expr *C = W->getCond();
3530
3531 // Specially handle logical operators, which have a slightly
3532 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003533 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003534 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003535 std::tie(EntryConditionBlock, ExitConditionBlock) =
3536 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003537 break;
3538 }
3539
3540 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003541 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003542 ExitConditionBlock->setTerminator(W);
3543
3544 // Now add the actual condition to the condition block.
3545 // Because the condition itself may contain control-flow, new blocks may
3546 // be created. Thus we update "Succ" after adding the condition.
3547 Block = ExitConditionBlock;
3548 Block = EntryConditionBlock = addStmt(C);
3549
3550 // If this block contains a condition variable, add both the condition
3551 // variable and initializer to the CFG.
3552 if (VarDecl *VD = W->getConditionVariable()) {
3553 if (Expr *Init = VD->getInit()) {
3554 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003555 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3556 assert(DS->isSingleDecl());
3557 findConstructionContexts(
3558 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3559 const_cast<DeclStmt *>(DS)),
3560 Init);
3561 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003562 EntryConditionBlock = addStmt(Init);
3563 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003564 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003565 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003566 }
Mike Stump31feda52009-07-17 01:31:16 +00003567
Ted Kremenekb50e7162012-07-14 05:04:10 +00003568 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003569 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003570
3571 // See if this is a known constant.
3572 const TryResult& KnownVal = tryEvaluateBool(C);
3573
Ted Kremenek30754282009-07-24 04:47:11 +00003574 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003575 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003576 // Link up the condition block with the code that follows the loop. (the
3577 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003578 addSuccessor(ExitConditionBlock,
3579 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003580 } while(false);
3581
3582 // Link up the loop-back block to the entry condition block.
3583 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003584
3585 // There can be no more statements in the condition block since we loop back
3586 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003587 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003588
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003589 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003590 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003591 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003592}
Mike Stump11289f42009-09-09 15:08:12 +00003593
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003594CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003595 // FIXME: For now we pretend that @catch and the code it contains does not
3596 // exit.
3597 return Block;
3598}
Mike Stump31feda52009-07-17 01:31:16 +00003599
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003600CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003601 // FIXME: This isn't complete. We basically treat @throw like a return
3602 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003603
Ted Kremenek0868eea2009-09-24 18:45:41 +00003604 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003605 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003606 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003607
Ted Kremenek93041ba2008-12-09 20:20:09 +00003608 // Create the new block.
3609 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003610
Ted Kremenek93041ba2008-12-09 20:20:09 +00003611 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003612 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003613
3614 // Add the statement to the block. This may create new blocks if S contains
3615 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003616 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003617}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003618
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003619CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
3620 AddStmtChoice asc) {
3621 findConstructionContextsForArguments(ME);
3622
3623 autoCreateBlock();
Artem Dergacheve1f30622018-07-31 19:46:14 +00003624 appendObjCMessage(Block, ME);
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003625
3626 return VisitChildren(ME);
3627}
3628
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003629CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003630 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003631 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003632 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003633
3634 // Create the new block.
3635 Block = createBlock(false);
3636
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003637 if (TryTerminatedBlock)
3638 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003639 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003640 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003641 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003642 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003643
3644 // Add the statement to the block. This may create new blocks if S contains
3645 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003646 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003647}
3648
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003649CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003650 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003651
Peter Szecsi999a25f2017-08-19 11:19:16 +00003652 addLoopExit(D);
3653
Mike Stump8d50b6a2009-07-21 01:27:50 +00003654 // "do...while" is a control-flow statement. Thus we stop processing the
3655 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003656 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003657 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003658 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003659 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003660 } else
3661 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003662
3663 // Because of short-circuit evaluation, the condition of the loop can span
3664 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3665 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003666 CFGBlock *ExitConditionBlock = createBlock(false);
3667 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003668
Ted Kremenek81e14852007-08-27 19:46:09 +00003669 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003670 ExitConditionBlock->setTerminator(D);
3671
3672 // Now add the actual condition to the condition block. Because the condition
3673 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003674 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003675 Block = ExitConditionBlock;
3676 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003677 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003678 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003679 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003680 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003681 }
Mike Stump31feda52009-07-17 01:31:16 +00003682
Ted Kremeneka1523a32008-02-27 07:20:00 +00003683 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003684 Succ = EntryConditionBlock;
3685
Mike Stump773582d2009-07-23 23:25:26 +00003686 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003687 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003688
Ted Kremenek9aae5132007-08-23 21:42:29 +00003689 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003690 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003691 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003692 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003693
Ted Kremenek9aae5132007-08-23 21:42:29 +00003694 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003695 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3696 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3697 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003698
Ted Kremenek9aae5132007-08-23 21:42:29 +00003699 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003700 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003701
Ted Kremenek9aae5132007-08-23 21:42:29 +00003702 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003703 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003704
Ted Kremenek9aae5132007-08-23 21:42:29 +00003705 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003706 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003707
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003708 // If body is not a compound statement create implicit scope
3709 // and add destructors.
3710 if (!isa<CompoundStmt>(D->getBody()))
3711 addLocalScopeAndDtors(D->getBody());
3712
Ted Kremenek9aae5132007-08-23 21:42:29 +00003713 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003714 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003715
Ted Kremeneke9610502007-08-30 18:39:40 +00003716 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003717 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003718 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003719 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003720 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003721 }
Mike Stump31feda52009-07-17 01:31:16 +00003722
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003723 // Add an intermediate block between the BodyBlock and the
3724 // ExitConditionBlock to represent the "loop back" transition. Create an
3725 // empty block to represent the transition block for looping back to the
3726 // head of the loop.
3727 // FIXME: Can we do this more efficiently without adding another block?
3728 Block = nullptr;
3729 Succ = BodyBlock;
3730 CFGBlock *LoopBackBlock = createBlock();
3731 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003732
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003733 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003734 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003735 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003736 else
Craig Topper25542942014-05-20 04:30:07 +00003737 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003738 }
Mike Stump31feda52009-07-17 01:31:16 +00003739
Ted Kremenek30754282009-07-24 04:47:11 +00003740 // Link up the condition block with the code that follows the loop.
3741 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003742 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003743
3744 // There can be no more statements in the body block(s) since we loop back to
3745 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003746 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003747
Ted Kremenek9aae5132007-08-23 21:42:29 +00003748 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003749 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003750 return BodyBlock;
3751}
3752
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003753CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003754 // "continue" is a control-flow statement. Thus we stop processing the
3755 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003756 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003757 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003758
Ted Kremenek9aae5132007-08-23 21:42:29 +00003759 // Now create a new block that ends with the continue statement.
3760 Block = createBlock(false);
3761 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003762
Ted Kremenek9aae5132007-08-23 21:42:29 +00003763 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003764 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003765 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003766 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003767 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003768 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003769 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003770
Ted Kremenek9aae5132007-08-23 21:42:29 +00003771 return Block;
3772}
Mike Stump11289f42009-09-09 15:08:12 +00003773
Peter Collingbournee190dee2011-03-11 19:24:49 +00003774CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3775 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003776 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003777 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003778 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003779 }
Mike Stump11289f42009-09-09 15:08:12 +00003780
Ted Kremenek93668002009-07-17 22:18:43 +00003781 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003782 CFGBlock *lastBlock = Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00003783
Ted Kremenek93668002009-07-17 22:18:43 +00003784 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003785 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003786 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003787 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003788 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003789 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003790}
Mike Stump11289f42009-09-09 15:08:12 +00003791
Ted Kremenek93668002009-07-17 22:18:43 +00003792/// VisitStmtExpr - Utility method to handle (nested) statement
3793/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003794CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003795 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003796 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003797 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003798 }
Ted Kremenek93668002009-07-17 22:18:43 +00003799 return VisitCompoundStmt(SE->getSubStmt());
3800}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003801
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003802CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003803 // "switch" is a control-flow statement. Thus we stop processing the current
3804 // block.
Craig Topper25542942014-05-20 04:30:07 +00003805 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003806
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003807 // Save local scope position because in case of condition variable ScopePos
3808 // won't be restored when traversing AST.
3809 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3810
Richard Smitha547eb22016-07-14 00:11:03 +00003811 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003812 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003813 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003814
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003815 // Create local scope for possible condition variable.
3816 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003817 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003818 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003819
Matthias Gehre351c2182017-07-12 07:04:19 +00003820 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003821
Ted Kremenek9aae5132007-08-23 21:42:29 +00003822 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003823 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003824 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003825 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003826 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003827
3828 // Save the current "switch" context.
3829 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003830 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003831 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003832
Mike Stump31feda52009-07-17 01:31:16 +00003833 // Set the "default" case to be the block after the switch statement. If the
3834 // switch statement contains a "default:", this value will be overwritten with
3835 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003836 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003837
Ted Kremenek9aae5132007-08-23 21:42:29 +00003838 // Create a new block that will contain the switch statement.
3839 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003840
Ted Kremenek9aae5132007-08-23 21:42:29 +00003841 // Now process the switch body. The code after the switch is the implicit
3842 // successor.
3843 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003844 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003845
3846 // When visiting the body, the case statements should automatically get linked
3847 // up to the switch. We also don't keep a pointer to the body, since all
3848 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003849 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003850 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003851
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003852 // For pruning unreachable case statements, save the current state
3853 // for tracking the condition value.
3854 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3855 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003856
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003857 // Determine if the switch condition can be explicitly evaluated.
3858 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003859 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003860 bool b = tryEvaluate(Terminator->getCond(), result);
3861 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003862 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003863
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003864 // If body is not a compound statement create implicit scope
3865 // and add destructors.
3866 if (!isa<CompoundStmt>(Terminator->getBody()))
3867 addLocalScopeAndDtors(Terminator->getBody());
3868
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003869 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003870 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003871 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003872 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003873 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003874
Mike Stump31feda52009-07-17 01:31:16 +00003875 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003876 // following the switch body. Moreover, take into account if all the
3877 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003878 //
3879 // Note: We add a successor to a switch that is considered covered yet has no
3880 // case statements if the enumeration has no enumerators.
3881 bool SwitchAlwaysHasSuccessor = false;
3882 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3883 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3884 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003885 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3886 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003887
Ted Kremenek81e14852007-08-27 19:46:09 +00003888 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003889 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003890 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003891 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003892
Richard Smitha547eb22016-07-14 00:11:03 +00003893 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003894 // SwitchStmt and the condition variable initialization to the CFG.
3895 if (VarDecl *VD = Terminator->getConditionVariable()) {
3896 if (Expr *Init = VD->getInit()) {
3897 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003898 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003899 LastBlock = addStmt(Init);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003900 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003901 }
3902 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003903
Richard Smitha547eb22016-07-14 00:11:03 +00003904 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3905 if (Stmt *Init = Terminator->getInit()) {
3906 autoCreateBlock();
3907 LastBlock = addStmt(Init);
3908 }
3909
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003910 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003911}
Fangrui Song6907ce22018-07-30 19:24:48 +00003912
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003913static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003914 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003915 const CaseStmt *CS,
3916 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003917 if (!switchCond)
3918 return true;
3919
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003920 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003921
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003922 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003923 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003924 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003925 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003926 const llvm::APSInt &condInt = switchCond->Val.getInt();
Fangrui Song6907ce22018-07-30 19:24:48 +00003927
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003928 if (condInt == lhsInt) {
3929 addCase = true;
3930 switchExclusivelyCovered = true;
3931 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003932 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003933 if (const Expr *RHS = CS->getRHS()) {
3934 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003935 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003936 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003937 addCase = true;
3938 switchExclusivelyCovered = true;
3939 }
3940 }
3941 }
3942 }
3943 else
3944 addCase = true;
3945 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003946 return addCase;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003947}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003948
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003949CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003950 // CaseStmts are essentially labels, so they are the first statement in a
3951 // block.
Craig Topper25542942014-05-20 04:30:07 +00003952 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003953
Ted Kremenek60fa6572010-08-04 23:54:30 +00003954 if (Stmt *Sub = CS->getSubStmt()) {
3955 // For deeply nested chains of CaseStmts, instead of doing a recursion
3956 // (which can blow out the stack), manually unroll and create blocks
3957 // along the way.
3958 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003959 CFGBlock *currentBlock = createBlock(false);
3960 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003961
Ted Kremenek60fa6572010-08-04 23:54:30 +00003962 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003963 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003964 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003965 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003966
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003967 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003968 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003969 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003970 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003971
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003972 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003973 CS = cast<CaseStmt>(Sub);
3974 Sub = CS->getSubStmt();
3975 }
3976
3977 addStmt(Sub);
3978 }
Mike Stump11289f42009-09-09 15:08:12 +00003979
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003980 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003981 if (!CaseBlock)
3982 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003983
3984 // Cases statements partition blocks, so this is the top of the basic block we
3985 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003986 CaseBlock->setLabel(CS);
3987
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003988 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003989 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003990
3991 // Add this block to the list of successors for the block with the switch
3992 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003993 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003994 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003995 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003996 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003997
Ted Kremenek9aae5132007-08-23 21:42:29 +00003998 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003999 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004000
Ted Kremenek60fa6572010-08-04 23:54:30 +00004001 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004002 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004003 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004004 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00004005 // This block is now the implicit successor of other blocks.
4006 Succ = CaseBlock;
4007 }
Mike Stump31feda52009-07-17 01:31:16 +00004008
Ted Kremenek60fa6572010-08-04 23:54:30 +00004009 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004010}
Mike Stump31feda52009-07-17 01:31:16 +00004011
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004012CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00004013 if (Terminator->getSubStmt())
4014 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00004015
Ted Kremenek654c78f2008-02-13 22:05:39 +00004016 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00004017
4018 if (!DefaultCaseBlock)
4019 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004020
4021 // Default statements partition blocks, so this is the top of the basic block
4022 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004023 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00004024
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004025 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004026 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00004027
Mike Stump31feda52009-07-17 01:31:16 +00004028 // Unlike case statements, we don't add the default block to the successors
4029 // for the switch statement immediately. This is done when we finish
4030 // processing the switch statement. This allows for the default case
4031 // (including a fall-through to the code after the switch statement) to always
4032 // be the last successor of a switch-terminated block.
4033
Ted Kremenek654c78f2008-02-13 22:05:39 +00004034 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004035 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004036
Ted Kremenek654c78f2008-02-13 22:05:39 +00004037 // This block is now the implicit successor of other blocks.
4038 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00004039
4040 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00004041}
Ted Kremenek9aae5132007-08-23 21:42:29 +00004042
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004043CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4044 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4045 // current block.
Craig Topper25542942014-05-20 04:30:07 +00004046 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004047
4048 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004049 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004050 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004051 TrySuccessor = Block;
4052 } else TrySuccessor = Succ;
4053
Mike Stump0bdba6c2010-01-20 01:15:34 +00004054 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004055
4056 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00004057 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004058 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00004059 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004060
Mike Stump0bdba6c2010-01-20 01:15:34 +00004061 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004062 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
4063 // The code after the try is the implicit successor.
4064 Succ = TrySuccessor;
4065 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00004066 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00004067 HasCatchAll = true;
4068 }
Craig Topper25542942014-05-20 04:30:07 +00004069 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004070 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00004071 if (!CatchBlock)
4072 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004073 // Add this block to the list of successors for the block with the try
4074 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004075 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004076 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00004077 if (!HasCatchAll) {
4078 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004079 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00004080 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004081 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00004082 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004083
4084 // The code after the try is the implicit successor.
4085 Succ = TrySuccessor;
4086
Mike Stump845384a2010-01-20 01:30:58 +00004087 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00004088 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
4089 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00004090
Ted Kremenek1362b8b2010-01-19 20:46:35 +00004091 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00004092 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004093 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004094}
4095
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004096CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004097 // CXXCatchStmt are treated like labels, so they are the first statement in a
4098 // block.
4099
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004100 // Save local scope position because in case of exception variable ScopePos
4101 // won't be restored when traversing AST.
4102 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4103
4104 // Create local scope for possible exception variable.
4105 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004106 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004107 LocalScope::const_iterator BeginScopePos = ScopePos;
4108 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00004109 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004110 }
4111
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004112 if (CS->getHandlerBlock())
4113 addStmt(CS->getHandlerBlock());
4114
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004115 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004116 if (!CatchBlock)
4117 CatchBlock = createBlock();
Fangrui Song6907ce22018-07-30 19:24:48 +00004118
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004119 // CXXCatchStmt is more than just a label. They have semantic meaning
4120 // as well, as they implicitly "initialize" the catch variable. Add
4121 // it to the CFG as a CFGElement so that the control-flow of these
4122 // semantics gets captured.
4123 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004124
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004125 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4126 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004127 CatchBlock->setLabel(CS);
4128
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004129 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004130 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004131 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004132
4133 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004134 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004135
4136 return CatchBlock;
4137}
4138
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004139CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00004140 // C++0x for-range statements are specified as [stmt.ranged]:
4141 //
4142 // {
4143 // auto && __range = range-init;
4144 // for ( auto __begin = begin-expr,
4145 // __end = end-expr;
4146 // __begin != __end;
4147 // ++__begin ) {
4148 // for-range-declaration = *__begin;
4149 // statement
4150 // }
4151 // }
4152
4153 // Save local scope position before the addition of the implicit variables.
4154 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4155
4156 // Create local scopes and destructors for range, begin and end variables.
4157 if (Stmt *Range = S->getRangeStmt())
4158 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00004159 if (Stmt *Begin = S->getBeginStmt())
4160 addLocalScopeForStmt(Begin);
4161 if (Stmt *End = S->getEndStmt())
4162 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00004163 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00004164
4165 LocalScope::const_iterator ContinueScopePos = ScopePos;
4166
4167 // "for" is a control-flow statement. Thus we stop processing the current
4168 // block.
Craig Topper25542942014-05-20 04:30:07 +00004169 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004170 if (Block) {
4171 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004172 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004173 LoopSuccessor = Block;
4174 } else
4175 LoopSuccessor = Succ;
4176
4177 // Save the current value for the break targets.
4178 // All breaks should go to the code following the loop.
4179 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4180 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4181
4182 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004183 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00004184 ConditionBlock->setTerminator(S);
4185
4186 // Now add the actual condition to the condition block.
4187 if (Expr *C = S->getCond()) {
4188 Block = ConditionBlock;
4189 CFGBlock *BeginConditionBlock = addStmt(C);
4190 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004191 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004192 assert(BeginConditionBlock == ConditionBlock &&
4193 "condition block in for-range was unexpectedly complex");
4194 (void)BeginConditionBlock;
4195 }
4196
4197 // The condition block is the implicit successor for the loop body as well as
4198 // any code above the loop.
4199 Succ = ConditionBlock;
4200
4201 // See if this is a known constant.
4202 TryResult KnownVal(true);
4203
4204 if (S->getCond())
4205 KnownVal = tryEvaluateBool(S->getCond());
4206
4207 // Now create the loop body.
4208 {
4209 assert(S->getBody());
4210
4211 // Save the current values for Block, Succ, and continue targets.
4212 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
4213 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
4214
4215 // Generate increment code in its own basic block. This is the target of
4216 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00004217 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004218 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00004219 if (badCFG)
4220 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004221 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4222
4223 // The starting block for the loop increment is the block that should
4224 // represent the 'loop target' for looping back to the start of the loop.
4225 ContinueJumpTarget.block->setLoopTarget(S);
4226
4227 // Finish up the increment block and prepare to start the loop body.
4228 assert(Block);
4229 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004230 return nullptr;
4231 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004232
4233 // Add implicit scope and dtors for loop variable.
4234 addLocalScopeAndDtors(S->getLoopVarStmt());
4235
4236 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004237 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00004238 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004239 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004240 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00004241 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004242 return nullptr;
4243
Richard Smith02e85f32011-04-14 22:09:26 +00004244 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00004245 addSuccessor(ConditionBlock,
4246 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00004247 }
4248
4249 // Link up the condition block with the code that follows the loop (the
4250 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00004251 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00004252
4253 // Add the initialization statements.
4254 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00004255 addStmt(S->getBeginStmt());
4256 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00004257 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00004258}
4259
John McCall5d413782010-12-06 08:20:24 +00004260CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004261 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004262 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004263 // If adding implicit destructors visit the full expression for adding
4264 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004265 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00004266 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004267
4268 // Full expression has to be added as CFGStmt so it will be sequenced
4269 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004270 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004271 }
4272 return Visit(E->getSubExpr(), asc);
4273}
4274
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004275CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4276 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004277 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004278 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004279 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004280
Artem Dergachev783a4572018-02-23 22:20:39 +00004281 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004282 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
Artem Dergachev783a4572018-02-23 22:20:39 +00004283 E->getSubExpr());
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004284
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004285 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004286 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004287 }
4288 return Visit(E->getSubExpr(), asc);
4289}
4290
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004291CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4292 AddStmtChoice asc) {
Artem Dergachevbd880fe2018-07-31 19:39:37 +00004293 // If the constructor takes objects as arguments by value, we need to properly
4294 // construct these objects. Construction contexts we find here aren't for the
4295 // constructor C, they're for its arguments only.
4296 findConstructionContextsForArguments(C);
4297
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004298 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00004299 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004300
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004301 return VisitChildren(C);
4302}
4303
Jordan Rosec9176072014-01-13 17:59:19 +00004304CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4305 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00004306 autoCreateBlock();
4307 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00004308
Artem Dergachev783a4572018-02-23 22:20:39 +00004309 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004310 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
Artem Dergachev783a4572018-02-23 22:20:39 +00004311 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
Artem Dergachev41ffb302018-02-08 22:58:15 +00004312
Jordan Rosec9176072014-01-13 17:59:19 +00004313 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004314 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004315
Jordan Rosec9176072014-01-13 17:59:19 +00004316 if (BuildOpts.AddCXXNewAllocator)
4317 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004318
Jordan Rosec9176072014-01-13 17:59:19 +00004319 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004320 Block = Visit(NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004321
Jordan Rosec9176072014-01-13 17:59:19 +00004322 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4323 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00004324 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004325
Jordan Rosec9176072014-01-13 17:59:19 +00004326 return Block;
4327}
Jordan Rosed2f40792013-09-03 17:00:57 +00004328
4329CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4330 AddStmtChoice asc) {
4331 autoCreateBlock();
4332 appendStmt(Block, DE);
4333 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00004334 if (!DTy.isNull()) {
4335 DTy = DTy.getNonReferenceType();
4336 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4337 if (RD) {
4338 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4339 appendDeleteDtor(Block, RD, DE);
4340 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004341 }
4342
4343 return VisitChildren(DE);
4344}
4345
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004346CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4347 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004348 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004349 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004350 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004351 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004352 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004353 }
4354 return Visit(E->getSubExpr(), asc);
4355}
4356
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004357CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4358 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004359 autoCreateBlock();
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004360 appendConstructor(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004361 return VisitChildren(C);
4362}
4363
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004364CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4365 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004366 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004367 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004368 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004369 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004370 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004371}
4372
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004373CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004374 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004375 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004376
Ted Kremenekeda180e22007-08-28 19:26:49 +00004377 if (!IBlock) {
4378 IBlock = createBlock(false);
4379 cfg->setIndirectGotoBlock(IBlock);
4380 }
Mike Stump31feda52009-07-17 01:31:16 +00004381
Ted Kremenekeda180e22007-08-28 19:26:49 +00004382 // IndirectGoto is a control-flow statement. Thus we stop processing the
4383 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004384 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004385 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004386
Ted Kremenekeda180e22007-08-28 19:26:49 +00004387 Block = createBlock(false);
4388 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004389 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004390 return addStmt(I->getTarget());
4391}
4392
Manuel Klimekb5616c92014-08-07 10:42:17 +00004393CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4394 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004395 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4396
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004397tryAgain:
4398 if (!E) {
4399 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004400 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004401 }
4402 switch (E->getStmtClass()) {
4403 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004404 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004405
4406 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004407 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4408 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004409
4410 case Stmt::CXXBindTemporaryExprClass:
4411 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004412 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004413
John McCallc07a0c72011-02-17 10:25:35 +00004414 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004415 case Stmt::ConditionalOperatorClass:
4416 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004417 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004418
4419 case Stmt::ImplicitCastExprClass:
4420 // For implicit cast we want BindToTemporary to be passed further.
4421 E = cast<CastExpr>(E)->getSubExpr();
4422 goto tryAgain;
4423
Manuel Klimekb0042c42014-07-30 08:34:42 +00004424 case Stmt::CXXFunctionalCastExprClass:
4425 // For functional cast we want BindToTemporary to be passed further.
4426 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4427 goto tryAgain;
4428
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004429 case Stmt::ParenExprClass:
4430 E = cast<ParenExpr>(E)->getSubExpr();
4431 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004432
Manuel Klimekb0042c42014-07-30 08:34:42 +00004433 case Stmt::MaterializeTemporaryExprClass: {
4434 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4435 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4436 SmallVector<const Expr *, 2> CommaLHSs;
4437 SmallVector<SubobjectAdjustment, 2> Adjustments;
4438 // Find the expression whose lifetime needs to be extended.
4439 E = const_cast<Expr *>(
4440 cast<MaterializeTemporaryExpr>(E)
4441 ->GetTemporaryExpr()
4442 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4443 // Visit the skipped comma operator left-hand sides for other temporaries.
4444 for (const Expr *CommaLHS : CommaLHSs) {
4445 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004446 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004447 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004448 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004449 }
Richard Smith4137af22014-07-27 05:12:49 +00004450
4451 case Stmt::BlockExprClass:
4452 // Don't recurse into blocks; their subexpressions don't get evaluated
4453 // here.
4454 return Block;
4455
4456 case Stmt::LambdaExprClass: {
4457 // For lambda expressions, only recurse into the capture initializers,
4458 // and not the body.
4459 auto *LE = cast<LambdaExpr>(E);
4460 CFGBlock *B = Block;
4461 for (Expr *Init : LE->capture_inits()) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00004462 if (Init) {
4463 if (CFGBlock *R = VisitForTemporaryDtors(
4464 Init, /*BindToTemporary=*/false, Context))
4465 B = R;
4466 }
Richard Smith4137af22014-07-27 05:12:49 +00004467 }
4468 return B;
4469 }
4470
4471 case Stmt::CXXDefaultArgExprClass:
4472 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4473 goto tryAgain;
4474
4475 case Stmt::CXXDefaultInitExprClass:
4476 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4477 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004478 }
4479}
4480
Manuel Klimekb5616c92014-08-07 10:42:17 +00004481CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4482 TempDtorContext &Context) {
4483 if (isa<LambdaExpr>(E)) {
4484 // Do not visit the children of lambdas; they have their own CFGs.
4485 return Block;
4486 }
4487
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004488 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004489 // order that they will appear in the CFG. Because the CFG is built
4490 // bottom-up, this means we visit them in their natural order, which
4491 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004492 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004493 for (Stmt *Child : E->children())
4494 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004495 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004496 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004497
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004498 return B;
4499}
4500
Manuel Klimekb5616c92014-08-07 10:42:17 +00004501CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4502 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004503 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004504 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004505 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4506 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4507 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004508
Manuel Klimekedf925b92014-08-07 18:44:19 +00004509 // We do not know at CFG-construction time whether the right-hand-side was
4510 // executed, thus we add a branch node that depends on the temporary
4511 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004512 TempDtorContext RHSContext(
4513 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004514 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004515 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004516
Manuel Klimekb5616c92014-08-07 10:42:17 +00004517 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004518 }
4519
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004520 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004521 // For assignment operator (=) LHS expression is visited
4522 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004523 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4524 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004525 return LHSBlock ? LHSBlock : RHSBlock;
4526 }
4527
4528 // For any other binary operator RHS expression is visited before
4529 // LHS expression (order of children). For destructors visit them in reverse
4530 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004531 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4532 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004533 return RHSBlock ? RHSBlock : LHSBlock;
4534}
4535
4536CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004537 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004538 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004539 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004540 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004541 // If lifetime of temporary is not prolonged (by assigning to constant
4542 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004543
Chandler Carruthad747252011-09-13 06:09:01 +00004544 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004545
Richard Trieu95a192a2015-05-28 00:14:02 +00004546 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004547 // If the destructor is marked as a no-return destructor, we need to
4548 // create a new block for the destructor which does not have as a
4549 // successor anything built thus far. Control won't flow out of this
4550 // block.
4551 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004552 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004553 } else if (Context.needsTempDtorBranch()) {
4554 // If we need to introduce a branch, we add a new block that we will hook
4555 // up to a decision block later.
4556 if (B) Succ = B;
4557 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004558 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004559 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004560 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004561 if (Context.needsTempDtorBranch()) {
4562 Context.setDecisionPoint(Succ, E);
4563 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004564 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004565
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004566 B = Block;
4567 }
4568 return B;
4569}
4570
Manuel Klimekb5616c92014-08-07 10:42:17 +00004571void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4572 CFGBlock *FalseSucc) {
4573 if (!Context.TerminatorExpr) {
4574 // If no temporary was found, we do not need to insert a decision point.
4575 return;
4576 }
4577 assert(Context.TerminatorExpr);
4578 CFGBlock *Decision = createBlock(false);
4579 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004580 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004581 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004582 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004583 Block = Decision;
4584}
4585
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004586CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004587 AbstractConditionalOperator *E, bool BindToTemporary,
4588 TempDtorContext &Context) {
4589 VisitForTemporaryDtors(E->getCond(), false, Context);
4590 CFGBlock *ConditionBlock = Block;
4591 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004592 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004593 TryResult NegatedVal = ConditionVal;
4594 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004595
Manuel Klimekdeb02622014-08-08 07:37:13 +00004596 TempDtorContext TrueContext(
4597 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004598 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004599 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004600
Manuel Klimekb5616c92014-08-07 10:42:17 +00004601 Block = ConditionBlock;
4602 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004603 TempDtorContext FalseContext(
4604 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004605 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004606
Manuel Klimekb5616c92014-08-07 10:42:17 +00004607 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004608 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004609 } else if (TrueContext.TerminatorExpr) {
4610 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004611 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004612 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004613 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004614 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004615 return Block;
4616}
4617
Mike Stump31feda52009-07-17 01:31:16 +00004618/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4619/// no successors or predecessors. If this is the first block created in the
4620/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004621CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004622 bool first_block = begin() == end();
4623
4624 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004625 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004626 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004627 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004628
4629 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004630 if (first_block)
4631 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004632
4633 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004634 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004635}
4636
David Blaikiee90195c2014-08-29 18:53:26 +00004637/// buildCFG - Constructs a CFG from an AST.
4638std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4639 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004640 CFGBuilder Builder(C, BO);
4641 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004642}
4643
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004644const CXXDestructorDecl *
4645CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004646 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004647 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004648 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004649 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004650 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004651 case CFGElement::Statement:
4652 case CFGElement::Constructor:
Artem Dergachev1527dec2018-03-12 23:12:40 +00004653 case CFGElement::CXXRecordTypedCall:
Maxim Ostapenkodebca452018-03-12 12:26:15 +00004654 case CFGElement::ScopeBegin:
4655 case CFGElement::ScopeEnd:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004656 llvm_unreachable("getDestructorDecl should only be used with "
4657 "ImplicitDtors");
4658 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004659 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004660 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004661
4662 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4663 //
4664 // Lifetime-extending constructs are handled here. This works for a single
4665 // temporary in an initializer expression.
4666 if (ty->isReferenceType()) {
4667 if (const Expr *Init = var->getInit()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00004668 ty = getReferenceInitTemporaryType(Init);
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004669 }
4670 }
4671
Ted Kremeneke7d78882012-03-19 23:48:41 +00004672 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004673 ty = arrayType->getElementType();
4674 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004675 const RecordType *recordType = ty->getAs<RecordType>();
4676 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004677 cast<CXXRecordDecl>(recordType->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004678 return classDecl->getDestructor();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004679 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004680 case CFGElement::DeleteDtor: {
4681 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4682 QualType DTy = DE->getDestroyedType();
4683 DTy = DTy.getNonReferenceType();
4684 const CXXRecordDecl *classDecl =
4685 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4686 return classDecl->getDestructor();
4687 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004688 case CFGElement::TemporaryDtor: {
4689 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004690 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004691 const CXXTemporary *temp = bindExpr->getTemporary();
4692 return temp->getDestructor();
4693 }
4694 case CFGElement::BaseDtor:
4695 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004696 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004697 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004698 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004699 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004700}
4701
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004702bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004703 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4704 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004705 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004706}
4707
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004708//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004709// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004710//===----------------------------------------------------------------------===//
4711
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004712CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004713 : ReachableBlock(IsReachable ? B : nullptr),
4714 UnreachableBlock(!IsReachable ? B : nullptr,
4715 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004716
4717CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004718 : ReachableBlock(B),
4719 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4720 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004721
4722void CFGBlock::addSuccessor(AdjacentBlock Succ,
4723 BumpVectorContext &C) {
4724 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004725 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004726
4727 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004728 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004729
4730 Succs.push_back(Succ, C);
4731}
4732
Ted Kremenekb0371852010-09-09 00:06:04 +00004733bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004734 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004735 if (F.IgnoreNullPredecessors && !From)
4736 return true;
4737
4738 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004739 // If the 'To' has no label or is labeled but the label isn't a
4740 // CaseStmt then filter this edge.
4741 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00004742 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004743 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004744 const Stmt *L = To->getLabel();
4745 if (!L || !isa<CaseStmt>(L))
4746 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004747 }
4748 }
4749 }
4750
4751 return false;
4752}
4753
4754//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004755// CFG pretty printing
4756//===----------------------------------------------------------------------===//
4757
Ted Kremenek7e776b12007-08-22 18:22:34 +00004758namespace {
4759
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004760class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004761 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4762 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4763
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004764 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004765 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004766 signed currentBlock = 0;
4767 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004768 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004769
Eugene Zelenko38c70522017-12-07 21:55:09 +00004770public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004771 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004772 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004773 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4774 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004775 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Fangrui Song6907ce22018-07-30 19:24:48 +00004776 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004777 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4778 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004779 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004780 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004781
Ted Kremenek96a7a592011-03-01 03:15:10 +00004782 switch (stmt->getStmtClass()) {
4783 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004784 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4785 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004786 case Stmt::IfStmtClass: {
4787 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4788 if (var)
4789 DeclMap[var] = P;
4790 break;
4791 }
4792 case Stmt::ForStmtClass: {
4793 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4794 if (var)
4795 DeclMap[var] = P;
4796 break;
4797 }
4798 case Stmt::WhileStmtClass: {
4799 const VarDecl *var =
4800 cast<WhileStmt>(stmt)->getConditionVariable();
4801 if (var)
4802 DeclMap[var] = P;
4803 break;
4804 }
4805 case Stmt::SwitchStmtClass: {
4806 const VarDecl *var =
4807 cast<SwitchStmt>(stmt)->getConditionVariable();
4808 if (var)
4809 DeclMap[var] = P;
4810 break;
4811 }
4812 case Stmt::CXXCatchStmtClass: {
4813 const VarDecl *var =
4814 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4815 if (var)
4816 DeclMap[var] = P;
4817 break;
4818 }
4819 default:
4820 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004821 }
4822 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004823 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004824 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004825 }
Mike Stump31feda52009-07-17 01:31:16 +00004826
Eugene Zelenko38c70522017-12-07 21:55:09 +00004827 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004828
Chris Lattnerc61089a2009-06-30 01:26:17 +00004829 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004830 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004831 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004832
Craig Topperb45acb82014-03-14 06:02:07 +00004833 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004834 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004835
4836 if (I == StmtMap.end())
4837 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004838
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004839 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004840 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004841 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004842 }
Mike Stump31feda52009-07-17 01:31:16 +00004843
Ted Kremenek60983dc2010-01-19 20:52:05 +00004844 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004845 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004846 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004847
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004848 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004849 DeclMapTy::iterator I = DeclMap.find(D);
4850
4851 if (I == DeclMap.end())
4852 return false;
4853
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004854 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004855 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004856 return false;
4857 }
4858
4859 OS << "[B" << I->second.first << "." << I->second.second << "]";
4860 return true;
4861 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004862};
4863
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004864class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00004865 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004866 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004867 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004868 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004869
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004870public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004871 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004872 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004873 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004874 this->Policy.IncludeNewlines = false;
4875 }
Mike Stump31feda52009-07-17 01:31:16 +00004876
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004877 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004878 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004879 if (Stmt *C = I->getCond())
4880 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004881 }
Mike Stump31feda52009-07-17 01:31:16 +00004882
Ted Kremenek9aae5132007-08-23 21:42:29 +00004883 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004884 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004885 Terminator->printPretty(OS, Helper, Policy);
4886 }
4887
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004888 void VisitDeclStmt(DeclStmt *DS) {
4889 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4890 OS << "static init " << VD->getName();
4891 }
4892
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004893 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004894 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004895 if (F->getInit())
4896 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004897 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004898 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004899 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004900 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004901 if (F->getInc())
4902 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004903 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004904 }
Mike Stump31feda52009-07-17 01:31:16 +00004905
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004906 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004907 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004908 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004909 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004910 }
Mike Stump31feda52009-07-17 01:31:16 +00004911
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004912 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004913 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004914 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004915 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004916 }
Mike Stump31feda52009-07-17 01:31:16 +00004917
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004918 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004919 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004920 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004921 }
Mike Stump31feda52009-07-17 01:31:16 +00004922
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004923 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004924 OS << "try ...";
4925 }
4926
Nico Weber699670e2017-08-23 15:33:16 +00004927 void VisitSEHTryStmt(SEHTryStmt *CS) {
4928 OS << "__try ...";
4929 }
4930
John McCallc07a0c72011-02-17 10:25:35 +00004931 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004932 if (Stmt *Cond = C->getCond())
4933 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004934 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004935 }
Mike Stump31feda52009-07-17 01:31:16 +00004936
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004937 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004938 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004939 if (Stmt *Cond = C->getCond())
4940 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004941 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004942 }
Mike Stump31feda52009-07-17 01:31:16 +00004943
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004944 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004945 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004946 if (Stmt *T = I->getTarget())
4947 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004948 }
Mike Stump31feda52009-07-17 01:31:16 +00004949
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004950 void VisitBinaryOperator(BinaryOperator* B) {
4951 if (!B->isLogicalOp()) {
4952 VisitExpr(B);
4953 return;
4954 }
Mike Stump31feda52009-07-17 01:31:16 +00004955
Richard Trieuddd01ce2014-06-09 22:53:25 +00004956 if (B->getLHS())
4957 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004958
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004959 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004960 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004961 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004962 return;
John McCalle3027922010-08-25 11:45:40 +00004963 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004964 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004965 return;
4966 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004967 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004968 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004969 }
Mike Stump31feda52009-07-17 01:31:16 +00004970
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004971 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004972 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004973 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004974
4975public:
4976 void print(CFGTerminator T) {
4977 if (T.isTemporaryDtorsBranch())
4978 OS << "(Temp Dtor) ";
4979 Visit(T.getStmt());
4980 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004981};
Eugene Zelenko38c70522017-12-07 21:55:09 +00004982
4983} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00004984
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004985static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
4986 const CXXCtorInitializer *I) {
4987 if (I->isBaseInitializer())
4988 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4989 else if (I->isDelegatingInitializer())
4990 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4991 else
4992 OS << I->getAnyMember()->getName();
4993 OS << "(";
4994 if (Expr *IE = I->getInit())
4995 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4996 OS << ")";
4997
4998 if (I->isBaseInitializer())
4999 OS << " (Base initializer)";
5000 else if (I->isDelegatingInitializer())
5001 OS << " (Delegating initializer)";
5002 else
5003 OS << " (Member initializer)";
5004}
5005
Artem Dergachev1527dec2018-03-12 23:12:40 +00005006static void print_construction_context(raw_ostream &OS,
5007 StmtPrinterHelper &Helper,
5008 const ConstructionContext *CC) {
Artem Dergachevff267df2018-06-28 00:04:54 +00005009 SmallVector<const Stmt *, 3> Stmts;
Artem Dergachev1527dec2018-03-12 23:12:40 +00005010 switch (CC->getKind()) {
Artem Dergachev922455f2018-03-22 22:02:38 +00005011 case ConstructionContext::SimpleConstructorInitializerKind: {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005012 OS << ", ";
Artem Dergachev922455f2018-03-22 22:02:38 +00005013 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5014 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
5015 break;
5016 }
5017 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5018 OS << ", ";
5019 const auto *CICC =
5020 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5021 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
Artem Dergachevff267df2018-06-28 00:04:54 +00005022 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005023 break;
5024 }
5025 case ConstructionContext::SimpleVariableKind: {
Artem Dergachev317291e2018-03-22 21:37:39 +00005026 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005027 Stmts.push_back(SDSCC->getDeclStmt());
Artem Dergachev317291e2018-03-22 21:37:39 +00005028 break;
5029 }
5030 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5031 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005032 Stmts.push_back(CDSCC->getDeclStmt());
5033 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005034 break;
5035 }
5036 case ConstructionContext::NewAllocatedObjectKind: {
5037 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005038 Stmts.push_back(NECC->getCXXNewExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005039 break;
5040 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005041 case ConstructionContext::SimpleReturnedValueKind: {
5042 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005043 Stmts.push_back(RSCC->getReturnStmt());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005044 break;
5045 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005046 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5047 const auto *RSCC =
5048 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005049 Stmts.push_back(RSCC->getReturnStmt());
5050 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
Artem Dergachev317291e2018-03-22 21:37:39 +00005051 break;
5052 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005053 case ConstructionContext::SimpleTemporaryObjectKind: {
5054 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5055 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5056 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5057 break;
5058 }
5059 case ConstructionContext::ElidedTemporaryObjectKind: {
5060 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5061 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5062 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5063 Stmts.push_back(TOCC->getConstructorAfterElision());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005064 break;
5065 }
5066 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005067 for (auto I: Stmts)
5068 if (I) {
5069 OS << ", ";
5070 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5071 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005072}
5073
Aaron Ballmanff924b02013-11-18 20:11:50 +00005074static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00005075 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00005076 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
5077 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00005078 assert(S != nullptr && "Expecting non-null Stmt");
5079
Aaron Ballmanff924b02013-11-18 20:11:50 +00005080 // special printing for statement-expressions.
5081 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5082 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00005083
Benjamin Kramer5733e352015-07-18 17:09:36 +00005084 auto Children = Sub->children();
5085 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005086 OS << "({ ... ; ";
5087 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5088 OS << " })\n";
5089 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005090 }
5091 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00005092 // special printing for comma expressions.
5093 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5094 if (B->getOpcode() == BO_Comma) {
5095 OS << "... , ";
5096 Helper.handledStmt(B->getRHS(),OS);
5097 OS << '\n';
5098 return;
5099 }
5100 }
5101 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00005102
Artem Dergachev1527dec2018-03-12 23:12:40 +00005103 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5104 if (isa<CXXOperatorCallExpr>(S))
5105 OS << " (OperatorCall)";
5106 OS << " (CXXRecordTypedCall";
5107 print_construction_context(OS, Helper, VTC->getConstructionContext());
5108 OS << ")";
5109 } else if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005110 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005111 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005112 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005113 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005114 OS << " (CXXConstructExpr";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005115 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005116 print_construction_context(OS, Helper, CE->getConstructionContext());
Artem Dergachev41ffb302018-02-08 22:58:15 +00005117 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005118 OS << ", " << CCE->getType().getAsString() << ")";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005119 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00005120 OS << " (" << CE->getStmtClassName() << ", "
5121 << CE->getCastKindName()
5122 << ", " << CE->getType().getAsString()
5123 << ")";
5124 }
Mike Stump31feda52009-07-17 01:31:16 +00005125
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005126 // Expressions need a newline.
5127 if (isa<Expr>(S))
5128 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005129 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00005130 print_initializer(OS, Helper, IE->getInitializer());
5131 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005132 } else if (Optional<CFGAutomaticObjDtor> DE =
5133 E.getAs<CFGAutomaticObjDtor>()) {
5134 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00005135 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005136
Artem Dergacheva25809f2018-06-04 18:56:25 +00005137 ASTContext &ACtx = VD->getASTContext();
5138 QualType T = VD->getType();
5139 if (T->isReferenceType())
5140 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5141 if (const ArrayType *AT = ACtx.getAsArrayType(T))
5142 T = ACtx.getBaseElementType(AT);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005143
5144 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
5145 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00005146 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
5147 const VarDecl *VD = DE->getVarDecl();
5148 Helper.handleDecl(VD, OS);
5149
5150 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00005151 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
5152 const Stmt *LoopStmt = LE->getLoopStmt();
5153 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Maxim Ostapenkodebca452018-03-12 12:26:15 +00005154 } else if (Optional<CFGScopeBegin> SB = E.getAs<CFGScopeBegin>()) {
5155 OS << "CFGScopeBegin(";
5156 if (const VarDecl *VD = SB->getVarDecl())
5157 OS << VD->getQualifiedNameAsString();
5158 OS << ")\n";
5159 } else if (Optional<CFGScopeEnd> SE = E.getAs<CFGScopeEnd>()) {
5160 OS << "CFGScopeEnd(";
5161 if (const VarDecl *VD = SE->getVarDecl())
5162 OS << VD->getQualifiedNameAsString();
5163 OS << ")\n";
Jordan Rosec9176072014-01-13 17:59:19 +00005164 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
5165 OS << "CFGNewAllocator(";
5166 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
5167 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5168 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00005169 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
5170 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
5171 if (!RD)
5172 return;
5173 CXXDeleteExpr *DelExpr =
5174 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00005175 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00005176 OS << "->~" << RD->getName().str() << "()";
5177 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005178 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
5179 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005180 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005181 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005182 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
5183 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00005184 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005185 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00005186 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005187 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005188 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
5189 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00005190 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005191 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00005192 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005193 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00005194}
Mike Stump31feda52009-07-17 01:31:16 +00005195
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005196static void print_block(raw_ostream &OS, const CFG* cfg,
5197 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00005198 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005199 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005200 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00005201
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005202 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005203 if (ShowColors)
5204 OS.changeColor(raw_ostream::YELLOW, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005205
Ted Kremenek72be32a2011-12-22 23:33:52 +00005206 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00005207
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005208 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005209 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005210 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005211 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005212 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005213 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00005214 else if (B.hasNoReturnElement())
5215 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005216 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00005217 OS << "]\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005218
Ted Kremenek72be32a2011-12-22 23:33:52 +00005219 if (ShowColors)
5220 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00005221
Ted Kremenek71eca012007-08-29 23:20:49 +00005222 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005223 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005224 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005225 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005226
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005227 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005228 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005229 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005230 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005231 if (C->getLHS())
5232 C->getLHS()->printPretty(OS, &Helper,
5233 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005234 if (C->getRHS()) {
5235 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005236 C->getRHS()->printPretty(OS, &Helper,
5237 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005238 }
Mike Stump92244b02010-01-19 22:00:14 +00005239 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005240 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00005241 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005242 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00005243 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00005244 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00005245 0);
5246 else
5247 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005248 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00005249 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5250 OS << "__except (";
5251 ES->getFilterExpr()->printPretty(OS, &Helper,
5252 PrintingPolicy(Helper.getLangOpts()), 0);
5253 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005254 } else
David Blaikie83d382b2011-09-23 05:06:16 +00005255 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00005256
Ted Kremenek71eca012007-08-29 23:20:49 +00005257 OS << ":\n";
5258 }
Mike Stump31feda52009-07-17 01:31:16 +00005259
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005260 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005261 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00005262
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005263 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5264 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005265 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005266 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005267 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005268
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005269 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00005270
Aaron Ballmanff924b02013-11-18 20:11:50 +00005271 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00005272
Ted Kremenek72be32a2011-12-22 23:33:52 +00005273 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005274 }
Mike Stump31feda52009-07-17 01:31:16 +00005275
Ted Kremenek71eca012007-08-29 23:20:49 +00005276 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005277 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00005278 if (ShowColors)
5279 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00005280
Ted Kremenek72be32a2011-12-22 23:33:52 +00005281 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00005282
Aaron Ballmanff924b02013-11-18 20:11:50 +00005283 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00005284
Aaron Ballmanff924b02013-11-18 20:11:50 +00005285 PrintingPolicy PP(Helper.getLangOpts());
5286 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00005287 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005288 OS << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00005289
Ted Kremenek72be32a2011-12-22 23:33:52 +00005290 if (ShowColors)
5291 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005292 }
Mike Stump31feda52009-07-17 01:31:16 +00005293
Ted Kremenek71eca012007-08-29 23:20:49 +00005294 if (print_edges) {
5295 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005296 if (!B.pred_empty()) {
5297 const raw_ostream::Colors Color = raw_ostream::BLUE;
5298 if (ShowColors)
5299 OS.changeColor(Color);
5300 OS << " Preds " ;
5301 if (ShowColors)
5302 OS.resetColor();
5303 OS << '(' << B.pred_size() << "):";
5304 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00005305
Ted Kremenek72be32a2011-12-22 23:33:52 +00005306 if (ShowColors)
5307 OS.changeColor(Color);
Fangrui Song6907ce22018-07-30 19:24:48 +00005308
Ted Kremenek72be32a2011-12-22 23:33:52 +00005309 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
5310 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005311 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005312 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00005313
Ted Kremenek4b6fee62014-02-27 00:24:00 +00005314 CFGBlock *B = *I;
5315 bool Reachable = true;
5316 if (!B) {
5317 Reachable = false;
5318 B = I->getPossiblyUnreachableBlock();
5319 }
5320
5321 OS << " B" << B->getBlockID();
5322 if (!Reachable)
5323 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00005324 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005325
Ted Kremenek72be32a2011-12-22 23:33:52 +00005326 if (ShowColors)
5327 OS.resetColor();
5328
5329 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00005330 }
Mike Stump31feda52009-07-17 01:31:16 +00005331
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005332 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005333 if (!B.succ_empty()) {
5334 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
5335 if (ShowColors)
5336 OS.changeColor(Color);
5337 OS << " Succs ";
5338 if (ShowColors)
5339 OS.resetColor();
5340 OS << '(' << B.succ_size() << "):";
5341 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005342
Ted Kremenek72be32a2011-12-22 23:33:52 +00005343 if (ShowColors)
5344 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00005345
Ted Kremenek72be32a2011-12-22 23:33:52 +00005346 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
5347 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005348 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005349 OS << "\n ";
5350
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005351 CFGBlock *B = *I;
5352
5353 bool Reachable = true;
5354 if (!B) {
5355 Reachable = false;
5356 B = I->getPossiblyUnreachableBlock();
5357 }
5358
5359 if (B) {
5360 OS << " B" << B->getBlockID();
5361 if (!Reachable)
5362 OS << "(Unreachable)";
5363 }
5364 else {
5365 OS << " NULL";
5366 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00005367 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005368
Ted Kremenek72be32a2011-12-22 23:33:52 +00005369 if (ShowColors)
5370 OS.resetColor();
5371 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005372 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005373 }
Mike Stump31feda52009-07-17 01:31:16 +00005374}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005375
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005376/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005377void CFG::dump(const LangOptions &LO, bool ShowColors) const {
5378 print(llvm::errs(), LO, ShowColors);
5379}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005380
5381/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005382void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005383 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00005384
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005385 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005386 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00005387
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005388 // Iterate through the CFGBlocks and print them one by one.
5389 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5390 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00005391 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005392 continue;
Mike Stump31feda52009-07-17 01:31:16 +00005393
Aaron Ballmanff924b02013-11-18 20:11:50 +00005394 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005395 }
Mike Stump31feda52009-07-17 01:31:16 +00005396
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005397 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005398 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005399 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00005400 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00005401}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005402
5403/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005404void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5405 bool ShowColors) const {
5406 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00005407}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005408
Yaron Kerencdae9412016-01-29 19:38:18 +00005409LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00005410 dump(getParent(), LangOptions(), false);
5411}
5412
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005413/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5414/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005415void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005416 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005417 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005418 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005419 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00005420}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005421
Ted Kremenek15647632008-01-30 23:02:42 +00005422/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005423void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00005424 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00005425 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00005426 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005427}
5428
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005429Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00005430 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005431 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00005432 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005433
Craig Topper25542942014-05-20 04:30:07 +00005434 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005435
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005436 switch (Terminator->getStmtClass()) {
5437 default:
5438 break;
Mike Stump31feda52009-07-17 01:31:16 +00005439
Jordan Rosecf10ea82013-06-06 21:53:45 +00005440 case Stmt::CXXForRangeStmtClass:
5441 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5442 break;
5443
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005444 case Stmt::ForStmtClass:
5445 E = cast<ForStmt>(Terminator)->getCond();
5446 break;
Mike Stump31feda52009-07-17 01:31:16 +00005447
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005448 case Stmt::WhileStmtClass:
5449 E = cast<WhileStmt>(Terminator)->getCond();
5450 break;
Mike Stump31feda52009-07-17 01:31:16 +00005451
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005452 case Stmt::DoStmtClass:
5453 E = cast<DoStmt>(Terminator)->getCond();
5454 break;
Mike Stump31feda52009-07-17 01:31:16 +00005455
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005456 case Stmt::IfStmtClass:
5457 E = cast<IfStmt>(Terminator)->getCond();
5458 break;
Mike Stump31feda52009-07-17 01:31:16 +00005459
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005460 case Stmt::ChooseExprClass:
5461 E = cast<ChooseExpr>(Terminator)->getCond();
5462 break;
Mike Stump31feda52009-07-17 01:31:16 +00005463
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005464 case Stmt::IndirectGotoStmtClass:
5465 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5466 break;
Mike Stump31feda52009-07-17 01:31:16 +00005467
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005468 case Stmt::SwitchStmtClass:
5469 E = cast<SwitchStmt>(Terminator)->getCond();
5470 break;
Mike Stump31feda52009-07-17 01:31:16 +00005471
John McCallc07a0c72011-02-17 10:25:35 +00005472 case Stmt::BinaryConditionalOperatorClass:
5473 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5474 break;
5475
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005476 case Stmt::ConditionalOperatorClass:
5477 E = cast<ConditionalOperator>(Terminator)->getCond();
5478 break;
Mike Stump31feda52009-07-17 01:31:16 +00005479
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005480 case Stmt::BinaryOperatorClass: // '&&' and '||'
5481 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005482 break;
Mike Stump31feda52009-07-17 01:31:16 +00005483
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005484 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00005485 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005486 }
Mike Stump31feda52009-07-17 01:31:16 +00005487
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005488 if (!StripParens)
5489 return E;
5490
Craig Topper25542942014-05-20 04:30:07 +00005491 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005492}
5493
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005494//===----------------------------------------------------------------------===//
5495// CFG Graphviz Visualization
5496//===----------------------------------------------------------------------===//
5497
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005498#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005499static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005500#endif
5501
Chris Lattnerc61089a2009-06-30 01:26:17 +00005502void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005503#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005504 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005505 GraphHelper = &H;
5506 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005507 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005508#endif
5509}
5510
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005511namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005512
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005513template<>
5514struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005515 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005516
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005517 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005518#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005519 std::string OutSStr;
5520 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005521 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005522 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005523
5524 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5525
5526 // Process string output to make it nicer...
5527 for (unsigned i = 0; i != OutStr.length(); ++i)
5528 if (OutStr[i] == '\n') { // Left justify
5529 OutStr[i] = '\\';
5530 OutStr.insert(OutStr.begin()+i+1, 'l');
5531 }
Mike Stump31feda52009-07-17 01:31:16 +00005532
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005533 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005534#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005535 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005536#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005537 }
5538};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005539
5540} // namespace llvm