blob: b050347826e524c162344996ed25a6637c9e142f [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the CFG and CFGBuilder classes for representing and
10// building Control-Flow Graphs (CFGs) from ASTs.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek6796fbd2009-07-16 18:13:04 +000014#include "clang/Analysis/CFG.h"
Benjamin Kramer1ea8e092012-07-04 17:04:04 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/Attr.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclCXX.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000020#include "clang/AST/DeclGroup.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/OperationKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/PrettyPrinter.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "clang/AST/StmtVisitor.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000029#include "clang/AST/Type.h"
Artem Dergachev40684812018-02-27 20:03:35 +000030#include "clang/Analysis/ConstructionContext.h"
Csaba Dabisdea605e2019-05-29 18:29:31 +000031#include "clang/Analysis/Support/BumpVector.h"
Jordan Rose5374c072013-08-19 16:27:28 +000032#include "clang/Basic/Builtins.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000033#include "clang/Basic/ExceptionSpecificationType.h"
Csaba Dabisdea605e2019-05-29 18:29:31 +000034#include "clang/Basic/JsonSupport.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000035#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);
Jennifer Yub8fee672019-06-03 15:57:25 +0000552 CFGBlock *VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000553 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000554 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Bill Wendling8003edc2018-11-09 00:41:36 +0000555 CFGBlock *VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000556 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
557 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000558 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000559 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000560 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000561 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
562 Stmt *Term,
563 CFGBlock *TrueBlock,
564 CFGBlock *FalseBlock);
Artem Dergachevf43ac4c2018-02-24 02:00:30 +0000565 CFGBlock *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
566 AddStmtChoice asc);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000567 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000568 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
569 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
570 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
571 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000572 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000573 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000574 CFGBlock *VisitObjCMessageExpr(ObjCMessageExpr *E, AddStmtChoice asc);
John McCallfe96e0b2011-11-06 09:01:30 +0000575 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Brian Gesiaka87ecf62018-11-03 22:35:17 +0000576 CFGBlock *VisitReturnStmt(Stmt *S);
Nico Weber699670e2017-08-23 15:33:16 +0000577 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
578 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
579 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
580 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000581 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000582 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000583 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
584 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000585 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000586 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000587
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000588 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
589 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000590 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000591 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Alexey Bataevc2c21ef2019-07-11 14:54:17 +0000592 CFGBlock *VisitOMPExecutableDirective(OMPExecutableDirective *D,
593 AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000594
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000595 void maybeAddScopeBeginForVarDecl(CFGBlock *B, const VarDecl *VD,
596 const Stmt *S) {
597 if (ScopePos && (VD == ScopePos.getFirstVarInScope()))
598 appendScopeBegin(B, VD, S);
599 }
600
Manuel Klimekb5616c92014-08-07 10:42:17 +0000601 /// When creating the CFG for temporary destructors, we want to mirror the
602 /// branch structure of the corresponding constructor calls.
603 /// Thus, while visiting a statement for temporary destructors, we keep a
604 /// context to keep track of the following information:
605 /// - whether a subexpression is executed unconditionally
606 /// - if a subexpression is executed conditionally, the first
607 /// CXXBindTemporaryExpr we encounter in that subexpression (which
608 /// corresponds to the last temporary destructor we have to call for this
609 /// subexpression) and the CFG block at that point (which will become the
610 /// successor block when inserting the decision point).
611 ///
612 /// That way, we can build the branch structure for temporary destructors as
613 /// follows:
614 /// 1. If a subexpression is executed unconditionally, we add the temporary
615 /// destructor calls to the current block.
616 /// 2. If a subexpression is executed conditionally, when we encounter a
617 /// CXXBindTemporaryExpr:
618 /// a) If it is the first temporary destructor call in the subexpression,
619 /// we remember the CXXBindTemporaryExpr and the current block in the
620 /// TempDtorContext; we start a new block, and insert the temporary
621 /// destructor call.
622 /// b) Otherwise, add the temporary destructor call to the current block.
623 /// 3. When we finished visiting a conditionally executed subexpression,
624 /// and we found at least one temporary constructor during the visitation
625 /// (2.a has executed), we insert a decision block that uses the
626 /// CXXBindTemporaryExpr as terminator, and branches to the current block
627 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
628 /// branches to the stored successor.
629 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000630 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000631 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000632 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000633
634 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000635 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000636 /// conditionally executed, and it is the first one we encounter while
637 /// visiting a subexpression - other temporary destructors at the same level
638 /// will be added to the same block and are executed under the same
639 /// condition.
640 bool needsTempDtorBranch() const {
641 return IsConditional && !TerminatorExpr;
642 }
643
644 /// Remember the successor S of a temporary destructor decision branch for
645 /// the corresponding CXXBindTemporaryExpr E.
646 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
647 Succ = S;
648 TerminatorExpr = E;
649 }
650
Eugene Zelenko38c70522017-12-07 21:55:09 +0000651 const bool IsConditional = false;
652 const TryResult KnownExecuted = true;
653 CFGBlock *Succ = nullptr;
654 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000655 };
656
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000657 // Visitors to walk an AST and generate destructors of temporaries in
658 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000659 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
660 TempDtorContext &Context);
661 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
662 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
663 TempDtorContext &Context);
664 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
665 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
666 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
667 AbstractConditionalOperator *E, bool BindToTemporary,
668 TempDtorContext &Context);
669 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
670 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000671
Ted Kremenek6065ef62008-04-28 18:00:46 +0000672 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000673 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000674 badCFG = true;
675 return Block;
676 }
Mike Stump31feda52009-07-17 01:31:16 +0000677
Artem Dergachev40684812018-02-27 20:03:35 +0000678 // Remember to apply the construction context based on the current \p Layer
679 // when constructing the CFG element for \p CE.
680 void consumeConstructionContext(const ConstructionContextLayer *Layer,
Artem Dergachev1527dec2018-03-12 23:12:40 +0000681 Expr *E);
Artem Dergachevc1b07bd2018-02-23 23:38:41 +0000682
Artem Dergachev40684812018-02-27 20:03:35 +0000683 // Scan \p Child statement to find constructors in it, while keeping in mind
684 // that its parent statement is providing a partial construction context
685 // described by \p Layer. If a constructor is found, it would be assigned
686 // the context based on the layer. If an additional construction context layer
687 // is found, the function recurses into that.
688 void findConstructionContexts(const ConstructionContextLayer *Layer,
Artem Dergachev783a4572018-02-23 22:20:39 +0000689 Stmt *Child);
Artem Dergachev40684812018-02-27 20:03:35 +0000690
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000691 // Scan all arguments of a call expression for a construction context.
692 // These sorts of call expressions don't have a common superclass,
693 // hence strict duck-typing.
694 template <typename CallLikeExpr,
695 typename = typename std::enable_if<
696 std::is_same<CallLikeExpr, CallExpr>::value ||
697 std::is_same<CallLikeExpr, CXXConstructExpr>::value ||
698 std::is_same<CallLikeExpr, ObjCMessageExpr>::value>>
699 void findConstructionContextsForArguments(CallLikeExpr *E) {
Artem Dergacheva657a322018-07-31 20:45:53 +0000700 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
701 Expr *Arg = E->getArg(i);
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000702 if (Arg->getType()->getAsCXXRecordDecl() && !Arg->isGLValue())
703 findConstructionContexts(
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +0000704 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
705 ConstructionContextItem(E, i)),
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000706 Arg);
Artem Dergacheva657a322018-07-31 20:45:53 +0000707 }
Artem Dergachevbd880fe2018-07-31 19:39:37 +0000708 }
709
Artem Dergachev41ffb302018-02-08 22:58:15 +0000710 // Unset the construction context after consuming it. This is done immediately
Artem Dergachev1527dec2018-03-12 23:12:40 +0000711 // after adding the CFGConstructor or CFGCXXRecordTypedCall element, so
712 // there's no need to do this manually in every Visit... function.
713 void cleanupConstructionContext(Expr *E);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000714
Ted Kremenek93668002009-07-17 22:18:43 +0000715 void autoCreateBlock() { if (!Block) Block = createBlock(); }
716 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000717 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000718
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000719 CFGBlock *addStmt(Stmt *S) {
720 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000721 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000722
Alexis Hunt1d792652011-01-08 20:30:50 +0000723 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000724 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000725 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000726 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000727 void addLifetimeEnds(LocalScope::const_iterator B,
728 LocalScope::const_iterator E, Stmt *S);
729 void addAutomaticObjHandling(LocalScope::const_iterator B,
730 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000731 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000732 void addScopesEnd(LocalScope::const_iterator B, LocalScope::const_iterator E,
733 Stmt *S);
734
735 void getDeclsWithEndedScope(LocalScope::const_iterator B,
736 LocalScope::const_iterator E, Stmt *S);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000737
Marcin Swiderski5e415732010-09-30 23:05:00 +0000738 // Local scopes creation.
739 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
740
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000741 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000742 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
743 LocalScope* Scope = nullptr);
744 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000745
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000746 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000747
Artem Dergacheve1f30622018-07-31 19:46:14 +0000748 const ConstructionContext *retrieveAndCleanupConstructionContext(Expr *E) {
749 if (!BuildOpts.AddRichCXXConstructors)
750 return nullptr;
751
752 const ConstructionContextLayer *Layer = ConstructionContextMap.lookup(E);
753 if (!Layer)
754 return nullptr;
755
756 cleanupConstructionContext(E);
757 return ConstructionContext::createFromLayers(cfg->getBumpVectorContext(),
758 Layer);
759 }
760
Marcin Swiderski5e415732010-09-30 23:05:00 +0000761 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000762
Ted Kremenek37881932011-04-04 23:29:12 +0000763 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000764 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000765 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000766
Jordy Rose17347372011-06-10 08:49:37 +0000767 // All block-level expressions should have already been IgnoreParens()ed.
768 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000769 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000770 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000771
Artem Dergachev41ffb302018-02-08 22:58:15 +0000772 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
Artem Dergacheve1f30622018-07-31 19:46:14 +0000773 if (const ConstructionContext *CC =
774 retrieveAndCleanupConstructionContext(CE)) {
775 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
776 return;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000777 }
778
779 // No valid construction context found. Fall back to statement.
780 B->appendStmt(CE, cfg->getBumpVectorContext());
781 }
782
Artem Dergachev1527dec2018-03-12 23:12:40 +0000783 void appendCall(CFGBlock *B, CallExpr *CE) {
Richard Trieuf4a0e9a2018-03-15 00:09:26 +0000784 if (alwaysAdd(CE) && cachedEntry)
785 cachedEntry->second = B;
786
Artem Dergacheve1f30622018-07-31 19:46:14 +0000787 if (const ConstructionContext *CC =
788 retrieveAndCleanupConstructionContext(CE)) {
789 B->appendCXXRecordTypedCall(CE, CC, cfg->getBumpVectorContext());
790 return;
Artem Dergachev1527dec2018-03-12 23:12:40 +0000791 }
792
793 // No valid construction context found. Fall back to statement.
794 B->appendStmt(CE, cfg->getBumpVectorContext());
795 }
796
Alexis Hunt1d792652011-01-08 20:30:50 +0000797 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000798 B->appendInitializer(I, cfg->getBumpVectorContext());
799 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000800
Jordan Rosec9176072014-01-13 17:59:19 +0000801 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
802 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
803 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000804
Marcin Swiderski20b88732010-10-05 05:37:00 +0000805 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
806 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
807 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000808
Marcin Swiderski20b88732010-10-05 05:37:00 +0000809 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
810 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
811 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000812
Artem Dergacheve1f30622018-07-31 19:46:14 +0000813 void appendObjCMessage(CFGBlock *B, ObjCMessageExpr *ME) {
814 if (alwaysAdd(ME) && cachedEntry)
815 cachedEntry->second = B;
816
817 if (const ConstructionContext *CC =
818 retrieveAndCleanupConstructionContext(ME)) {
819 B->appendCXXRecordTypedCall(ME, CC, cfg->getBumpVectorContext());
820 return;
821 }
822
823 B->appendStmt(const_cast<ObjCMessageExpr *>(ME),
824 cfg->getBumpVectorContext());
825 }
826
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000827 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
828 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
829 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000830
Chandler Carruthad747252011-09-13 06:09:01 +0000831 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
832 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
833 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000834
Matthias Gehre351c2182017-07-12 07:04:19 +0000835 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
836 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
837 }
838
Peter Szecsi999a25f2017-08-19 11:19:16 +0000839 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
840 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
841 }
842
Jordan Rosed2f40792013-09-03 17:00:57 +0000843 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
844 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
845 }
846
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000847 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000848 LocalScope::const_iterator B, LocalScope::const_iterator E);
849
Matthias Gehre351c2182017-07-12 07:04:19 +0000850 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
851 LocalScope::const_iterator B,
852 LocalScope::const_iterator E);
853
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000854 const VarDecl *
855 prependAutomaticObjScopeEndWithTerminator(CFGBlock *Blk,
856 LocalScope::const_iterator B,
857 LocalScope::const_iterator E);
858
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000859 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
860 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
861 cfg->getBumpVectorContext());
862 }
863
864 /// Add a reachable successor to a block, with the alternate variant that is
865 /// unreachable.
866 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
867 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
868 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000869 }
Mike Stump11289f42009-09-09 15:08:12 +0000870
Maxim Ostapenkodebca452018-03-12 12:26:15 +0000871 void appendScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
872 if (BuildOpts.AddScopes)
873 B->appendScopeBegin(VD, S, cfg->getBumpVectorContext());
874 }
875
876 void prependScopeBegin(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
877 if (BuildOpts.AddScopes)
878 B->prependScopeBegin(VD, S, cfg->getBumpVectorContext());
879 }
880
881 void appendScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
882 if (BuildOpts.AddScopes)
883 B->appendScopeEnd(VD, S, cfg->getBumpVectorContext());
884 }
885
886 void prependScopeEnd(CFGBlock *B, const VarDecl *VD, const Stmt *S) {
887 if (BuildOpts.AddScopes)
888 B->prependScopeEnd(VD, S, cfg->getBumpVectorContext());
889 }
890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000891 /// Find a relational comparison with an expression evaluating to a
Richard Trieuf935b562014-04-05 05:17:01 +0000892 /// boolean and a constant other than 0 and 1.
893 /// e.g. if ((x < y) == 10)
894 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
895 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
896 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
897
898 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
899 const Expr *BoolExpr = RHSExpr;
900 bool IntFirst = true;
901 if (!IntLiteral) {
902 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
903 BoolExpr = LHSExpr;
904 IntFirst = false;
905 }
906
907 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
908 return TryResult();
909
910 llvm::APInt IntValue = IntLiteral->getValue();
911 if ((IntValue == 1) || (IntValue == 0))
912 return TryResult();
913
914 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
915 !IntValue.isNegative();
916
917 BinaryOperatorKind Bok = B->getOpcode();
918 if (Bok == BO_GT || Bok == BO_GE) {
919 // Always true for 10 > bool and bool > -1
920 // Always false for -1 > bool and bool > 10
921 return TryResult(IntFirst == IntLarger);
922 } else {
923 // Always true for -1 < bool and bool < 10
924 // Always false for 10 < bool and bool < -1
925 return TryResult(IntFirst != IntLarger);
926 }
927 }
928
Jordan Rose7afd71e2014-05-20 17:31:11 +0000929 /// Find an incorrect equality comparison. Either with an expression
930 /// evaluating to a boolean and a constant other than 0 and 1.
931 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
932 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000933 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
934 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
935 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
936
937 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
938 const Expr *BoolExpr = RHSExpr;
939
940 if (!IntLiteral) {
941 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
942 BoolExpr = LHSExpr;
943 }
944
Jordan Rose7afd71e2014-05-20 17:31:11 +0000945 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000946 return TryResult();
947
Jordan Rose7afd71e2014-05-20 17:31:11 +0000948 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
949 if (BitOp && (BitOp->getOpcode() == BO_And ||
950 BitOp->getOpcode() == BO_Or)) {
951 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
952 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
953
954 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
955
956 if (!IntLiteral2)
957 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
958
959 if (!IntLiteral2)
960 return TryResult();
961
962 llvm::APInt L1 = IntLiteral->getValue();
963 llvm::APInt L2 = IntLiteral2->getValue();
964 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
965 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
966 if (BuildOpts.Observer)
967 BuildOpts.Observer->compareBitwiseEquality(B,
968 B->getOpcode() != BO_EQ);
969 TryResult(B->getOpcode() != BO_EQ);
970 }
971 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
972 llvm::APInt IntValue = IntLiteral->getValue();
973 if ((IntValue == 1) || (IntValue == 0)) {
974 return TryResult();
975 }
976 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000977 }
978
Jordan Rose7afd71e2014-05-20 17:31:11 +0000979 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000980 }
981
982 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
983 const llvm::APSInt &Value1,
984 const llvm::APSInt &Value2) {
985 assert(Value1.isSigned() == Value2.isSigned());
986 switch (Relation) {
987 default:
988 return TryResult();
989 case BO_EQ:
990 return TryResult(Value1 == Value2);
991 case BO_NE:
992 return TryResult(Value1 != Value2);
993 case BO_LT:
994 return TryResult(Value1 < Value2);
995 case BO_LE:
996 return TryResult(Value1 <= Value2);
997 case BO_GT:
998 return TryResult(Value1 > Value2);
999 case BO_GE:
1000 return TryResult(Value1 >= Value2);
1001 }
1002 }
1003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001004 /// Find a pair of comparison expressions with or without parentheses
Richard Trieuf935b562014-04-05 05:17:01 +00001005 /// with a shared variable and constants and a logical operator between them
1006 /// that always evaluates to either true or false.
1007 /// e.g. if (x != 3 || x != 4)
1008 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
1009 assert(B->isLogicalOp());
1010 const BinaryOperator *LHS =
1011 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
1012 const BinaryOperator *RHS =
1013 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
1014 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001015 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001016
1017 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001018 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001019
George Burgess IVced56e62015-10-01 18:47:52 +00001020 const DeclRefExpr *Decl1;
1021 const Expr *Expr1;
1022 BinaryOperatorKind BO1;
1023 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001024
George Burgess IVced56e62015-10-01 18:47:52 +00001025 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001026 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001027
George Burgess IVced56e62015-10-01 18:47:52 +00001028 const DeclRefExpr *Decl2;
1029 const Expr *Expr2;
1030 BinaryOperatorKind BO2;
1031 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001032
George Burgess IVced56e62015-10-01 18:47:52 +00001033 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +00001034 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001035
1036 // Check that it is the same variable on both sides.
1037 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001038 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001039
George Burgess IVced56e62015-10-01 18:47:52 +00001040 // Make sure the user's intent is clear (e.g. they're comparing against two
1041 // int literals, or two things from the same enum)
1042 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +00001043 return {};
George Burgess IVced56e62015-10-01 18:47:52 +00001044
Fangrui Song407659a2018-11-30 23:41:18 +00001045 Expr::EvalResult L1Result, L2Result;
1046 if (!Expr1->EvaluateAsInt(L1Result, *Context) ||
1047 !Expr2->EvaluateAsInt(L2Result, *Context))
Fangrui Songf5d33352018-11-30 21:26:09 +00001048 return {};
Hans Wennborg48ee4ad2018-11-28 14:04:12 +00001049
Fangrui Song407659a2018-11-30 23:41:18 +00001050 llvm::APSInt L1 = L1Result.Val.getInt();
1051 llvm::APSInt L2 = L2Result.Val.getInt();
1052
Richard Trieuf935b562014-04-05 05:17:01 +00001053 // Can't compare signed with unsigned or with different bit width.
1054 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001055 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001056
1057 // Values that will be used to determine if result of logical
1058 // operator is always true/false
1059 const llvm::APSInt Values[] = {
1060 // Value less than both Value1 and Value2
1061 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
1062 // L1
1063 L1,
1064 // Value between Value1 and Value2
1065 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
1066 L1.isUnsigned()),
1067 // L2
1068 L2,
1069 // Value greater than both Value1 and Value2
1070 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
1071 };
1072
1073 // Check whether expression is always true/false by evaluating the following
1074 // * variable x is less than the smallest literal.
1075 // * variable x is equal to the smallest literal.
1076 // * Variable x is between smallest and largest literal.
1077 // * Variable x is equal to the largest literal.
1078 // * Variable x is greater than largest literal.
1079 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +00001080 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +00001081 TryResult Res1, Res2;
1082 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
1083 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
1084
1085 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001086 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001087
1088 if (B->getOpcode() == BO_LAnd) {
1089 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
1090 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
1091 } else {
1092 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
1093 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
1094 }
1095 }
1096
1097 if (AlwaysTrue || AlwaysFalse) {
1098 if (BuildOpts.Observer)
1099 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
1100 return TryResult(AlwaysTrue);
1101 }
Eugene Zelenko38c70522017-12-07 21:55:09 +00001102 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001103 }
1104
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001105 /// Try and evaluate an expression to an integer constant.
1106 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
1107 if (!BuildOpts.PruneTriviallyFalseEdges)
1108 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001109 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +00001110 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +00001111 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00001112 }
Mike Stump11289f42009-09-09 15:08:12 +00001113
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001114 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +00001115 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001116 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +00001117 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001118 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +00001119 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001120
1121 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1122 if (Bop->isLogicalOp()) {
1123 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001124 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1125 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001126 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001127
1128 // Retrieve result at first, or the map might be updated.
1129 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1130 CachedBoolEvals[S] = Result; // update or insert
1131 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001132 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001133 else {
1134 switch (Bop->getOpcode()) {
1135 default: break;
1136 // For 'x & 0' and 'x * 0', we can determine that
1137 // the value is always false.
1138 case BO_Mul:
1139 case BO_And: {
1140 // If either operand is zero, we know the value
1141 // must be false.
Fangrui Song407659a2018-11-30 23:41:18 +00001142 Expr::EvalResult LHSResult;
1143 if (Bop->getLHS()->EvaluateAsInt(LHSResult, *Context)) {
1144 llvm::APSInt IntVal = LHSResult.Val.getInt();
David Blaikie7a3cbb22015-03-09 02:02:07 +00001145 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001146 return TryResult(false);
1147 }
1148 }
Fangrui Song407659a2018-11-30 23:41:18 +00001149 Expr::EvalResult RHSResult;
1150 if (Bop->getRHS()->EvaluateAsInt(RHSResult, *Context)) {
1151 llvm::APSInt IntVal = RHSResult.Val.getInt();
David Blaikie7a3cbb22015-03-09 02:02:07 +00001152 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001153 return TryResult(false);
1154 }
1155 }
1156 }
1157 break;
1158 }
1159 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001160 }
1161
1162 return evaluateAsBooleanConditionNoCache(S);
1163 }
1164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001165 /// Evaluate as boolean \param E without using the cache.
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001166 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1167 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1168 if (Bop->isLogicalOp()) {
1169 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1170 if (LHS.isKnown()) {
1171 // We were able to evaluate the LHS, see if we can get away with not
1172 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1173 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1174 return LHS.isTrue();
1175
1176 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1177 if (RHS.isKnown()) {
1178 if (Bop->getOpcode() == BO_LOr)
1179 return LHS.isTrue() || RHS.isTrue();
1180 else
1181 return LHS.isTrue() && RHS.isTrue();
1182 }
1183 } else {
1184 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1185 if (RHS.isKnown()) {
1186 // We can't evaluate the LHS; however, sometimes the result
1187 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1188 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1189 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001190 } else {
1191 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1192 if (BopRes.isKnown())
1193 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001194 }
1195 }
1196
Eugene Zelenko38c70522017-12-07 21:55:09 +00001197 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001198 } else if (Bop->isEqualityOp()) {
1199 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1200 if (BopRes.isKnown())
1201 return BopRes.isTrue();
1202 } else if (Bop->isRelationalOp()) {
1203 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1204 if (BopRes.isKnown())
1205 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001206 }
1207 }
1208
1209 bool Result;
1210 if (E->EvaluateAsBooleanCondition(Result, *Context))
1211 return Result;
1212
Eugene Zelenko38c70522017-12-07 21:55:09 +00001213 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001214 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001215
1216 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001217};
Mike Stump31feda52009-07-17 01:31:16 +00001218
Eugene Zelenko38c70522017-12-07 21:55:09 +00001219} // namespace
1220
Ted Kremeneka099c592011-03-10 03:50:34 +00001221inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1222 const Stmt *stmt) const {
1223 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1224}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001225
Ted Kremeneka099c592011-03-10 03:50:34 +00001226bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001227 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
Fangrui Song6907ce22018-07-30 19:24:48 +00001228
Ted Kremeneka099c592011-03-10 03:50:34 +00001229 if (!BuildOpts.forcedBlkExprs)
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 if (lastLookup == stmt) {
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001233 if (cachedEntry) {
1234 assert(cachedEntry->first == stmt);
1235 return true;
1236 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001237 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001238 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001239
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001240 lastLookup = stmt;
1241
1242 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001243 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1244
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001245 if (!fb) {
1246 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001247 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001248 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001249 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001250
1251 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001252 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001253 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001254 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001255 }
1256
Ted Kremeneka099c592011-03-10 03:50:34 +00001257 cachedEntry = &*itr;
1258 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001259}
Fangrui Song6907ce22018-07-30 19:24:48 +00001260
Douglas Gregor4619e432008-12-05 23:32:09 +00001261// FIXME: Add support for dependent-sized array types in C++?
1262// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001263static const VariableArrayType *FindVA(const Type *t) {
1264 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1265 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001266 if (vat->getSizeExpr())
1267 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001268
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001269 t = vt->getElementType().getTypePtr();
1270 }
Mike Stump31feda52009-07-17 01:31:16 +00001271
Craig Topper25542942014-05-20 04:30:07 +00001272 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001273}
Mike Stump31feda52009-07-17 01:31:16 +00001274
Artem Dergachev40684812018-02-27 20:03:35 +00001275void CFGBuilder::consumeConstructionContext(
Artem Dergachev1527dec2018-03-12 23:12:40 +00001276 const ConstructionContextLayer *Layer, Expr *E) {
Artem Dergacheve1f30622018-07-31 19:46:14 +00001277 assert((isa<CXXConstructExpr>(E) || isa<CallExpr>(E) ||
1278 isa<ObjCMessageExpr>(E)) && "Expression cannot construct an object!");
Artem Dergachev40684812018-02-27 20:03:35 +00001279 if (const ConstructionContextLayer *PreviouslyStoredLayer =
Artem Dergachev1527dec2018-03-12 23:12:40 +00001280 ConstructionContextMap.lookup(E)) {
George Burgess IVa47e1b72018-03-06 07:45:11 +00001281 (void)PreviouslyStoredLayer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001282 // We might have visited this child when we were finding construction
1283 // contexts within its parents.
Artem Dergachev40684812018-02-27 20:03:35 +00001284 assert(PreviouslyStoredLayer->isStrictlyMoreSpecificThan(Layer) &&
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001285 "Already within a different construction context!");
1286 } else {
Artem Dergachev1527dec2018-03-12 23:12:40 +00001287 ConstructionContextMap[E] = Layer;
Artem Dergachevc1b07bd2018-02-23 23:38:41 +00001288 }
1289}
1290
Artem Dergachev783a4572018-02-23 22:20:39 +00001291void CFGBuilder::findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001292 const ConstructionContextLayer *Layer, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001293 if (!BuildOpts.AddRichCXXConstructors)
1294 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001295
Artem Dergachev41ffb302018-02-08 22:58:15 +00001296 if (!Child)
1297 return;
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001298
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001299 auto withExtraLayer = [this, Layer](const ConstructionContextItem &Item) {
1300 return ConstructionContextLayer::create(cfg->getBumpVectorContext(), Item,
1301 Layer);
Artem Dergachevff267df2018-06-28 00:04:54 +00001302 };
1303
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001304 switch(Child->getStmtClass()) {
1305 case Stmt::CXXConstructExprClass:
1306 case Stmt::CXXTemporaryObjectExprClass: {
Artem Dergachevff267df2018-06-28 00:04:54 +00001307 // Support pre-C++17 copy elision AST.
1308 auto *CE = cast<CXXConstructExpr>(Child);
1309 if (BuildOpts.MarkElidedCXXConstructors && CE->isElidable()) {
Artem Dergachevff267df2018-06-28 00:04:54 +00001310 findConstructionContexts(withExtraLayer(CE), CE->getArg(0));
1311 }
1312
1313 consumeConstructionContext(Layer, CE);
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001314 break;
1315 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00001316 // FIXME: This, like the main visit, doesn't support CUDAKernelCallExpr.
1317 // FIXME: An isa<> would look much better but this whole switch is a
1318 // workaround for an internal compiler error in MSVC 2015 (see r326021).
1319 case Stmt::CallExprClass:
1320 case Stmt::CXXMemberCallExprClass:
1321 case Stmt::CXXOperatorCallExprClass:
Artem Dergacheve1f30622018-07-31 19:46:14 +00001322 case Stmt::UserDefinedLiteralClass:
1323 case Stmt::ObjCMessageExprClass: {
1324 auto *E = cast<Expr>(Child);
1325 if (CFGCXXRecordTypedCall::isCXXRecordTypedCall(E))
1326 consumeConstructionContext(Layer, E);
Artem Dergachev1527dec2018-03-12 23:12:40 +00001327 break;
1328 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001329 case Stmt::ExprWithCleanupsClass: {
1330 auto *Cleanups = cast<ExprWithCleanups>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001331 findConstructionContexts(Layer, Cleanups->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001332 break;
1333 }
1334 case Stmt::CXXFunctionalCastExprClass: {
1335 auto *Cast = cast<CXXFunctionalCastExpr>(Child);
Artem Dergachev40684812018-02-27 20:03:35 +00001336 findConstructionContexts(Layer, Cast->getSubExpr());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001337 break;
1338 }
1339 case Stmt::ImplicitCastExprClass: {
1340 auto *Cast = cast<ImplicitCastExpr>(Child);
Artem Dergachev317291e2018-03-22 21:37:39 +00001341 // Should we support other implicit cast kinds?
Artem Dergachev13f96642018-03-09 01:39:59 +00001342 switch (Cast->getCastKind()) {
1343 case CK_NoOp:
1344 case CK_ConstructorConversion:
Artem Dergachev66030522018-03-01 01:09:24 +00001345 findConstructionContexts(Layer, Cast->getSubExpr());
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00001346 break;
Artem Dergachev13f96642018-03-09 01:39:59 +00001347 default:
1348 break;
1349 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001350 break;
1351 }
1352 case Stmt::CXXBindTemporaryExprClass: {
1353 auto *BTE = cast<CXXBindTemporaryExpr>(Child);
Artem Dergachevff267df2018-06-28 00:04:54 +00001354 findConstructionContexts(withExtraLayer(BTE), BTE->getSubExpr());
1355 break;
1356 }
1357 case Stmt::MaterializeTemporaryExprClass: {
1358 // Normally we don't want to search in MaterializeTemporaryExpr because
1359 // it indicates the beginning of a temporary object construction context,
1360 // so it shouldn't be found in the middle. However, if it is the beginning
1361 // of an elidable copy or move construction context, we need to include it.
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001362 if (Layer->getItem().getKind() ==
1363 ConstructionContextItem::ElidableConstructorKind) {
1364 auto *MTE = cast<MaterializeTemporaryExpr>(Child);
1365 findConstructionContexts(withExtraLayer(MTE), MTE->GetTemporaryExpr());
Artem Dergachevff267df2018-06-28 00:04:54 +00001366 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001367 break;
1368 }
1369 case Stmt::ConditionalOperatorClass: {
1370 auto *CO = cast<ConditionalOperator>(Child);
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00001371 if (Layer->getItem().getKind() !=
1372 ConstructionContextItem::MaterializationKind) {
Artem Dergachev9d3a7d82018-03-30 19:21:18 +00001373 // If the object returned by the conditional operator is not going to be a
1374 // temporary object that needs to be immediately materialized, then
1375 // it must be C++17 with its mandatory copy elision. Do not yet promise
1376 // to support this case.
1377 assert(!CO->getType()->getAsCXXRecordDecl() || CO->isGLValue() ||
1378 Context->getLangOpts().CPlusPlus17);
1379 break;
1380 }
Artem Dergachev40684812018-02-27 20:03:35 +00001381 findConstructionContexts(Layer, CO->getLHS());
1382 findConstructionContexts(Layer, CO->getRHS());
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001383 break;
1384 }
Artem Dergachevaa403152019-03-21 00:15:07 +00001385 case Stmt::InitListExprClass: {
1386 auto *ILE = cast<InitListExpr>(Child);
1387 if (ILE->isTransparent()) {
1388 findConstructionContexts(Layer, ILE->getInit(0));
1389 break;
1390 }
1391 // TODO: Handle other cases. For now, fail to find construction contexts.
1392 break;
1393 }
Artem Dergachev1c6ed3a2018-02-24 03:54:22 +00001394 default:
1395 break;
Artem Dergachev41ffb302018-02-08 22:58:15 +00001396 }
1397}
1398
Artem Dergachev1527dec2018-03-12 23:12:40 +00001399void CFGBuilder::cleanupConstructionContext(Expr *E) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001400 assert(BuildOpts.AddRichCXXConstructors &&
1401 "We should not be managing construction contexts!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001402 assert(ConstructionContextMap.count(E) &&
Artem Dergachev41ffb302018-02-08 22:58:15 +00001403 "Cannot exit construction context without the context!");
Artem Dergachev1527dec2018-03-12 23:12:40 +00001404 ConstructionContextMap.erase(E);
Artem Dergachev41ffb302018-02-08 22:58:15 +00001405}
1406
1407
Mike Stump31feda52009-07-17 01:31:16 +00001408/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1409/// arbitrary statement. Examples include a single expression or a function
1410/// body (compound statement). The ownership of the returned CFG is
1411/// transferred to the caller. If CFG construction fails, this method returns
1412/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001413std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001414 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001415 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001416 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001417
Mike Stump31feda52009-07-17 01:31:16 +00001418 // Create an empty block that will serve as the exit block for the CFG. Since
1419 // this is the first block added to the CFG, it will be implicitly registered
1420 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001421 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001422 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001423 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001424
Matthias Gehre351c2182017-07-12 07:04:19 +00001425 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1426 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1427
Marcin Swiderski20b88732010-10-05 05:37:00 +00001428 if (BuildOpts.AddImplicitDtors)
1429 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1430 addImplicitDtorsForDestructor(DD);
1431
Ted Kremenek9aae5132007-08-23 21:42:29 +00001432 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001433 CFGBlock *B = addStmt(Statement);
1434
1435 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001436 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001437
Artem Dergachev192a7472019-05-24 23:37:08 +00001438 // For C++ constructor add initializers to CFG. Constructors of virtual bases
1439 // are ignored unless the object is of the most derived class.
1440 // class VBase { VBase() = default; VBase(int) {} };
1441 // class A : virtual public VBase { A() : VBase(0) {} };
1442 // class B : public A {};
1443 // B b; // Constructor calls in order: VBase(), A(), B().
1444 // // VBase(0) is ignored because A isn't the most derived class.
1445 // This may result in the virtual base(s) being already initialized at this
1446 // point, in which case we should jump right onto non-virtual bases and
1447 // fields. To handle this, make a CFG branch. We only need to add one such
1448 // branch per constructor, since the Standard states that all virtual bases
1449 // shall be initialized before non-virtual bases and direct data members.
1450 if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
1451 CFGBlock *VBaseSucc = nullptr;
Pete Cooper57d3f142015-07-30 17:22:52 +00001452 for (auto *I : llvm::reverse(CD->inits())) {
Artem Dergachev192a7472019-05-24 23:37:08 +00001453 if (BuildOpts.AddVirtualBaseBranches && !VBaseSucc &&
1454 I->isBaseInitializer() && I->isBaseVirtual()) {
1455 // We've reached the first virtual base init while iterating in reverse
1456 // order. Make a new block for virtual base initializers so that we
1457 // could skip them.
1458 VBaseSucc = Succ = B ? B : &cfg->getExit();
1459 Block = createBlock();
1460 }
Pete Cooper57d3f142015-07-30 17:22:52 +00001461 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001462 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001463 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001464 }
Artem Dergachev192a7472019-05-24 23:37:08 +00001465 if (VBaseSucc) {
1466 // Make a branch block for potentially skipping virtual base initializers.
1467 Succ = VBaseSucc;
1468 B = createBlock();
1469 B->setTerminator(
1470 CFGTerminator(nullptr, CFGTerminator::VirtualBaseBranch));
1471 addSuccessor(B, Block, true);
1472 }
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001473 }
1474
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001475 if (B)
1476 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001477
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001478 // Backpatch the gotos whose label -> block mappings we didn't know when we
1479 // encountered them.
1480 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1481 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001482
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001483 CFGBlock *B = I->block;
Jennifer Yub8fee672019-06-03 15:57:25 +00001484 if (auto *G = dyn_cast<GotoStmt>(B->getTerminator())) {
1485 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
1486 // If there is no target for the goto, then we are looking at an
1487 // incomplete AST. Handle this by not registering a successor.
1488 if (LI == LabelMap.end())
1489 continue;
1490 JumpTarget JT = LI->second;
1491 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1492 JT.scopePosition);
1493 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1494 JT.scopePosition);
1495 const VarDecl *VD = prependAutomaticObjScopeEndWithTerminator(
1496 B, I->scopePosition, JT.scopePosition);
1497 appendScopeBegin(JT.block, VD, G);
1498 addSuccessor(B, JT.block);
1499 };
1500 if (auto *G = dyn_cast<GCCAsmStmt>(B->getTerminator())) {
1501 CFGBlock *Successor = (I+1)->block;
1502 for (auto *L : G->labels()) {
1503 LabelMapTy::iterator LI = LabelMap.find(L->getLabel());
1504 // If there is no target for the goto, then we are looking at an
1505 // incomplete AST. Handle this by not registering a successor.
1506 if (LI == LabelMap.end())
1507 continue;
1508 JumpTarget JT = LI->second;
1509 // Successor has been added, so skip it.
1510 if (JT.block == Successor)
1511 continue;
1512 addSuccessor(B, JT.block);
1513 }
1514 I++;
1515 }
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001516 }
1517
1518 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001519 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001520 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1521 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001522 // Lookup the target block.
1523 LabelMapTy::iterator LI = LabelMap.find(*I);
1524
1525 // If there is no target block that contains label, then we are looking
1526 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001527 if (LI == LabelMap.end()) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001528
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001529 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001530 }
Mike Stump31feda52009-07-17 01:31:16 +00001531
Mike Stump31feda52009-07-17 01:31:16 +00001532 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001533 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001534
Artem Dergachev783a4572018-02-23 22:20:39 +00001535 if (BuildOpts.AddRichCXXConstructors)
1536 assert(ConstructionContextMap.empty() &&
1537 "Not all construction contexts were cleaned up!");
1538
David Blaikiee90195c2014-08-29 18:53:26 +00001539 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001540}
Mike Stump31feda52009-07-17 01:31:16 +00001541
Ted Kremenek9aae5132007-08-23 21:42:29 +00001542/// createBlock - Used to lazily create blocks that are connected
1543/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001544CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1545 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001546 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001547 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001548 return B;
1549}
Mike Stump31feda52009-07-17 01:31:16 +00001550
Chandler Carrutha70991b2011-09-13 09:13:49 +00001551/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1552/// CFG. It is *not* connected to the current (global) successor, and instead
1553/// directly tied to the exit block in order to be reachable.
1554CFGBlock *CFGBuilder::createNoReturnBlock() {
1555 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001556 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001557 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001558 return B;
1559}
1560
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001561/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001562CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001563 if (!BuildOpts.AddInitializers)
1564 return Block;
1565
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001566 bool HasTemporaries = false;
1567
1568 // Destructors of temporaries in initialization expression should be called
1569 // after initialization finishes.
1570 Expr *Init = I->getInit();
1571 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001572 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001573
Jordan Rose6d671cc2012-09-05 22:55:23 +00001574 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001575 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001576 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001577 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1578 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001579 }
1580 }
1581
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001582 autoCreateBlock();
1583 appendInitializer(Block, I);
1584
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001585 if (Init) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001586 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00001587 ConstructionContextLayer::create(cfg->getBumpVectorContext(), I),
Artem Dergachev783a4572018-02-23 22:20:39 +00001588 Init);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001589
Ted Kremenek8219b822010-12-16 07:46:53 +00001590 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001591 // For expression with temporaries go directly to subexpression to omit
1592 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001593 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1594 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001595 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1596 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1597 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1598 // may cause the same Expr to appear more than once in the CFG. Doing it
1599 // here is safe because there's only one initializer per field.
1600 autoCreateBlock();
1601 appendStmt(Block, Default);
1602 if (Stmt *Child = Default->getExpr())
1603 if (CFGBlock *R = Visit(Child))
1604 Block = R;
1605 return Block;
1606 }
1607 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001608 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001609 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001610
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001611 return Block;
1612}
1613
Fangrui Song6907ce22018-07-30 19:24:48 +00001614/// Retrieve the type of the temporary object whose lifetime was
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001615/// extended by a local reference with the given initializer.
Artem Dergacheva25809f2018-06-04 18:56:25 +00001616static QualType getReferenceInitTemporaryType(const Expr *Init,
Richard Smithb8c0f552016-12-09 18:49:13 +00001617 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001618 while (true) {
1619 // Skip parentheses.
1620 Init = Init->IgnoreParens();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001621
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001622 // Skip through cleanups.
1623 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1624 Init = EWC->getSubExpr();
1625 continue;
1626 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001627
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001628 // Skip through the temporary-materialization expression.
1629 if (const MaterializeTemporaryExpr *MTE
1630 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1631 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001632 if (FoundMTE)
1633 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001634 continue;
1635 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001636
1637 // Skip sub-object accesses into rvalues.
1638 SmallVector<const Expr *, 2> CommaLHSs;
1639 SmallVector<SubobjectAdjustment, 2> Adjustments;
1640 const Expr *SkippedInit =
1641 Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1642 if (SkippedInit != Init) {
1643 Init = SkippedInit;
1644 continue;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001645 }
Artem Dergacheva25809f2018-06-04 18:56:25 +00001646
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001647 break;
1648 }
1649
1650 return Init->getType();
1651}
Matthias Gehre351c2182017-07-12 07:04:19 +00001652
Peter Szecsi999a25f2017-08-19 11:19:16 +00001653// TODO: Support adding LoopExit element to the CFG in case where the loop is
1654// ended by ReturnStmt, GotoStmt or ThrowExpr.
1655void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1656 if(!BuildOpts.AddLoopExit)
1657 return;
1658 autoCreateBlock();
1659 appendLoopExit(Block, LoopStmt);
1660}
1661
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001662void CFGBuilder::getDeclsWithEndedScope(LocalScope::const_iterator B,
1663 LocalScope::const_iterator E, Stmt *S) {
1664 if (!BuildOpts.AddScopes)
1665 return;
1666
1667 if (B == E)
1668 return;
1669
1670 // To go from B to E, one first goes up the scopes from B to P
1671 // then sideways in one scope from P to P' and then down
1672 // the scopes from P' to E.
1673 // The lifetime of all objects between B and P end.
1674 LocalScope::const_iterator P = B.shared_parent(E);
1675 int Dist = B.distance(P);
1676 if (Dist <= 0)
1677 return;
1678
1679 for (LocalScope::const_iterator I = B; I != P; ++I)
1680 if (I.pointsToFirstDeclaredVar())
1681 DeclsWithEndedScope.insert(*I);
1682}
1683
Matthias Gehre351c2182017-07-12 07:04:19 +00001684void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1685 LocalScope::const_iterator E,
1686 Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001687 getDeclsWithEndedScope(B, E, S);
1688 if (BuildOpts.AddScopes)
1689 addScopesEnd(B, E, S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001690 if (BuildOpts.AddImplicitDtors)
1691 addAutomaticObjDtors(B, E, S);
1692 if (BuildOpts.AddLifetime)
1693 addLifetimeEnds(B, E, S);
1694}
1695
1696/// Add to current block automatic objects that leave the scope.
1697void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1698 LocalScope::const_iterator E, Stmt *S) {
1699 if (!BuildOpts.AddLifetime)
1700 return;
1701
1702 if (B == E)
1703 return;
1704
1705 // To go from B to E, one first goes up the scopes from B to P
1706 // then sideways in one scope from P to P' and then down
1707 // the scopes from P' to E.
1708 // The lifetime of all objects between B and P end.
1709 LocalScope::const_iterator P = B.shared_parent(E);
1710 int dist = B.distance(P);
1711 if (dist <= 0)
1712 return;
1713
1714 // We need to perform the scope leaving in reverse order
1715 SmallVector<VarDecl *, 10> DeclsTrivial;
1716 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1717 DeclsTrivial.reserve(dist);
1718 DeclsNonTrivial.reserve(dist);
1719
1720 for (LocalScope::const_iterator I = B; I != P; ++I)
1721 if (hasTrivialDestructor(*I))
1722 DeclsTrivial.push_back(*I);
1723 else
1724 DeclsNonTrivial.push_back(*I);
1725
1726 autoCreateBlock();
1727 // object with trivial destructor end their lifetime last (when storage
1728 // duration ends)
1729 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1730 E = DeclsTrivial.rend();
1731 I != E; ++I)
1732 appendLifetimeEnds(Block, *I, S);
1733
1734 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1735 I = DeclsNonTrivial.rbegin(),
1736 E = DeclsNonTrivial.rend();
1737 I != E; ++I)
1738 appendLifetimeEnds(Block, *I, S);
1739}
1740
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001741/// Add to current block markers for ending scopes.
1742void CFGBuilder::addScopesEnd(LocalScope::const_iterator B,
1743 LocalScope::const_iterator E, Stmt *S) {
1744 // If implicit destructors are enabled, we'll add scope ends in
1745 // addAutomaticObjDtors.
1746 if (BuildOpts.AddImplicitDtors)
1747 return;
1748
1749 autoCreateBlock();
1750
1751 for (auto I = DeclsWithEndedScope.rbegin(), E = DeclsWithEndedScope.rend();
1752 I != E; ++I)
1753 appendScopeEnd(Block, *I, S);
1754
1755 return;
1756}
1757
Marcin Swiderski5e415732010-09-30 23:05:00 +00001758/// addAutomaticObjDtors - Add to current block automatic objects destructors
1759/// for objects in range of local scope positions. Use S as trigger statement
1760/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001761void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001762 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001763 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001764 return;
1765
Marcin Swiderski5e415732010-09-30 23:05:00 +00001766 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001767 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001768
Chandler Carruthad747252011-09-13 06:09:01 +00001769 // We need to append the destructors in reverse order, but any one of them
1770 // may be a no-return destructor which changes the CFG. As a result, buffer
1771 // this sequence up and replay them in reverse order when appending onto the
1772 // CFGBlock(s).
1773 SmallVector<VarDecl*, 10> Decls;
1774 Decls.reserve(B.distance(E));
1775 for (LocalScope::const_iterator I = B; I != E; ++I)
1776 Decls.push_back(*I);
1777
1778 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1779 E = Decls.rend();
1780 I != E; ++I) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001781 if (hasTrivialDestructor(*I)) {
1782 // If AddScopes is enabled and *I is a first variable in a scope, add a
1783 // ScopeEnd marker in a Block.
1784 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I)) {
1785 autoCreateBlock();
1786 appendScopeEnd(Block, *I, S);
1787 }
1788 continue;
1789 }
Chandler Carruthad747252011-09-13 06:09:01 +00001790 // If this destructor is marked as a no-return destructor, we need to
1791 // create a new block for the destructor which does not have as a successor
1792 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001793 QualType Ty = (*I)->getType();
1794 if (Ty->isReferenceType()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00001795 Ty = getReferenceInitTemporaryType((*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001796 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001797 Ty = Context->getBaseElementType(Ty);
1798
Richard Trieu95a192a2015-05-28 00:14:02 +00001799 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001800 Block = createNoReturnBlock();
1801 else
Chandler Carruthad747252011-09-13 06:09:01 +00001802 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001803
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001804 // Add ScopeEnd just after automatic obj destructor.
1805 if (BuildOpts.AddScopes && DeclsWithEndedScope.count(*I))
1806 appendScopeEnd(Block, *I, S);
Chandler Carruthad747252011-09-13 06:09:01 +00001807 appendAutomaticObjDtor(Block, *I, S);
1808 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001809}
1810
Marcin Swiderski20b88732010-10-05 05:37:00 +00001811/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1812/// base and member objects in destructor.
1813void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001814 assert(BuildOpts.AddImplicitDtors &&
1815 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001816 const CXXRecordDecl *RD = DD->getParent();
1817
1818 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001819 for (const auto &VI : RD->vbases()) {
Artem Dergachev192a7472019-05-24 23:37:08 +00001820 // TODO: Add a VirtualBaseBranch to see if the most derived class
1821 // (which is different from the current class) is responsible for
1822 // destroying them.
Aaron Ballman445a9392014-03-13 16:15:17 +00001823 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001824 if (!CD->hasTrivialDestructor()) {
1825 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001826 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001827 }
1828 }
1829
1830 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001831 for (const auto &BI : RD->bases()) {
1832 if (!BI.isVirtual()) {
1833 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001834 if (!CD->hasTrivialDestructor()) {
1835 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001836 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001837 }
1838 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001839 }
1840
1841 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001842 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001843 // Check for constant size array. Set type to array element type.
1844 QualType QT = FI->getType();
1845 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1846 if (AT->getSize() == 0)
1847 continue;
1848 QT = AT->getElementType();
1849 }
1850
1851 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001852 if (!CD->hasTrivialDestructor()) {
1853 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001854 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001855 }
1856 }
1857}
1858
Marcin Swiderski5e415732010-09-30 23:05:00 +00001859/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1860/// way return valid LocalScope object.
1861LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001862 if (Scope)
1863 return Scope;
1864 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1865 return new (alloc.Allocate<LocalScope>())
1866 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001867}
1868
1869/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Fangrui Song6907ce22018-07-30 19:24:48 +00001870/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001871void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001872 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1873 !BuildOpts.AddScopes)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001874 return;
1875
Craig Topper25542942014-05-20 04:30:07 +00001876 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001877
1878 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001879 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001880 for (auto *BI : CS->body()) {
1881 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001882 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001883 Scope = addLocalScopeForDeclStmt(DS, Scope);
1884 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001885 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001886 }
1887
1888 // For any other statement scope will be implicit and as such will be
1889 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001890 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001891 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001892}
1893
1894/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1895/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001896LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001897 LocalScope* Scope) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001898 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1899 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001900 return Scope;
1901
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001902 for (auto *DI : DS->decls())
1903 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001904 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001905 return Scope;
1906}
1907
Matthias Gehre351c2182017-07-12 07:04:19 +00001908bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1909 // Check for const references bound to temporary. Set type to pointee.
1910 QualType QT = VD->getType();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001911 if (QT->isReferenceType()) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001912 // Attempt to determine whether this declaration lifetime-extends a
1913 // temporary.
1914 //
1915 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1916 // temporaries, and a single declaration can extend multiple temporaries.
1917 // We should look at the storage duration on each nested
1918 // MaterializeTemporaryExpr instead.
1919
1920 const Expr *Init = VD->getInit();
Artem Dergacheva25809f2018-06-04 18:56:25 +00001921 if (!Init) {
1922 // Probably an exception catch-by-reference variable.
1923 // FIXME: It doesn't really mean that the object has a trivial destructor.
1924 // Also are there other cases?
Matthias Gehre351c2182017-07-12 07:04:19 +00001925 return true;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001926 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001927
Artem Dergacheva25809f2018-06-04 18:56:25 +00001928 // Lifetime-extending a temporary?
Matthias Gehre351c2182017-07-12 07:04:19 +00001929 bool FoundMTE = false;
Artem Dergacheva25809f2018-06-04 18:56:25 +00001930 QT = getReferenceInitTemporaryType(Init, &FoundMTE);
Matthias Gehre351c2182017-07-12 07:04:19 +00001931 if (!FoundMTE)
1932 return true;
1933 }
1934
1935 // Check for constant size array. Set type to array element type.
1936 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1937 if (AT->getSize() == 0)
1938 return true;
1939 QT = AT->getElementType();
1940 }
1941
1942 // Check if type is a C++ class with non-trivial destructor.
1943 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1944 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1945 return true;
1946}
1947
Marcin Swiderski5e415732010-09-30 23:05:00 +00001948/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1949/// create add scope for automatic objects and temporary objects bound to
1950/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001951LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001952 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001953 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1954 "AddImplicitDtors and AddLifetime cannot be used at the same time");
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001955 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime &&
1956 !BuildOpts.AddScopes)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001957 return Scope;
1958
1959 // Check if variable is local.
1960 switch (VD->getStorageClass()) {
1961 case SC_None:
1962 case SC_Auto:
1963 case SC_Register:
1964 break;
1965 default: return Scope;
1966 }
1967
Matthias Gehre351c2182017-07-12 07:04:19 +00001968 if (BuildOpts.AddImplicitDtors) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00001969 if (!hasTrivialDestructor(VD) || BuildOpts.AddScopes) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001970 // Add the variable to scope
1971 Scope = createOrReuseLocalScope(Scope);
1972 Scope->addVar(VD);
1973 ScopePos = Scope->begin();
1974 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001975 return Scope;
1976 }
1977
1978 assert(BuildOpts.AddLifetime);
1979 // Add the variable to scope
1980 Scope = createOrReuseLocalScope(Scope);
1981 Scope->addVar(VD);
1982 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001983 return Scope;
1984}
1985
1986/// addLocalScopeAndDtors - For given statement add local scope for it and
1987/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001988void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001989 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001990 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001991 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001992}
1993
Marcin Swiderski321a7072010-09-30 22:54:37 +00001994/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1995/// variables with automatic storage duration to CFGBlock's elements vector.
1996/// Elements will be prepended to physical beginning of the vector which
1997/// happens to be logical end. Use blocks terminator as statement that specifies
1998/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001999/// FIXME: This mechanism for adding automatic destructors doesn't handle
2000/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002001void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00002002 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002003 if (!BuildOpts.AddImplicitDtors)
2004 return;
Chandler Carruthad747252011-09-13 06:09:01 +00002005 BumpVectorContext &C = cfg->getBumpVectorContext();
2006 CFGBlock::iterator InsertPos
2007 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
2008 for (LocalScope::const_iterator I = B; I != E; ++I)
2009 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
Artem Dergachev4e530322019-05-24 01:34:22 +00002010 Blk->getTerminatorStmt());
Marcin Swiderski321a7072010-09-30 22:54:37 +00002011}
2012
Matthias Gehre351c2182017-07-12 07:04:19 +00002013/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
2014/// variables with automatic storage duration to CFGBlock's elements vector.
2015/// Elements will be prepended to physical beginning of the vector which
2016/// happens to be logical end. Use blocks terminator as statement that specifies
2017/// where lifetime ends.
2018void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
2019 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2020 if (!BuildOpts.AddLifetime)
2021 return;
2022 BumpVectorContext &C = cfg->getBumpVectorContext();
2023 CFGBlock::iterator InsertPos =
2024 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
Artem Dergachev4e530322019-05-24 01:34:22 +00002025 for (LocalScope::const_iterator I = B; I != E; ++I) {
2026 InsertPos =
2027 Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminatorStmt());
2028 }
Matthias Gehre351c2182017-07-12 07:04:19 +00002029}
Eugene Zelenko38c70522017-12-07 21:55:09 +00002030
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002031/// prependAutomaticObjScopeEndWithTerminator - Prepend scope end CFGElements for
2032/// variables with automatic storage duration to CFGBlock's elements vector.
2033/// Elements will be prepended to physical beginning of the vector which
2034/// happens to be logical end. Use blocks terminator as statement that specifies
2035/// where scope ends.
2036const VarDecl *
2037CFGBuilder::prependAutomaticObjScopeEndWithTerminator(
2038 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
2039 if (!BuildOpts.AddScopes)
2040 return nullptr;
2041 BumpVectorContext &C = cfg->getBumpVectorContext();
2042 CFGBlock::iterator InsertPos =
2043 Blk->beginScopeEndInsert(Blk->end(), 1, C);
2044 LocalScope::const_iterator PlaceToInsert = B;
2045 for (LocalScope::const_iterator I = B; I != E; ++I)
2046 PlaceToInsert = I;
Artem Dergachev4e530322019-05-24 01:34:22 +00002047 Blk->insertScopeEnd(InsertPos, *PlaceToInsert, Blk->getTerminatorStmt());
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002048 return *PlaceToInsert;
2049}
2050
Ted Kremenek93668002009-07-17 22:18:43 +00002051/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00002052/// blocks for ternary operators, &&, and ||. We also process "," and
2053/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002054CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00002055 if (!S) {
2056 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00002057 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00002058 }
Jordy Rose17347372011-06-10 08:49:37 +00002059
2060 if (Expr *E = dyn_cast<Expr>(S))
2061 S = E->IgnoreParens();
2062
Alexey Bataevc2c21ef2019-07-11 14:54:17 +00002063 if (Context->getLangOpts().OpenMP)
2064 if (auto *D = dyn_cast<OMPExecutableDirective>(S))
2065 return VisitOMPExecutableDirective(D, asc);
2066
Ted Kremenek93668002009-07-17 22:18:43 +00002067 switch (S->getStmtClass()) {
2068 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002069 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002070
2071 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002072 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCallc07a0c72011-02-17 10:25:35 +00002074 case Stmt::BinaryConditionalOperatorClass:
2075 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
2076
Ted Kremenek93668002009-07-17 22:18:43 +00002077 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002078 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenek93668002009-07-17 22:18:43 +00002080 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00002081 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00002082
Ted Kremenek93668002009-07-17 22:18:43 +00002083 case Stmt::BreakStmtClass:
2084 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002085
Ted Kremenek93668002009-07-17 22:18:43 +00002086 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00002087 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00002088 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00002089 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002090 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002091
Ted Kremenek93668002009-07-17 22:18:43 +00002092 case Stmt::CaseStmtClass:
2093 return VisitCaseStmt(cast<CaseStmt>(S));
2094
2095 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002096 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002097
Ted Kremenek93668002009-07-17 22:18:43 +00002098 case Stmt::CompoundStmtClass:
2099 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002100
Ted Kremenek93668002009-07-17 22:18:43 +00002101 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002102 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Ted Kremenek93668002009-07-17 22:18:43 +00002104 case Stmt::ContinueStmtClass:
2105 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002106
Ted Kremenekb27378c2010-01-19 20:40:33 +00002107 case Stmt::CXXCatchStmtClass:
2108 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
2109
John McCall5d413782010-12-06 08:20:24 +00002110 case Stmt::ExprWithCleanupsClass:
2111 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00002112
Jordan Rosee5d53932012-08-23 18:10:53 +00002113 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00002114 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00002115 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
2116 // called function's declaration, not by the caller. If we simply add
2117 // this expression to the CFG, we could end up with the same Expr
2118 // appearing multiple times.
2119 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00002120 //
2121 // It's likewise possible for multiple CXXDefaultInitExprs for the same
2122 // expression to be used in the same function (through aggregate
2123 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00002124 return VisitStmt(S, asc);
2125
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002126 case Stmt::CXXBindTemporaryExprClass:
2127 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
2128
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002129 case Stmt::CXXConstructExprClass:
2130 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
2131
Jordan Rosec9176072014-01-13 17:59:19 +00002132 case Stmt::CXXNewExprClass:
2133 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
2134
Jordan Rosed2f40792013-09-03 17:00:57 +00002135 case Stmt::CXXDeleteExprClass:
2136 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
2137
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002138 case Stmt::CXXFunctionalCastExprClass:
2139 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
2140
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00002141 case Stmt::CXXTemporaryObjectExprClass:
2142 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
2143
Ted Kremenekb27378c2010-01-19 20:40:33 +00002144 case Stmt::CXXThrowExprClass:
2145 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002146
Ted Kremenekb27378c2010-01-19 20:40:33 +00002147 case Stmt::CXXTryStmtClass:
2148 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002149
Richard Smith02e85f32011-04-14 22:09:26 +00002150 case Stmt::CXXForRangeStmtClass:
2151 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
2152
Ted Kremenek93668002009-07-17 22:18:43 +00002153 case Stmt::DeclStmtClass:
2154 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002155
Ted Kremenek93668002009-07-17 22:18:43 +00002156 case Stmt::DefaultStmtClass:
2157 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002158
Ted Kremenek93668002009-07-17 22:18:43 +00002159 case Stmt::DoStmtClass:
2160 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002161
Ted Kremenek93668002009-07-17 22:18:43 +00002162 case Stmt::ForStmtClass:
2163 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002164
Ted Kremenek93668002009-07-17 22:18:43 +00002165 case Stmt::GotoStmtClass:
2166 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002167
Jennifer Yub8fee672019-06-03 15:57:25 +00002168 case Stmt::GCCAsmStmtClass:
2169 return VisitGCCAsmStmt(cast<GCCAsmStmt>(S), asc);
2170
Ted Kremenek93668002009-07-17 22:18:43 +00002171 case Stmt::IfStmtClass:
2172 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002173
Ted Kremenek8219b822010-12-16 07:46:53 +00002174 case Stmt::ImplicitCastExprClass:
2175 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00002176
Bill Wendling8003edc2018-11-09 00:41:36 +00002177 case Stmt::ConstantExprClass:
2178 return VisitConstantExpr(cast<ConstantExpr>(S), asc);
2179
Ted Kremenek93668002009-07-17 22:18:43 +00002180 case Stmt::IndirectGotoStmtClass:
2181 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002182
Ted Kremenek93668002009-07-17 22:18:43 +00002183 case Stmt::LabelStmtClass:
2184 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002185
Ted Kremenekda76a942012-04-12 20:34:52 +00002186 case Stmt::LambdaExprClass:
2187 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
2188
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00002189 case Stmt::MaterializeTemporaryExprClass:
2190 return VisitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(S),
2191 asc);
2192
Ted Kremenek5868ec62010-04-11 17:02:10 +00002193 case Stmt::MemberExprClass:
2194 return VisitMemberExpr(cast<MemberExpr>(S), asc);
2195
Ted Kremenek04268232011-11-05 00:10:15 +00002196 case Stmt::NullStmtClass:
2197 return Block;
2198
Ted Kremenek93668002009-07-17 22:18:43 +00002199 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00002200 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
2201
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002202 case Stmt::ObjCAutoreleasePoolStmtClass:
2203 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
2204
Ted Kremenek93668002009-07-17 22:18:43 +00002205 case Stmt::ObjCAtSynchronizedStmtClass:
2206 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002207
Ted Kremenek93668002009-07-17 22:18:43 +00002208 case Stmt::ObjCAtThrowStmtClass:
2209 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002210
Ted Kremenek93668002009-07-17 22:18:43 +00002211 case Stmt::ObjCAtTryStmtClass:
2212 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002213
Ted Kremenek93668002009-07-17 22:18:43 +00002214 case Stmt::ObjCForCollectionStmtClass:
2215 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002216
Artem Dergachevbd880fe2018-07-31 19:39:37 +00002217 case Stmt::ObjCMessageExprClass:
2218 return VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), asc);
2219
Ted Kremenek04268232011-11-05 00:10:15 +00002220 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00002221 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00002222
John McCallfe96e0b2011-11-06 09:01:30 +00002223 case Stmt::PseudoObjectExprClass:
2224 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
2225
Ted Kremenek93668002009-07-17 22:18:43 +00002226 case Stmt::ReturnStmtClass:
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002227 case Stmt::CoreturnStmtClass:
2228 return VisitReturnStmt(S);
Mike Stump11289f42009-09-09 15:08:12 +00002229
Nico Weber699670e2017-08-23 15:33:16 +00002230 case Stmt::SEHExceptStmtClass:
2231 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
2232
2233 case Stmt::SEHFinallyStmtClass:
2234 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
2235
2236 case Stmt::SEHLeaveStmtClass:
2237 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
2238
2239 case Stmt::SEHTryStmtClass:
2240 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
2241
Peter Collingbournee190dee2011-03-11 19:24:49 +00002242 case Stmt::UnaryExprOrTypeTraitExprClass:
2243 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
2244 asc);
Mike Stump11289f42009-09-09 15:08:12 +00002245
Ted Kremenek93668002009-07-17 22:18:43 +00002246 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002247 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00002248
Ted Kremenek93668002009-07-17 22:18:43 +00002249 case Stmt::SwitchStmtClass:
2250 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00002251
Zhanyong Wan6dace612010-11-22 08:45:56 +00002252 case Stmt::UnaryOperatorClass:
2253 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
2254
Ted Kremenek93668002009-07-17 22:18:43 +00002255 case Stmt::WhileStmtClass:
2256 return VisitWhileStmt(cast<WhileStmt>(S));
2257 }
2258}
Mike Stump11289f42009-09-09 15:08:12 +00002259
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002260CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002261 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002262 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002263 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00002264 }
Mike Stump11289f42009-09-09 15:08:12 +00002265
Ted Kremenek93668002009-07-17 22:18:43 +00002266 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00002267}
Mike Stump31feda52009-07-17 01:31:16 +00002268
Ted Kremenek93668002009-07-17 22:18:43 +00002269/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00002270CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
2271 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00002272
Ted Kremenek8ae67872013-02-05 22:00:19 +00002273 // Visit the children in their reverse order so that they appear in
2274 // left-to-right (natural) order in the CFG.
2275 reverse_children RChildren(S);
2276 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
2277 I != E; ++I) {
2278 if (Stmt *Child = *I)
2279 if (CFGBlock *R = Visit(Child))
2280 B = R;
2281 }
2282 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00002283}
Mike Stump11289f42009-09-09 15:08:12 +00002284
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002285CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
2286 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00002287 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00002288
Ted Kremenek7c58d352011-03-10 01:14:11 +00002289 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00002290 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002291 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00002292 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002293
Ted Kremenek9aae5132007-08-23 21:42:29 +00002294 return Block;
2295}
Mike Stump11289f42009-09-09 15:08:12 +00002296
Zhanyong Wan6dace612010-11-22 08:45:56 +00002297CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00002298 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002299 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00002300 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002301 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00002302 }
2303
Ted Kremenek8219b822010-12-16 07:46:53 +00002304 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00002305}
2306
Ted Kremeneka16436f2012-07-14 05:04:06 +00002307CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
2308 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
2309 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00002310
Ted Kremeneka16436f2012-07-14 05:04:06 +00002311 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002312 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00002313
Craig Topper25542942014-05-20 04:30:07 +00002314 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
2315 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002316}
2317
2318std::pair<CFGBlock*, CFGBlock*>
2319CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
2320 Stmt *Term,
2321 CFGBlock *TrueBlock,
2322 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00002323 // Introspect the RHS. If it is a nested logical operation, we recursively
2324 // build the CFG using this function. Otherwise, resort to default
2325 // CFG construction behavior.
2326 Expr *RHS = B->getRHS()->IgnoreParens();
2327 CFGBlock *RHSBlock, *ExitBlock;
2328
2329 do {
2330 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
2331 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002332 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002333 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
2334 break;
2335 }
2336
2337 // The RHS is not a nested logical operation. Don't push the terminator
2338 // down further, but instead visit RHS and construct the respective
2339 // pieces of the CFG, and link up the RHSBlock with the terminator
2340 // we have been provided.
2341 ExitBlock = RHSBlock = createBlock(false);
2342
Richard Trieu6a6af522017-01-04 00:46:30 +00002343 // Even though KnownVal is only used in the else branch of the next
2344 // conditional, tryEvaluateBool performs additional checking on the
2345 // Expr, so it should be called unconditionally.
2346 TryResult KnownVal = tryEvaluateBool(RHS);
2347 if (!KnownVal.isKnown())
2348 KnownVal = tryEvaluateBool(B);
2349
Ted Kremenekb50e7162012-07-14 05:04:10 +00002350 if (!Term) {
2351 assert(TrueBlock == FalseBlock);
2352 addSuccessor(RHSBlock, TrueBlock);
2353 }
2354 else {
2355 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00002356 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
2357 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00002358 }
2359
2360 Block = RHSBlock;
2361 RHSBlock = addStmt(RHS);
2362 }
2363 while (false);
2364
2365 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002366 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002367
2368 // Generate the blocks for evaluating the LHS.
2369 Expr *LHS = B->getLHS()->IgnoreParens();
2370
2371 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2372 if (B_LHS->isLogicalOp()) {
2373 if (B->getOpcode() == BO_LOr)
2374 FalseBlock = RHSBlock;
2375 else
2376 TrueBlock = RHSBlock;
2377
2378 // For the LHS, treat 'B' as the terminator that we want to sink
2379 // into the nested branch. The RHS always gets the top-most
2380 // terminator.
2381 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2382 }
2383
2384 // Create the block evaluating the LHS.
2385 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002386 CFGBlock *LHSBlock = createBlock(false);
2387 LHSBlock->setTerminator(B);
2388
Ted Kremeneka16436f2012-07-14 05:04:06 +00002389 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002390 CFGBlock *EntryLHSBlock = addStmt(LHS);
2391
2392 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002393 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002394
2395 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002396 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002397
2398 // Now link the LHSBlock with RHSBlock.
2399 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002400 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2401 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002402 } else {
2403 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002404 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2405 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002406 }
2407
Ted Kremenekb50e7162012-07-14 05:04:10 +00002408 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002409}
2410
2411CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2412 AddStmtChoice asc) {
2413 // && or ||
2414 if (B->isLogicalOp())
2415 return VisitLogicalOperator(B);
2416
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002417 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002418 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002419 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002420 addStmt(B->getRHS());
2421 return addStmt(B->getLHS());
2422 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002423
2424 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002425 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002426 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002427 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002428 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002429 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002430 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
Ted Kremenek7c58d352011-03-10 01:14:11 +00002433 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002434 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002435 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002436 }
2437
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002438 CFGBlock *RBlock = Visit(B->getRHS());
2439 CFGBlock *LBlock = Visit(B->getLHS());
2440 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2441 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2442 // return RBlock. Otherwise we'll incorrectly return NULL.
2443 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002444}
2445
Ted Kremeneke2499842012-04-12 20:03:44 +00002446CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002447 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002448 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002449 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002450 }
2451 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002452}
2453
Ted Kremenek93668002009-07-17 22:18:43 +00002454CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2455 // "break" is a control-flow statement. Thus we stop processing the current
2456 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002457 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002458 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002459
Ted Kremenek93668002009-07-17 22:18:43 +00002460 // Now create a new block that ends with the break statement.
2461 Block = createBlock(false);
2462 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002463
Ted Kremenek93668002009-07-17 22:18:43 +00002464 // If there is no target for the break, then we are looking at an incomplete
2465 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002466 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002467 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002468 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002469 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002470 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002471
Ted Kremenek9aae5132007-08-23 21:42:29 +00002472 return Block;
2473}
Mike Stump11289f42009-09-09 15:08:12 +00002474
Sebastian Redl31ad7542011-03-13 17:09:40 +00002475static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002476 QualType Ty = E->getType();
2477 if (Ty->isFunctionPointerType())
2478 Ty = Ty->getAs<PointerType>()->getPointeeType();
2479 else if (Ty->isBlockPointerType())
2480 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002481
Mike Stump04c68512010-01-21 15:20:48 +00002482 const FunctionType *FT = Ty->getAs<FunctionType>();
2483 if (FT) {
2484 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002485 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smitheaf11ad2018-05-03 03:58:32 +00002486 Proto->isNothrow())
Mike Stump04c68512010-01-21 15:20:48 +00002487 return false;
2488 }
2489 return true;
2490}
2491
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002492CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002493 // Compute the callee type.
2494 QualType calleeType = C->getCallee()->getType();
2495 if (calleeType == Context->BoundMemberTy) {
2496 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2497
2498 // We should only get a null bound type if processing a dependent
2499 // CFG. Recover by assuming nothing.
2500 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002501 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002502
John McCallc67067f2011-05-11 07:19:11 +00002503 // If this is a call to a no-return function, this stops the block here.
2504 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2505
Mike Stump04c68512010-01-21 15:20:48 +00002506 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002507
2508 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002509 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002510 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002511 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002512 }
2513
Jordan Rose5374c072013-08-19 16:27:28 +00002514 // If this is a call to a builtin function, it might not actually evaluate
2515 // its arguments. Don't add them to the CFG if this is the case.
2516 bool OmitArguments = false;
2517
Mike Stump92244b02010-01-19 22:00:14 +00002518 if (FunctionDecl *FD = C->getDirectCallee()) {
Artem Dergachev594b5412018-08-29 21:50:52 +00002519 // TODO: Support construction contexts for variadic function arguments.
2520 // These are a bit problematic and not very useful because passing
2521 // C++ objects as C-style variadic arguments doesn't work in general
2522 // (see [expr.call]).
2523 if (!FD->isVariadic())
2524 findConstructionContextsForArguments(C);
2525
Nico Weber758fbac2018-02-13 21:31:47 +00002526 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
Mike Stump8c5d7992009-07-25 21:26:53 +00002527 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002528 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002529 AddEHEdge = false;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00002530 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size ||
2531 FD->getBuiltinID() == Builtin::BI__builtin_dynamic_object_size)
Jordan Rose5374c072013-08-19 16:27:28 +00002532 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002533 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002534
Sebastian Redl31ad7542011-03-13 17:09:40 +00002535 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002536 AddEHEdge = false;
2537
Jordan Rose5374c072013-08-19 16:27:28 +00002538 if (OmitArguments) {
2539 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2540 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2541 autoCreateBlock();
2542 appendStmt(Block, C);
2543 return Visit(C->getCallee());
2544 }
2545
2546 if (!NoReturn && !AddEHEdge) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00002547 autoCreateBlock();
2548 appendCall(Block, C);
2549
2550 return VisitChildren(C);
Jordan Rose5374c072013-08-19 16:27:28 +00002551 }
Mike Stump11289f42009-09-09 15:08:12 +00002552
Mike Stump92244b02010-01-19 22:00:14 +00002553 if (Block) {
2554 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002555 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002556 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002557 }
Mike Stump11289f42009-09-09 15:08:12 +00002558
Chandler Carrutha70991b2011-09-13 09:13:49 +00002559 if (NoReturn)
2560 Block = createNoReturnBlock();
2561 else
2562 Block = createBlock();
2563
Artem Dergachev1527dec2018-03-12 23:12:40 +00002564 appendCall(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002565
Mike Stump04c68512010-01-21 15:20:48 +00002566 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002567 // Add exceptional edges.
2568 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002569 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002570 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002571 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002572 }
Mike Stump11289f42009-09-09 15:08:12 +00002573
Mike Stump8c5d7992009-07-25 21:26:53 +00002574 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002575}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002576
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002577CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2578 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002579 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002580 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002581 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002582 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002583
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002584 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002585 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002586 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002587 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002588 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002589 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Ted Kremenek21822592009-07-17 18:20:32 +00002591 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002592 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002593 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002594 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002595 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002596
Ted Kremenek21822592009-07-17 18:20:32 +00002597 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002598 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002599 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002600 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2601 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002602 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002603 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002604}
Mike Stump11289f42009-09-09 15:08:12 +00002605
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002606CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002607 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002608 addLocalScopeForStmt(C);
2609
Matthias Gehre09a134e2015-11-14 00:36:50 +00002610 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002611 // If the body ends with a ReturnStmt, the dtors will be added in
2612 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002613 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002614 }
2615
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002616 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002617
2618 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2619 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002620 // If we hit a segment of code just containing ';' (NullStmts), we can
2621 // get a null block back. In such cases, just use the LastBlock
2622 if (CFGBlock *newBlock = addStmt(*I))
2623 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002624
Ted Kremenekce499c22009-08-27 23:16:26 +00002625 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002626 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002627 }
Mike Stump92244b02010-01-19 22:00:14 +00002628
Ted Kremenek93668002009-07-17 22:18:43 +00002629 return LastBlock;
2630}
Mike Stump11289f42009-09-09 15:08:12 +00002631
John McCallc07a0c72011-02-17 10:25:35 +00002632CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002633 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002634 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002635 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002636
Ted Kremenek51d40b02009-07-17 18:15:54 +00002637 // Create the confluence block that will "merge" the results of the ternary
2638 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002639 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002640 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002641 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002642 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002643
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002644 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002645
Ted Kremenek51d40b02009-07-17 18:15:54 +00002646 // Create a block for the LHS expression if there is an LHS expression. A
2647 // GCC extension allows LHS to be NULL, causing the condition to be the
2648 // value that is returned instead.
2649 // e.g: x ?: y is shorthand for: x ? x : y;
2650 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002651 Block = nullptr;
2652 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002653 const Expr *trueExpr = C->getTrueExpr();
2654 if (trueExpr != opaqueValue) {
2655 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002656 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002657 return nullptr;
2658 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002659 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002660 else
2661 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002662
Ted Kremenek51d40b02009-07-17 18:15:54 +00002663 // Create the block for the RHS expression.
2664 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002665 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002666 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002667 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002668
Richard Smithf676e452012-07-24 21:02:14 +00002669 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2670 if (BinaryOperator *Cond =
2671 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2672 if (Cond->isLogicalOp())
2673 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2674
Ted Kremenek51d40b02009-07-17 18:15:54 +00002675 // Create the block that will contain the condition.
2676 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002677
Mike Stump773582d2009-07-23 23:25:26 +00002678 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002679 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002680 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2681 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002682 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002683 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002684
Ted Kremenekd8138012011-02-24 03:09:15 +00002685 if (opaqueValue) {
2686 // Run the condition expression if it's not trivially expressed in
2687 // terms of the opaque value (or if there is no opaque value).
2688 if (condExpr != opaqueValue)
2689 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002690
Ted Kremenekd8138012011-02-24 03:09:15 +00002691 // Before that, run the common subexpression if there was one.
2692 // At least one of this or the above will be run.
2693 return addStmt(BCO->getCommon());
2694 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002695
Ted Kremenekd8138012011-02-24 03:09:15 +00002696 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002697}
2698
Ted Kremenek93668002009-07-17 22:18:43 +00002699CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002700 // Check if the Decl is for an __label__. If so, elide it from the
2701 // CFG entirely.
2702 if (isa<LabelDecl>(*DS->decl_begin()))
2703 return Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00002704
Ted Kremenek3a601142011-05-24 20:41:31 +00002705 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002706 if (DS->isSingleDecl())
2707 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002708
Craig Topper25542942014-05-20 04:30:07 +00002709 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002710
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002711 // Build an individual DeclStmt for each decl.
2712 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2713 E = DS->decl_rend();
2714 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002715
Ted Kremenek93668002009-07-17 22:18:43 +00002716 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2717 // automatically freed with the CFG.
2718 DeclGroupRef DG(*I);
2719 Decl *D = *I;
George Karpenkovc1ac8082018-10-02 21:19:01 +00002720 DeclStmt *DSNew = new (Context) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002721 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002722
Ted Kremenek93668002009-07-17 22:18:43 +00002723 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002724 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002725 }
Mike Stump11289f42009-09-09 15:08:12 +00002726
2727 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002728}
Mike Stump11289f42009-09-09 15:08:12 +00002729
Ted Kremenek93668002009-07-17 22:18:43 +00002730/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002731/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002732CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002733 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002734 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002735
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002736 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002737 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2738 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002739 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002740 }
Mike Stump11289f42009-09-09 15:08:12 +00002741
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002742 bool HasTemporaries = false;
2743
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002744 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002745 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002746
2747 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2748 // For static variables, we need to create a branch to track
2749 // whether or not they are initialized.
2750 if (Block) {
2751 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002752 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002753 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002754 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002755 }
2756 blockAfterStaticInit = Succ;
2757 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002758
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002759 // Destructors of temporaries in initialization expression should be called
2760 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002761 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002762 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002763 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002764
Jordan Rose6d671cc2012-09-05 22:55:23 +00002765 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002766 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002767 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002768 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2769 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002770 }
2771 }
2772
2773 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002774 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002775
Artem Dergachev783a4572018-02-23 22:20:39 +00002776 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00002777 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Artem Dergachev783a4572018-02-23 22:20:39 +00002778 Init);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002779
Ted Kremenek213d0532012-03-22 05:57:43 +00002780 // Keep track of the last non-null block, as 'Block' can be nulled out
2781 // if the initializer expression is something like a 'while' in a
2782 // statement-expression.
2783 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002784
Ted Kremenek93668002009-07-17 22:18:43 +00002785 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002786 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002787 // For expression with temporaries go directly to subexpression to omit
2788 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002789 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2790 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2791 LastBlock = newBlock;
2792 }
2793 else {
2794 if (CFGBlock *newBlock = Visit(Init))
2795 LastBlock = newBlock;
2796 }
Ted Kremenek93668002009-07-17 22:18:43 +00002797 }
Mike Stump11289f42009-09-09 15:08:12 +00002798
Ted Kremenek93668002009-07-17 22:18:43 +00002799 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002800 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002801 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002802 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2803 LastBlock = newBlock;
2804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Maxim Ostapenkodebca452018-03-12 12:26:15 +00002806 maybeAddScopeBeginForVarDecl(Block, VD, DS);
2807
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002808 // Remove variable from local scope.
2809 if (ScopePos && VD == *ScopePos)
2810 ++ScopePos;
2811
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002812 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002813 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002814 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002815 Block = createBlock(false);
2816 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002817 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002818 addSuccessor(Block, B);
2819 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002820 }
2821
2822 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002823}
2824
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002825CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002826 // We may see an if statement in the middle of a basic block, or it may be the
2827 // first statement we are processing. In either case, we create a new basic
2828 // block. First, we create the blocks for the then...else statements, and
2829 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002830 // middle of a block, we stop processing that block. That block is then the
2831 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002832
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002833 // Save local scope position because in case of condition variable ScopePos
2834 // won't be restored when traversing AST.
2835 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2836
Richard Smitha547eb22016-07-14 00:11:03 +00002837 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002838 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002839 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002840
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002841 // Create local scope for possible condition variable.
2842 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002843 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002844 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002845
Matthias Gehre351c2182017-07-12 07:04:19 +00002846 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002847
Chris Lattner57540c52011-04-15 05:22:18 +00002848 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002849 // block.
2850 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002851 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002852 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002853 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002854 }
Mike Stump31feda52009-07-17 01:31:16 +00002855
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002856 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002857 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002858
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002859 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002860 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002861
Ted Kremenek9aae5132007-08-23 21:42:29 +00002862 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002863 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002864 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002865
2866 // If branch is not a compound statement create implicit scope
2867 // and add destructors.
2868 if (!isa<CompoundStmt>(Else))
2869 addLocalScopeAndDtors(Else);
2870
Ted Kremenek93668002009-07-17 22:18:43 +00002871 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002872
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002873 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2874 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002875 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002876 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002877 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002878 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002879 }
Mike Stump31feda52009-07-17 01:31:16 +00002880
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002881 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002882 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002883 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002884 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002885 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002886 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002887 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002888
2889 // If branch is not a compound statement create implicit scope
2890 // and add destructors.
2891 if (!isa<CompoundStmt>(Then))
2892 addLocalScopeAndDtors(Then);
2893
Ted Kremenek93668002009-07-17 22:18:43 +00002894 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002895
Ted Kremenek1b379512009-04-01 03:52:47 +00002896 if (!ThenBlock) {
2897 // We can reach here if the "then" body has all NullStmts.
2898 // Create an empty block so we can distinguish between true and false
2899 // branches in path-sensitive analyses.
2900 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002901 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002902 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002903 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002904 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002905 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002906 }
2907
Ted Kremenekb50e7162012-07-14 05:04:10 +00002908 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2909 // having these handle the actual control-flow jump. Note that
2910 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2911 // we resort to the old control-flow behavior. This special handling
2912 // removes infeasible paths from the control-flow graph by having the
2913 // control-flow transfer of '&&' or '||' go directly into the then/else
2914 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002915 BinaryOperator *Cond =
2916 I->getConditionVariable()
2917 ? nullptr
2918 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2919 CFGBlock *LastBlock;
2920 if (Cond && Cond->isLogicalOp())
2921 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2922 else {
2923 // Now create a new block containing the if statement.
2924 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002925
Richard Smith509bbd12017-01-13 22:16:41 +00002926 // Set the terminator of the new block to the If statement.
2927 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002928
Richard Smith509bbd12017-01-13 22:16:41 +00002929 // See if this is a known constant.
2930 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002931
Richard Smith509bbd12017-01-13 22:16:41 +00002932 // Add the successors. If we know that specific branches are
2933 // unreachable, inform addSuccessor() of that knowledge.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002934 addSuccessor(Block, ThenBlock, /* IsReachable = */ !KnownVal.isFalse());
2935 addSuccessor(Block, ElseBlock, /* IsReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002936
Richard Smith509bbd12017-01-13 22:16:41 +00002937 // Add the condition as the last statement in the new block. This may
2938 // create new blocks as the condition may contain control-flow. Any newly
2939 // created blocks will be pointed to be "Block".
2940 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002941
Richard Smith509bbd12017-01-13 22:16:41 +00002942 // If the IfStmt contains a condition variable, add it and its
2943 // initializer to the CFG.
2944 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2945 autoCreateBlock();
2946 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2947 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002948 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002949
Richard Smitha547eb22016-07-14 00:11:03 +00002950 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2951 if (Stmt *Init = I->getInit()) {
2952 autoCreateBlock();
2953 LastBlock = addStmt(Init);
2954 }
2955
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002956 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002957}
Mike Stump31feda52009-07-17 01:31:16 +00002958
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002959CFGBlock *CFGBuilder::VisitReturnStmt(Stmt *S) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002960 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002961 //
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002962 // NOTE: If a "return" or "co_return" appears in the middle of a block, this
2963 // means that the code afterwards is DEAD (unreachable). We still keep
2964 // a basic block for that code; a simple "mark-and-sweep" from the entry
2965 // block will be able to report such dead blocks.
2966 assert(isa<ReturnStmt>(S) || isa<CoreturnStmt>(S));
Ted Kremenek9aae5132007-08-23 21:42:29 +00002967
2968 // Create the new block.
2969 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002970
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002971 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), S);
Pavel Labath921e7652013-09-06 08:12:48 +00002972
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002973 if (auto *R = dyn_cast<ReturnStmt>(S))
2974 findConstructionContexts(
2975 ConstructionContextLayer::create(cfg->getBumpVectorContext(), R),
2976 R->getRetValue());
Artem Dergachev9ac2e112018-02-12 22:36:36 +00002977
Pavel Labath921e7652013-09-06 08:12:48 +00002978 // If the one of the destructors does not return, we already have the Exit
2979 // block as a successor.
2980 if (!Block->hasNoReturnElement())
2981 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002982
2983 // Add the return statement to the block. This may create new blocks if R
2984 // contains control-flow (short-circuit operations).
Brian Gesiaka87ecf62018-11-03 22:35:17 +00002985 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002986}
2987
Nico Weber699670e2017-08-23 15:33:16 +00002988CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2989 // SEHExceptStmt are treated like labels, so they are the first statement in a
2990 // block.
2991
2992 // Save local scope position because in case of exception variable ScopePos
2993 // won't be restored when traversing AST.
2994 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2995
2996 addStmt(ES->getBlock());
2997 CFGBlock *SEHExceptBlock = Block;
2998 if (!SEHExceptBlock)
2999 SEHExceptBlock = createBlock();
3000
3001 appendStmt(SEHExceptBlock, ES);
3002
3003 // Also add the SEHExceptBlock as a label, like with regular labels.
3004 SEHExceptBlock->setLabel(ES);
3005
3006 // Bail out if the CFG is bad.
3007 if (badCFG)
3008 return nullptr;
3009
3010 // We set Block to NULL to allow lazy creation of a new block (if necessary).
3011 Block = nullptr;
3012
3013 return SEHExceptBlock;
3014}
3015
3016CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
3017 return VisitCompoundStmt(FS->getBlock());
3018}
3019
3020CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
3021 // "__leave" is a control-flow statement. Thus we stop processing the current
3022 // block.
3023 if (badCFG)
3024 return nullptr;
3025
3026 // Now create a new block that ends with the __leave statement.
3027 Block = createBlock(false);
3028 Block->setTerminator(LS);
3029
3030 // If there is no target for the __leave, then we are looking at an incomplete
3031 // AST. This means that the CFG cannot be constructed.
3032 if (SEHLeaveJumpTarget.block) {
3033 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
3034 addSuccessor(Block, SEHLeaveJumpTarget.block);
3035 } else
3036 badCFG = true;
3037
3038 return Block;
3039}
3040
3041CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
3042 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
3043 // processing the current block.
3044 CFGBlock *SEHTrySuccessor = nullptr;
3045
3046 if (Block) {
3047 if (badCFG)
3048 return nullptr;
3049 SEHTrySuccessor = Block;
3050 } else SEHTrySuccessor = Succ;
3051
3052 // FIXME: Implement __finally support.
3053 if (Terminator->getFinallyHandler())
3054 return NYS();
3055
3056 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
3057
3058 // Create a new block that will contain the __try statement.
3059 CFGBlock *NewTryTerminatedBlock = createBlock(false);
3060
3061 // Add the terminator in the __try block.
3062 NewTryTerminatedBlock->setTerminator(Terminator);
3063
3064 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
3065 // The code after the try is the implicit successor if there's an __except.
3066 Succ = SEHTrySuccessor;
3067 Block = nullptr;
3068 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
3069 if (!ExceptBlock)
3070 return nullptr;
3071 // Add this block to the list of successors for the block with the try
3072 // statement.
3073 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
3074 }
3075 if (PrevSEHTryTerminatedBlock)
3076 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
3077 else
3078 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
3079
3080 // The code after the try is the implicit successor.
3081 Succ = SEHTrySuccessor;
3082
3083 // Save the current "__try" context.
3084 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
3085 NewTryTerminatedBlock);
3086 cfg->addTryDispatchBlock(TryTerminatedBlock);
3087
3088 // Save the current value for the __leave target.
3089 // All __leaves should go to the code following the __try
3090 // (FIXME: or if the __try has a __finally, to the __finally.)
3091 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
3092 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
3093
3094 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
3095 Block = nullptr;
3096 return addStmt(Terminator->getTryBlock());
3097}
3098
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003099CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003100 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00003101 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003102 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003103
Ted Kremenek93668002009-07-17 22:18:43 +00003104 if (!LabelBlock) // This can happen when the body is empty, i.e.
3105 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00003106
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003107 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
3108 "label already in map");
3109 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003110
3111 // Labels partition blocks, so this is the end of the basic block we were
3112 // processing (L is the block's label). Because this is label (and we have
3113 // already processed the substatement) there is no extra control-flow to worry
3114 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00003115 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003116 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003117 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003118
3119 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00003120 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003121
Ted Kremenek9aae5132007-08-23 21:42:29 +00003122 // This block is now the implicit successor of other blocks.
3123 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003124
Ted Kremenek9aae5132007-08-23 21:42:29 +00003125 return LabelBlock;
3126}
3127
Devin Coughlinb6029b72015-11-25 22:35:37 +00003128CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
3129 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3130 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
3131 if (Expr *CopyExpr = CI.getCopyExpr()) {
3132 CFGBlock *Tmp = Visit(CopyExpr);
3133 if (Tmp)
3134 LastBlock = Tmp;
3135 }
3136 }
3137 return LastBlock;
3138}
3139
Ted Kremenekda76a942012-04-12 20:34:52 +00003140CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
3141 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
3142 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
3143 et = E->capture_init_end(); it != et; ++it) {
3144 if (Expr *Init = *it) {
3145 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00003146 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00003147 LastBlock = Tmp;
3148 }
3149 }
3150 return LastBlock;
3151}
Fangrui Song6907ce22018-07-30 19:24:48 +00003152
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003153CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00003154 // Goto is a control-flow statement. Thus we stop processing the current
3155 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00003156
Ted Kremenek9aae5132007-08-23 21:42:29 +00003157 Block = createBlock(false);
3158 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00003159
3160 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003161 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00003162
Ted Kremenek9aae5132007-08-23 21:42:29 +00003163 if (I == LabelMap.end())
3164 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003165 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3166 else {
3167 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00003168 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003169 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003170 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00003171
Mike Stump31feda52009-07-17 01:31:16 +00003172 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003173}
3174
Jennifer Yub8fee672019-06-03 15:57:25 +00003175CFGBlock *CFGBuilder::VisitGCCAsmStmt(GCCAsmStmt *G, AddStmtChoice asc) {
3176 // Goto is a control-flow statement. Thus we stop processing the current
3177 // block and create a new one.
3178
3179 if (!G->isAsmGoto())
3180 return VisitStmt(G, asc);
3181
3182 if (Block) {
3183 Succ = Block;
3184 if (badCFG)
3185 return nullptr;
3186 }
3187 Block = createBlock();
3188 Block->setTerminator(G);
3189 // We will backpatch this block later for all the labels.
3190 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
3191 // Save "Succ" in BackpatchBlocks. In the backpatch processing, "Succ" is
3192 // used to avoid adding "Succ" again.
3193 BackpatchBlocks.push_back(JumpSource(Succ, ScopePos));
3194 return Block;
3195}
3196
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003197CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00003198 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003199
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003200 // Save local scope position because in case of condition variable ScopePos
3201 // won't be restored when traversing AST.
3202 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3203
3204 // Create local scope for init statement and possible condition variable.
3205 // Add destructor for init statement and condition variable.
3206 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003207 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003208 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003209 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
3210
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003211 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003212 addLocalScopeForVarDecl(VD);
3213 LocalScope::const_iterator ContinueScopePos = ScopePos;
3214
Matthias Gehre351c2182017-07-12 07:04:19 +00003215 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003216
Peter Szecsi999a25f2017-08-19 11:19:16 +00003217 addLoopExit(F);
3218
Mike Stump014b3ea2009-07-21 01:12:51 +00003219 // "for" is a control-flow statement. Thus we stop processing the current
3220 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003221 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003222 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003223 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003224 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003225 } else
3226 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003227
Ted Kremenek304a9532010-05-21 20:30:15 +00003228 // Save the current value for the break targets.
3229 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003230 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003231 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00003232
Craig Topper25542942014-05-20 04:30:07 +00003233 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003234
Ted Kremenek9aae5132007-08-23 21:42:29 +00003235 // Now create the loop body.
3236 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003237 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003238
Ted Kremenekb50e7162012-07-14 05:04:10 +00003239 // Save the current values for Block, Succ, continue and break targets.
3240 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3241 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003242
Ted Kremenekb50e7162012-07-14 05:04:10 +00003243 // Create an empty block to represent the transition block for looping back
3244 // to the head of the loop. If we have increment code, it will
3245 // go in this block as well.
3246 Block = Succ = TransitionBlock = createBlock(false);
3247 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003248
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003249 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00003250 // Generate increment code in its own basic block. This is the target of
3251 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00003252 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00003253 }
Mike Stump31feda52009-07-17 01:31:16 +00003254
Ted Kremenek902393b2009-04-28 00:51:56 +00003255 // Finish up the increment (or empty) block if it hasn't been already.
3256 if (Block) {
3257 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003258 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003259 return nullptr;
3260 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00003261 }
Mike Stump31feda52009-07-17 01:31:16 +00003262
Ted Kremenekb50e7162012-07-14 05:04:10 +00003263 // The starting block for the loop increment is the block that should
3264 // represent the 'loop target' for looping back to the start of the loop.
3265 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3266 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00003267
Ted Kremenekb50e7162012-07-14 05:04:10 +00003268 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003269 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00003270
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00003271 // If body is not a compound statement create implicit scope
3272 // and add destructors.
3273 if (!isa<CompoundStmt>(F->getBody()))
3274 addLocalScopeAndDtors(F->getBody());
3275
Mike Stump31feda52009-07-17 01:31:16 +00003276 // Now populate the body block, and in the process create new blocks as we
3277 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003278 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00003279
Ted Kremenekb50e7162012-07-14 05:04:10 +00003280 if (!BodyBlock) {
3281 // In the case of "for (...;...;...);" we can have a null BodyBlock.
3282 // Use the continue jump target as the proxy for the body.
3283 BodyBlock = ContinueJumpTarget.block;
3284 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003285 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003286 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003287 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003288
Ted Kremenekb50e7162012-07-14 05:04:10 +00003289 // Because of short-circuit evaluation, the condition of the loop can span
3290 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3291 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003292 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003293
Ted Kremenekb50e7162012-07-14 05:04:10 +00003294 do {
3295 Expr *C = F->getCond();
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003296 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003297
3298 // Specially handle logical operators, which have a slightly
3299 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003300 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00003301 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003302 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003303 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00003304 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
3305 break;
3306 }
3307
3308 // The default case when not handling logical operators.
3309 EntryConditionBlock = ExitConditionBlock = createBlock(false);
3310 ExitConditionBlock->setTerminator(F);
3311
3312 // See if this is a known constant.
3313 TryResult KnownVal(true);
3314
3315 if (C) {
3316 // Now add the actual condition to the condition block.
3317 // Because the condition itself may contain control-flow, new blocks may
3318 // be created. Thus we update "Succ" after adding the condition.
3319 Block = ExitConditionBlock;
3320 EntryConditionBlock = addStmt(C);
3321
3322 // If this block contains a condition variable, add both the condition
3323 // variable and initializer to the CFG.
3324 if (VarDecl *VD = F->getConditionVariable()) {
3325 if (Expr *Init = VD->getInit()) {
3326 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003327 const DeclStmt *DS = F->getConditionVariableDeclStmt();
3328 assert(DS->isSingleDecl());
3329 findConstructionContexts(
Artem Dergachev1f8cb3a2018-07-31 21:12:42 +00003330 ConstructionContextLayer::create(cfg->getBumpVectorContext(), DS),
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003331 Init);
3332 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003333 EntryConditionBlock = addStmt(Init);
3334 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003335 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003336 }
3337 }
3338
3339 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003340 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003341
3342 KnownVal = tryEvaluateBool(C);
3343 }
3344
3345 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003346 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003347 // Link up the condition block with the code that follows the loop. (the
3348 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003349 addSuccessor(ExitConditionBlock,
3350 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003351 } while (false);
3352
3353 // Link up the loop-back block to the entry condition block.
3354 addSuccessor(TransitionBlock, EntryConditionBlock);
Fangrui Song6907ce22018-07-30 19:24:48 +00003355
Ted Kremenekb50e7162012-07-14 05:04:10 +00003356 // The condition block is the implicit successor for any code above the loop.
3357 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003358
Ted Kremenek9aae5132007-08-23 21:42:29 +00003359 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00003360 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003361 if (Stmt *I = F->getInit()) {
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003362 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3363 ScopePos = LoopBeginScopePos;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003364 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00003365 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003366 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003367
3368 // There is no loop initialization. We are thus basically a while loop.
3369 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00003370 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003371 Succ = EntryConditionBlock;
3372 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003373}
3374
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003375CFGBlock *
3376CFGBuilder::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *MTE,
3377 AddStmtChoice asc) {
3378 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00003379 ConstructionContextLayer::create(cfg->getBumpVectorContext(), MTE),
Artem Dergachevf43ac4c2018-02-24 02:00:30 +00003380 MTE->getTemporary());
3381
3382 return VisitStmt(MTE, asc);
3383}
3384
Ted Kremenek5868ec62010-04-11 17:02:10 +00003385CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003386 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00003387 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003388 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00003389 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003390 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00003391}
3392
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003393CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00003394 // Objective-C fast enumeration 'for' statements:
3395 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
3396 //
3397 // for ( Type newVariable in collection_expression ) { statements }
3398 //
3399 // becomes:
3400 //
3401 // prologue:
3402 // 1. collection_expression
3403 // T. jump to loop_entry
3404 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003405 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00003406 // 1. ObjCForCollectionStmt [performs binding to newVariable]
3407 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
3408 // TB:
3409 // statements
3410 // T. jump to loop_entry
3411 // FB:
3412 // what comes after
3413 //
3414 // and
3415 //
3416 // Type existingItem;
3417 // for ( existingItem in expression ) { statements }
3418 //
3419 // becomes:
3420 //
Mike Stump31feda52009-07-17 01:31:16 +00003421 // the same with newVariable replaced with existingItem; the binding works
3422 // the same except that for one ObjCForCollectionStmt::getElement() returns
3423 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00003424
Craig Topper25542942014-05-20 04:30:07 +00003425 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003426
Ted Kremenek9d56e642008-11-11 17:10:00 +00003427 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003428 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003429 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00003430 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003431 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003432 } else
3433 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003434
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003435 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003436 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003437
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003438 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003439 ExitConditionBlock->setTerminator(S);
3440
3441 // The last statement in the block should be the ObjCForCollectionStmt, which
3442 // performs the actual binding to 'element' and determines if there are any
3443 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003444 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003445 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003446
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003447 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003448 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003449 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003450 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3451 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003452 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003453 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003454 return nullptr;
3455 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003456 }
Mike Stump31feda52009-07-17 01:31:16 +00003457
3458 // The condition block is the implicit successor for the loop body as well as
3459 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003460 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003461
Ted Kremenek9d56e642008-11-11 17:10:00 +00003462 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003463 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003464 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003465 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003466 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003467 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003468
Anna Zaks56b49752013-06-22 00:23:20 +00003469 // Add an intermediate block between the BodyBlock and the
3470 // EntryConditionBlock to represent the "loop back" transition, for looping
3471 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003472 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003473 Succ = LoopBackBlock = createBlock();
3474 LoopBackBlock->setLoopTarget(S);
Fangrui Song6907ce22018-07-30 19:24:48 +00003475
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003476 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003477 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003478
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003479 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003480
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003481 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003482 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003483 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003484 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003485 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003486 }
Mike Stump31feda52009-07-17 01:31:16 +00003487
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003488 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003489 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003490 }
Mike Stump31feda52009-07-17 01:31:16 +00003491
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003492 // Link up the condition block with the code that follows the loop.
3493 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003494 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003495
Ted Kremenek9d56e642008-11-11 17:10:00 +00003496 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003497 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003498 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003499}
3500
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003501CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3502 // Inline the body.
3503 return addStmt(S->getSubStmt());
3504 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3505}
3506
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003507CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003508 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003509
Ted Kremenek49805452009-05-02 01:49:13 +00003510 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003511 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003512
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003513 // The sync body starts its own basic block. This makes it a little easier
3514 // for diagnostic clients.
3515 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003516 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003517 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003518
Craig Topper25542942014-05-20 04:30:07 +00003519 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003520 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003521 }
Mike Stump31feda52009-07-17 01:31:16 +00003522
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003523 // Add the @synchronized to the CFG.
3524 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003525 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003526
Ted Kremenek49805452009-05-02 01:49:13 +00003527 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003528 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003529}
Mike Stump31feda52009-07-17 01:31:16 +00003530
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003531CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003532 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003533 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003534}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003535
John McCallfe96e0b2011-11-06 09:01:30 +00003536CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3537 autoCreateBlock();
3538
3539 // Add the PseudoObject as the last thing.
3540 appendStmt(Block, E);
3541
Fangrui Song6907ce22018-07-30 19:24:48 +00003542 CFGBlock *lastBlock = Block;
John McCallfe96e0b2011-11-06 09:01:30 +00003543
3544 // Before that, evaluate all of the semantics in order. In
3545 // CFG-land, that means appending them in reverse order.
3546 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3547 Expr *Semantic = E->getSemanticExpr(--i);
3548
3549 // If the semantic is an opaque value, we're being asked to bind
3550 // it to its source expression.
3551 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3552 Semantic = OVE->getSourceExpr();
3553
3554 if (CFGBlock *B = Visit(Semantic))
3555 lastBlock = B;
3556 }
3557
3558 return lastBlock;
3559}
3560
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003561CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003562 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003563
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003564 // Save local scope position because in case of condition variable ScopePos
3565 // won't be restored when traversing AST.
3566 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3567
3568 // Create local scope for possible condition variable.
3569 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003570 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003571 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003572 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003573 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003574 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003575 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003576
Mike Stump014b3ea2009-07-21 01:12:51 +00003577 // "while" is a control-flow statement. Thus we stop processing the current
3578 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003579 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003580 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003581 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003582 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003583 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003584 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003585 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003586 }
Mike Stump31feda52009-07-17 01:31:16 +00003587
Craig Topper25542942014-05-20 04:30:07 +00003588 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003589
Ted Kremenek9aae5132007-08-23 21:42:29 +00003590 // Process the loop body.
3591 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003592 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003593
Ted Kremenekb50e7162012-07-14 05:04:10 +00003594 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003595 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3596 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003597 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003598
Mike Stump31feda52009-07-17 01:31:16 +00003599 // Create an empty block to represent the transition block for looping back
3600 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003601 Succ = TransitionBlock = createBlock(false);
3602 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003603 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003604
Ted Kremenek9aae5132007-08-23 21:42:29 +00003605 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003606 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003607
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003608 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003609 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003610
3611 // If body is not a compound statement create implicit scope
3612 // and add destructors.
3613 if (!isa<CompoundStmt>(W->getBody()))
3614 addLocalScopeAndDtors(W->getBody());
3615
Ted Kremenek9aae5132007-08-23 21:42:29 +00003616 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003617 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003618
Ted Kremeneke9610502007-08-30 18:39:40 +00003619 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003620 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003621 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003622 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003623 }
3624
3625 // Because of short-circuit evaluation, the condition of the loop can span
3626 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3627 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003628 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003629
3630 do {
3631 Expr *C = W->getCond();
3632
3633 // Specially handle logical operators, which have a slightly
3634 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003635 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003636 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003637 std::tie(EntryConditionBlock, ExitConditionBlock) =
3638 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003639 break;
3640 }
3641
3642 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003643 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003644 ExitConditionBlock->setTerminator(W);
3645
3646 // Now add the actual condition to the condition block.
3647 // Because the condition itself may contain control-flow, new blocks may
3648 // be created. Thus we update "Succ" after adding the condition.
3649 Block = ExitConditionBlock;
3650 Block = EntryConditionBlock = addStmt(C);
3651
3652 // If this block contains a condition variable, add both the condition
3653 // variable and initializer to the CFG.
3654 if (VarDecl *VD = W->getConditionVariable()) {
3655 if (Expr *Init = VD->getInit()) {
3656 autoCreateBlock();
Artem Dergachevab9b78b2018-04-19 23:30:15 +00003657 const DeclStmt *DS = W->getConditionVariableDeclStmt();
3658 assert(DS->isSingleDecl());
3659 findConstructionContexts(
3660 ConstructionContextLayer::create(cfg->getBumpVectorContext(),
3661 const_cast<DeclStmt *>(DS)),
3662 Init);
3663 appendStmt(Block, DS);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003664 EntryConditionBlock = addStmt(Init);
3665 assert(Block == EntryConditionBlock);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00003666 maybeAddScopeBeginForVarDecl(EntryConditionBlock, VD, C);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003667 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003668 }
Mike Stump31feda52009-07-17 01:31:16 +00003669
Ted Kremenekb50e7162012-07-14 05:04:10 +00003670 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003671 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003672
3673 // See if this is a known constant.
3674 const TryResult& KnownVal = tryEvaluateBool(C);
3675
Ted Kremenek30754282009-07-24 04:47:11 +00003676 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003677 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003678 // Link up the condition block with the code that follows the loop. (the
3679 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003680 addSuccessor(ExitConditionBlock,
3681 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003682 } while(false);
3683
3684 // Link up the loop-back block to the entry condition block.
3685 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003686
3687 // There can be no more statements in the condition block since we loop back
3688 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003689 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003690
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003691 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003692 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003693 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003694}
Mike Stump11289f42009-09-09 15:08:12 +00003695
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003696CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003697 // FIXME: For now we pretend that @catch and the code it contains does not
3698 // exit.
3699 return Block;
3700}
Mike Stump31feda52009-07-17 01:31:16 +00003701
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003702CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003703 // FIXME: This isn't complete. We basically treat @throw like a return
3704 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003705
Ted Kremenek0868eea2009-09-24 18:45:41 +00003706 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003707 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003708 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003709
Ted Kremenek93041ba2008-12-09 20:20:09 +00003710 // Create the new block.
3711 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003712
Ted Kremenek93041ba2008-12-09 20:20:09 +00003713 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003714 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003715
3716 // Add the statement to the block. This may create new blocks if S contains
3717 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003718 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003719}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003720
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003721CFGBlock *CFGBuilder::VisitObjCMessageExpr(ObjCMessageExpr *ME,
3722 AddStmtChoice asc) {
3723 findConstructionContextsForArguments(ME);
3724
3725 autoCreateBlock();
Artem Dergacheve1f30622018-07-31 19:46:14 +00003726 appendObjCMessage(Block, ME);
Artem Dergachevbd880fe2018-07-31 19:39:37 +00003727
3728 return VisitChildren(ME);
3729}
3730
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003731CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003732 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003733 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003734 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003735
3736 // Create the new block.
3737 Block = createBlock(false);
3738
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003739 if (TryTerminatedBlock)
3740 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003741 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003742 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003743 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003744 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003745
3746 // Add the statement to the block. This may create new blocks if S contains
3747 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003748 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003749}
3750
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003751CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003752 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003753
Peter Szecsi999a25f2017-08-19 11:19:16 +00003754 addLoopExit(D);
3755
Mike Stump8d50b6a2009-07-21 01:27:50 +00003756 // "do...while" is a control-flow statement. Thus we stop processing the
3757 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003758 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003759 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003760 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003761 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003762 } else
3763 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003764
3765 // Because of short-circuit evaluation, the condition of the loop can span
3766 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3767 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003768 CFGBlock *ExitConditionBlock = createBlock(false);
3769 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003770
Ted Kremenek81e14852007-08-27 19:46:09 +00003771 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003772 ExitConditionBlock->setTerminator(D);
3773
3774 // Now add the actual condition to the condition block. Because the condition
3775 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003776 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003777 Block = ExitConditionBlock;
3778 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003779 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003780 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003781 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003782 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003783 }
Mike Stump31feda52009-07-17 01:31:16 +00003784
Ted Kremeneka1523a32008-02-27 07:20:00 +00003785 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003786 Succ = EntryConditionBlock;
3787
Mike Stump773582d2009-07-23 23:25:26 +00003788 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003789 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003790
Ted Kremenek9aae5132007-08-23 21:42:29 +00003791 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003792 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003793 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003794 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003795
Ted Kremenek9aae5132007-08-23 21:42:29 +00003796 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003797 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3798 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3799 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003800
Ted Kremenek9aae5132007-08-23 21:42:29 +00003801 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003802 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003803
Ted Kremenek9aae5132007-08-23 21:42:29 +00003804 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003805 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003806
Ted Kremenek9aae5132007-08-23 21:42:29 +00003807 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003808 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003809
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003810 // If body is not a compound statement create implicit scope
3811 // and add destructors.
3812 if (!isa<CompoundStmt>(D->getBody()))
3813 addLocalScopeAndDtors(D->getBody());
3814
Ted Kremenek9aae5132007-08-23 21:42:29 +00003815 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003816 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003817
Ted Kremeneke9610502007-08-30 18:39:40 +00003818 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003819 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003820 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003821 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003822 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003823 }
Mike Stump31feda52009-07-17 01:31:16 +00003824
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003825 // Add an intermediate block between the BodyBlock and the
3826 // ExitConditionBlock to represent the "loop back" transition. Create an
3827 // empty block to represent the transition block for looping back to the
3828 // head of the loop.
3829 // FIXME: Can we do this more efficiently without adding another block?
3830 Block = nullptr;
3831 Succ = BodyBlock;
3832 CFGBlock *LoopBackBlock = createBlock();
3833 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003834
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003835 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003836 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003837 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003838 else
Craig Topper25542942014-05-20 04:30:07 +00003839 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003840 }
Mike Stump31feda52009-07-17 01:31:16 +00003841
Ted Kremenek30754282009-07-24 04:47:11 +00003842 // Link up the condition block with the code that follows the loop.
3843 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003844 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003845
3846 // There can be no more statements in the body block(s) since we loop back to
3847 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003848 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003849
Ted Kremenek9aae5132007-08-23 21:42:29 +00003850 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003851 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003852 return BodyBlock;
3853}
3854
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003855CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003856 // "continue" is a control-flow statement. Thus we stop processing the
3857 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003858 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003859 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003860
Ted Kremenek9aae5132007-08-23 21:42:29 +00003861 // Now create a new block that ends with the continue statement.
3862 Block = createBlock(false);
3863 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003864
Ted Kremenek9aae5132007-08-23 21:42:29 +00003865 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003866 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003867 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003868 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003869 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003870 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003871 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003872
Ted Kremenek9aae5132007-08-23 21:42:29 +00003873 return Block;
3874}
Mike Stump11289f42009-09-09 15:08:12 +00003875
Peter Collingbournee190dee2011-03-11 19:24:49 +00003876CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3877 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003878 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003879 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003880 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003881 }
Mike Stump11289f42009-09-09 15:08:12 +00003882
Ted Kremenek93668002009-07-17 22:18:43 +00003883 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003884 CFGBlock *lastBlock = Block;
Fangrui Song6907ce22018-07-30 19:24:48 +00003885
Ted Kremenek93668002009-07-17 22:18:43 +00003886 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003887 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003888 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003889 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003890 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003891 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003892}
Mike Stump11289f42009-09-09 15:08:12 +00003893
Ted Kremenek93668002009-07-17 22:18:43 +00003894/// VisitStmtExpr - Utility method to handle (nested) statement
3895/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003896CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003897 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003898 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003899 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003900 }
Ted Kremenek93668002009-07-17 22:18:43 +00003901 return VisitCompoundStmt(SE->getSubStmt());
3902}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003903
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003904CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003905 // "switch" is a control-flow statement. Thus we stop processing the current
3906 // block.
Craig Topper25542942014-05-20 04:30:07 +00003907 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003908
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003909 // Save local scope position because in case of condition variable ScopePos
3910 // won't be restored when traversing AST.
3911 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3912
Richard Smitha547eb22016-07-14 00:11:03 +00003913 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003914 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003915 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003916
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003917 // Create local scope for possible condition variable.
3918 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003919 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003920 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003921
Matthias Gehre351c2182017-07-12 07:04:19 +00003922 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003923
Ted Kremenek9aae5132007-08-23 21:42:29 +00003924 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003925 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003926 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003927 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003928 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003929
3930 // Save the current "switch" context.
3931 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003932 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003933 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003934
Mike Stump31feda52009-07-17 01:31:16 +00003935 // Set the "default" case to be the block after the switch statement. If the
3936 // switch statement contains a "default:", this value will be overwritten with
3937 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003938 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003939
Ted Kremenek9aae5132007-08-23 21:42:29 +00003940 // Create a new block that will contain the switch statement.
3941 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003942
Ted Kremenek9aae5132007-08-23 21:42:29 +00003943 // Now process the switch body. The code after the switch is the implicit
3944 // successor.
3945 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003946 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003947
3948 // When visiting the body, the case statements should automatically get linked
3949 // up to the switch. We also don't keep a pointer to the body, since all
3950 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003951 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003952 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003953
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003954 // For pruning unreachable case statements, save the current state
3955 // for tracking the condition value.
3956 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3957 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003958
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003959 // Determine if the switch condition can be explicitly evaluated.
3960 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003961 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003962 bool b = tryEvaluate(Terminator->getCond(), result);
3963 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003964 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003965
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003966 // If body is not a compound statement create implicit scope
3967 // and add destructors.
3968 if (!isa<CompoundStmt>(Terminator->getBody()))
3969 addLocalScopeAndDtors(Terminator->getBody());
3970
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003971 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003972 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003973 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003974 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003975 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003976
Mike Stump31feda52009-07-17 01:31:16 +00003977 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003978 // following the switch body. Moreover, take into account if all the
3979 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003980 //
3981 // Note: We add a successor to a switch that is considered covered yet has no
3982 // case statements if the enumeration has no enumerators.
3983 bool SwitchAlwaysHasSuccessor = false;
3984 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3985 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3986 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003987 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3988 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003989
Ted Kremenek81e14852007-08-27 19:46:09 +00003990 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003991 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003992 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003993 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003994
Richard Smitha547eb22016-07-14 00:11:03 +00003995 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003996 // SwitchStmt and the condition variable initialization to the CFG.
3997 if (VarDecl *VD = Terminator->getConditionVariable()) {
3998 if (Expr *Init = VD->getInit()) {
3999 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00004000 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004001 LastBlock = addStmt(Init);
Maxim Ostapenkodebca452018-03-12 12:26:15 +00004002 maybeAddScopeBeginForVarDecl(LastBlock, VD, Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00004003 }
4004 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00004005
Richard Smitha547eb22016-07-14 00:11:03 +00004006 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
4007 if (Stmt *Init = Terminator->getInit()) {
4008 autoCreateBlock();
4009 LastBlock = addStmt(Init);
4010 }
4011
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004012 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004013}
Fangrui Song6907ce22018-07-30 19:24:48 +00004014
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004015static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00004016 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004017 const CaseStmt *CS,
4018 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00004019 if (!switchCond)
4020 return true;
4021
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004022 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00004023
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004024 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00004025 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004026 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00004027 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00004028 const llvm::APSInt &condInt = switchCond->Val.getInt();
Fangrui Song6907ce22018-07-30 19:24:48 +00004029
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004030 if (condInt == lhsInt) {
4031 addCase = true;
4032 switchExclusivelyCovered = true;
4033 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00004034 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004035 if (const Expr *RHS = CS->getRHS()) {
4036 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00004037 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00004038 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004039 addCase = true;
4040 switchExclusivelyCovered = true;
4041 }
4042 }
4043 }
4044 }
4045 else
4046 addCase = true;
4047 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004048 return addCase;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004049}
Ted Kremenek9aae5132007-08-23 21:42:29 +00004050
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004051CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00004052 // CaseStmts are essentially labels, so they are the first statement in a
4053 // block.
Craig Topper25542942014-05-20 04:30:07 +00004054 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00004055
Ted Kremenek60fa6572010-08-04 23:54:30 +00004056 if (Stmt *Sub = CS->getSubStmt()) {
4057 // For deeply nested chains of CaseStmts, instead of doing a recursion
4058 // (which can blow out the stack), manually unroll and create blocks
4059 // along the way.
4060 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004061 CFGBlock *currentBlock = createBlock(false);
4062 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00004063
Ted Kremenek60fa6572010-08-04 23:54:30 +00004064 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004065 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004066 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004067 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00004068
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004069 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00004070 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004071 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00004072 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004073
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00004074 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00004075 CS = cast<CaseStmt>(Sub);
4076 Sub = CS->getSubStmt();
4077 }
4078
4079 addStmt(Sub);
4080 }
Mike Stump11289f42009-09-09 15:08:12 +00004081
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004082 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00004083 if (!CaseBlock)
4084 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004085
4086 // Cases statements partition blocks, so this is the top of the basic block we
4087 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00004088 CaseBlock->setLabel(CS);
4089
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004090 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004091 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004092
4093 // Add this block to the list of successors for the block with the switch
4094 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00004095 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004096 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00004097 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004098 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00004099
Ted Kremenek9aae5132007-08-23 21:42:29 +00004100 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004101 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004102
Ted Kremenek60fa6572010-08-04 23:54:30 +00004103 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004104 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00004105 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004106 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00004107 // This block is now the implicit successor of other blocks.
4108 Succ = CaseBlock;
4109 }
Mike Stump31feda52009-07-17 01:31:16 +00004110
Ted Kremenek60fa6572010-08-04 23:54:30 +00004111 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004112}
Mike Stump31feda52009-07-17 01:31:16 +00004113
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004114CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00004115 if (Terminator->getSubStmt())
4116 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00004117
Ted Kremenek654c78f2008-02-13 22:05:39 +00004118 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00004119
4120 if (!DefaultCaseBlock)
4121 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004122
4123 // Default statements partition blocks, so this is the top of the basic block
4124 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004125 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00004126
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004127 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004128 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00004129
Mike Stump31feda52009-07-17 01:31:16 +00004130 // Unlike case statements, we don't add the default block to the successors
4131 // for the switch statement immediately. This is done when we finish
4132 // processing the switch statement. This allows for the default case
4133 // (including a fall-through to the code after the switch statement) to always
4134 // be the last successor of a switch-terminated block.
4135
Ted Kremenek654c78f2008-02-13 22:05:39 +00004136 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004137 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004138
Ted Kremenek654c78f2008-02-13 22:05:39 +00004139 // This block is now the implicit successor of other blocks.
4140 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00004141
4142 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00004143}
Ted Kremenek9aae5132007-08-23 21:42:29 +00004144
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004145CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
4146 // "try"/"catch" is a control-flow statement. Thus we stop processing the
4147 // current block.
Craig Topper25542942014-05-20 04:30:07 +00004148 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004149
4150 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004151 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004152 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004153 TrySuccessor = Block;
4154 } else TrySuccessor = Succ;
4155
Mike Stump0bdba6c2010-01-20 01:15:34 +00004156 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004157
4158 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00004159 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004160 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00004161 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004162
Mike Stump0bdba6c2010-01-20 01:15:34 +00004163 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004164 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
4165 // The code after the try is the implicit successor.
4166 Succ = TrySuccessor;
4167 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00004168 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00004169 HasCatchAll = true;
4170 }
Craig Topper25542942014-05-20 04:30:07 +00004171 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004172 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00004173 if (!CatchBlock)
4174 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004175 // Add this block to the list of successors for the block with the try
4176 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004177 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004178 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00004179 if (!HasCatchAll) {
4180 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004181 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00004182 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004183 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00004184 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004185
4186 // The code after the try is the implicit successor.
4187 Succ = TrySuccessor;
4188
Mike Stump845384a2010-01-20 01:30:58 +00004189 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00004190 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
4191 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00004192
Ted Kremenek1362b8b2010-01-19 20:46:35 +00004193 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00004194 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004195 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004196}
4197
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004198CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004199 // CXXCatchStmt are treated like labels, so they are the first statement in a
4200 // block.
4201
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004202 // Save local scope position because in case of exception variable ScopePos
4203 // won't be restored when traversing AST.
4204 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4205
4206 // Create local scope for possible exception variable.
4207 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004208 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004209 LocalScope::const_iterator BeginScopePos = ScopePos;
4210 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00004211 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00004212 }
4213
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004214 if (CS->getHandlerBlock())
4215 addStmt(CS->getHandlerBlock());
4216
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004217 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004218 if (!CatchBlock)
4219 CatchBlock = createBlock();
Fangrui Song6907ce22018-07-30 19:24:48 +00004220
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004221 // CXXCatchStmt is more than just a label. They have semantic meaning
4222 // as well, as they implicitly "initialize" the catch variable. Add
4223 // it to the CFG as a CFGElement so that the control-flow of these
4224 // semantics gets captured.
4225 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004226
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004227 // Also add the CXXCatchStmt as a label, to mirror handling of regular
4228 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004229 CatchBlock->setLabel(CS);
4230
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00004231 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004232 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004233 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004234
4235 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00004236 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004237
4238 return CatchBlock;
4239}
4240
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004241CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00004242 // C++0x for-range statements are specified as [stmt.ranged]:
4243 //
4244 // {
4245 // auto && __range = range-init;
4246 // for ( auto __begin = begin-expr,
4247 // __end = end-expr;
4248 // __begin != __end;
4249 // ++__begin ) {
4250 // for-range-declaration = *__begin;
4251 // statement
4252 // }
4253 // }
4254
4255 // Save local scope position before the addition of the implicit variables.
4256 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
4257
4258 // Create local scopes and destructors for range, begin and end variables.
4259 if (Stmt *Range = S->getRangeStmt())
4260 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00004261 if (Stmt *Begin = S->getBeginStmt())
4262 addLocalScopeForStmt(Begin);
4263 if (Stmt *End = S->getEndStmt())
4264 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00004265 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00004266
4267 LocalScope::const_iterator ContinueScopePos = ScopePos;
4268
4269 // "for" is a control-flow statement. Thus we stop processing the current
4270 // block.
Craig Topper25542942014-05-20 04:30:07 +00004271 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004272 if (Block) {
4273 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004274 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004275 LoopSuccessor = Block;
4276 } else
4277 LoopSuccessor = Succ;
4278
4279 // Save the current value for the break targets.
4280 // All breaks should go to the code following the loop.
4281 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
4282 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
4283
4284 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004285 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00004286 ConditionBlock->setTerminator(S);
4287
4288 // Now add the actual condition to the condition block.
4289 if (Expr *C = S->getCond()) {
4290 Block = ConditionBlock;
4291 CFGBlock *BeginConditionBlock = addStmt(C);
4292 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004293 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004294 assert(BeginConditionBlock == ConditionBlock &&
4295 "condition block in for-range was unexpectedly complex");
4296 (void)BeginConditionBlock;
4297 }
4298
4299 // The condition block is the implicit successor for the loop body as well as
4300 // any code above the loop.
4301 Succ = ConditionBlock;
4302
4303 // See if this is a known constant.
4304 TryResult KnownVal(true);
4305
4306 if (S->getCond())
4307 KnownVal = tryEvaluateBool(S->getCond());
4308
4309 // Now create the loop body.
4310 {
4311 assert(S->getBody());
4312
4313 // Save the current values for Block, Succ, and continue targets.
4314 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
4315 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
4316
4317 // Generate increment code in its own basic block. This is the target of
4318 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00004319 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004320 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00004321 if (badCFG)
4322 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004323 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
4324
4325 // The starting block for the loop increment is the block that should
4326 // represent the 'loop target' for looping back to the start of the loop.
4327 ContinueJumpTarget.block->setLoopTarget(S);
4328
4329 // Finish up the increment block and prepare to start the loop body.
4330 assert(Block);
4331 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004332 return nullptr;
4333 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00004334
4335 // Add implicit scope and dtors for loop variable.
4336 addLocalScopeAndDtors(S->getLoopVarStmt());
4337
4338 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004339 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00004340 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004341 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00004342 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00004343 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004344 return nullptr;
4345
Richard Smith02e85f32011-04-14 22:09:26 +00004346 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00004347 addSuccessor(ConditionBlock,
4348 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00004349 }
4350
4351 // Link up the condition block with the code that follows the loop (the
4352 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00004353 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00004354
4355 // Add the initialization statements.
4356 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00004357 addStmt(S->getBeginStmt());
4358 addStmt(S->getEndStmt());
Richard Smith8baa5002018-09-28 18:44:09 +00004359 CFGBlock *Head = addStmt(S->getRangeStmt());
4360 if (S->getInit())
4361 Head = addStmt(S->getInit());
4362 return Head;
Richard Smith02e85f32011-04-14 22:09:26 +00004363}
4364
John McCall5d413782010-12-06 08:20:24 +00004365CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004366 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004367 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004368 // If adding implicit destructors visit the full expression for adding
4369 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004370 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00004371 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004372
4373 // Full expression has to be added as CFGStmt so it will be sequenced
4374 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004375 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004376 }
4377 return Visit(E->getSubExpr(), asc);
4378}
4379
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004380CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
4381 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004382 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004383 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004384 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004385
Artem Dergachev783a4572018-02-23 22:20:39 +00004386 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004387 ConstructionContextLayer::create(cfg->getBumpVectorContext(), E),
Artem Dergachev783a4572018-02-23 22:20:39 +00004388 E->getSubExpr());
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004389
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004390 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004391 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004392 }
4393 return Visit(E->getSubExpr(), asc);
4394}
4395
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004396CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
4397 AddStmtChoice asc) {
Artem Dergachevbd880fe2018-07-31 19:39:37 +00004398 // If the constructor takes objects as arguments by value, we need to properly
4399 // construct these objects. Construction contexts we find here aren't for the
4400 // constructor C, they're for its arguments only.
4401 findConstructionContextsForArguments(C);
4402
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004403 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00004404 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004405
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004406 return VisitChildren(C);
4407}
4408
Jordan Rosec9176072014-01-13 17:59:19 +00004409CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
4410 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00004411 autoCreateBlock();
4412 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00004413
Artem Dergachev783a4572018-02-23 22:20:39 +00004414 findConstructionContexts(
Artem Dergachev40684812018-02-27 20:03:35 +00004415 ConstructionContextLayer::create(cfg->getBumpVectorContext(), NE),
Artem Dergachev783a4572018-02-23 22:20:39 +00004416 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
Artem Dergachev41ffb302018-02-08 22:58:15 +00004417
Jordan Rosec9176072014-01-13 17:59:19 +00004418 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00004419 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004420
Jordan Rosec9176072014-01-13 17:59:19 +00004421 if (BuildOpts.AddCXXNewAllocator)
4422 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004423
Richard Smithb9fb1212019-05-06 03:47:15 +00004424 if (NE->isArray() && *NE->getArraySize())
4425 Block = Visit(*NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00004426
Jordan Rosec9176072014-01-13 17:59:19 +00004427 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
4428 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00004429 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004430
Jordan Rosec9176072014-01-13 17:59:19 +00004431 return Block;
4432}
Jordan Rosed2f40792013-09-03 17:00:57 +00004433
4434CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
4435 AddStmtChoice asc) {
4436 autoCreateBlock();
4437 appendStmt(Block, DE);
4438 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00004439 if (!DTy.isNull()) {
4440 DTy = DTy.getNonReferenceType();
4441 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4442 if (RD) {
4443 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4444 appendDeleteDtor(Block, RD, DE);
4445 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004446 }
4447
4448 return VisitChildren(DE);
4449}
4450
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004451CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4452 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004453 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004454 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004455 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004456 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004457 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004458 }
4459 return Visit(E->getSubExpr(), asc);
4460}
4461
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004462CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4463 AddStmtChoice asc) {
Artem Dergachevc531d542018-08-14 21:10:46 +00004464 // If the constructor takes objects as arguments by value, we need to properly
4465 // construct these objects. Construction contexts we find here aren't for the
4466 // constructor C, they're for its arguments only.
4467 findConstructionContextsForArguments(C);
4468
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004469 autoCreateBlock();
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004470 appendConstructor(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004471 return VisitChildren(C);
4472}
4473
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004474CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4475 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004476 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004477 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004478 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004479 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004480 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004481}
4482
Bill Wendling8003edc2018-11-09 00:41:36 +00004483CFGBlock *CFGBuilder::VisitConstantExpr(ConstantExpr *E, AddStmtChoice asc) {
4484 return Visit(E->getSubExpr(), AddStmtChoice());
4485}
4486
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004487CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004488 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004489 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004490
Ted Kremenekeda180e22007-08-28 19:26:49 +00004491 if (!IBlock) {
4492 IBlock = createBlock(false);
4493 cfg->setIndirectGotoBlock(IBlock);
4494 }
Mike Stump31feda52009-07-17 01:31:16 +00004495
Ted Kremenekeda180e22007-08-28 19:26:49 +00004496 // IndirectGoto is a control-flow statement. Thus we stop processing the
4497 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004498 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004499 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004500
Ted Kremenekeda180e22007-08-28 19:26:49 +00004501 Block = createBlock(false);
4502 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004503 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004504 return addStmt(I->getTarget());
4505}
4506
Manuel Klimekb5616c92014-08-07 10:42:17 +00004507CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4508 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004509 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4510
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004511tryAgain:
4512 if (!E) {
4513 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004514 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004515 }
4516 switch (E->getStmtClass()) {
4517 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004518 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004519
4520 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004521 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4522 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004523
4524 case Stmt::CXXBindTemporaryExprClass:
4525 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004526 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004527
John McCallc07a0c72011-02-17 10:25:35 +00004528 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004529 case Stmt::ConditionalOperatorClass:
4530 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004531 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004532
4533 case Stmt::ImplicitCastExprClass:
4534 // For implicit cast we want BindToTemporary to be passed further.
4535 E = cast<CastExpr>(E)->getSubExpr();
4536 goto tryAgain;
4537
Manuel Klimekb0042c42014-07-30 08:34:42 +00004538 case Stmt::CXXFunctionalCastExprClass:
4539 // For functional cast we want BindToTemporary to be passed further.
4540 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4541 goto tryAgain;
4542
Bill Wendling8003edc2018-11-09 00:41:36 +00004543 case Stmt::ConstantExprClass:
4544 E = cast<ConstantExpr>(E)->getSubExpr();
4545 goto tryAgain;
4546
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004547 case Stmt::ParenExprClass:
4548 E = cast<ParenExpr>(E)->getSubExpr();
4549 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004550
Manuel Klimekb0042c42014-07-30 08:34:42 +00004551 case Stmt::MaterializeTemporaryExprClass: {
4552 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4553 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4554 SmallVector<const Expr *, 2> CommaLHSs;
4555 SmallVector<SubobjectAdjustment, 2> Adjustments;
4556 // Find the expression whose lifetime needs to be extended.
4557 E = const_cast<Expr *>(
4558 cast<MaterializeTemporaryExpr>(E)
4559 ->GetTemporaryExpr()
4560 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4561 // Visit the skipped comma operator left-hand sides for other temporaries.
4562 for (const Expr *CommaLHS : CommaLHSs) {
4563 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004564 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004565 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004566 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004567 }
Richard Smith4137af22014-07-27 05:12:49 +00004568
4569 case Stmt::BlockExprClass:
4570 // Don't recurse into blocks; their subexpressions don't get evaluated
4571 // here.
4572 return Block;
4573
4574 case Stmt::LambdaExprClass: {
4575 // For lambda expressions, only recurse into the capture initializers,
4576 // and not the body.
4577 auto *LE = cast<LambdaExpr>(E);
4578 CFGBlock *B = Block;
4579 for (Expr *Init : LE->capture_inits()) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00004580 if (Init) {
4581 if (CFGBlock *R = VisitForTemporaryDtors(
4582 Init, /*BindToTemporary=*/false, Context))
4583 B = R;
4584 }
Richard Smith4137af22014-07-27 05:12:49 +00004585 }
4586 return B;
4587 }
4588
4589 case Stmt::CXXDefaultArgExprClass:
4590 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4591 goto tryAgain;
4592
4593 case Stmt::CXXDefaultInitExprClass:
4594 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4595 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004596 }
4597}
4598
Manuel Klimekb5616c92014-08-07 10:42:17 +00004599CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4600 TempDtorContext &Context) {
4601 if (isa<LambdaExpr>(E)) {
4602 // Do not visit the children of lambdas; they have their own CFGs.
4603 return Block;
4604 }
4605
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004606 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004607 // order that they will appear in the CFG. Because the CFG is built
4608 // bottom-up, this means we visit them in their natural order, which
4609 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004610 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004611 for (Stmt *Child : E->children())
4612 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004613 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004614 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004615
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004616 return B;
4617}
4618
Manuel Klimekb5616c92014-08-07 10:42:17 +00004619CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4620 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004621 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004622 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004623 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4624 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4625 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004626
Manuel Klimekedf925b92014-08-07 18:44:19 +00004627 // We do not know at CFG-construction time whether the right-hand-side was
4628 // executed, thus we add a branch node that depends on the temporary
4629 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004630 TempDtorContext RHSContext(
4631 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004632 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004633 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004634
Manuel Klimekb5616c92014-08-07 10:42:17 +00004635 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004636 }
4637
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004638 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004639 // For assignment operator (=) LHS expression is visited
4640 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004641 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4642 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004643 return LHSBlock ? LHSBlock : RHSBlock;
4644 }
4645
4646 // For any other binary operator RHS expression is visited before
4647 // LHS expression (order of children). For destructors visit them in reverse
4648 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004649 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4650 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004651 return RHSBlock ? RHSBlock : LHSBlock;
4652}
4653
4654CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004655 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004656 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004657 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004658 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004659 // If lifetime of temporary is not prolonged (by assigning to constant
4660 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004661
Chandler Carruthad747252011-09-13 06:09:01 +00004662 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004663
Richard Trieu95a192a2015-05-28 00:14:02 +00004664 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004665 // If the destructor is marked as a no-return destructor, we need to
4666 // create a new block for the destructor which does not have as a
4667 // successor anything built thus far. Control won't flow out of this
4668 // block.
4669 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004670 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004671 } else if (Context.needsTempDtorBranch()) {
4672 // If we need to introduce a branch, we add a new block that we will hook
4673 // up to a decision block later.
4674 if (B) Succ = B;
4675 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004676 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004677 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004678 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004679 if (Context.needsTempDtorBranch()) {
4680 Context.setDecisionPoint(Succ, E);
4681 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004682 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004683
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004684 B = Block;
4685 }
4686 return B;
4687}
4688
Manuel Klimekb5616c92014-08-07 10:42:17 +00004689void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4690 CFGBlock *FalseSucc) {
4691 if (!Context.TerminatorExpr) {
4692 // If no temporary was found, we do not need to insert a decision point.
4693 return;
4694 }
4695 assert(Context.TerminatorExpr);
4696 CFGBlock *Decision = createBlock(false);
Artem Dergachev4e530322019-05-24 01:34:22 +00004697 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr,
4698 CFGTerminator::TemporaryDtorsBranch));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004699 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004700 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004701 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004702 Block = Decision;
4703}
4704
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004705CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004706 AbstractConditionalOperator *E, bool BindToTemporary,
4707 TempDtorContext &Context) {
4708 VisitForTemporaryDtors(E->getCond(), false, Context);
4709 CFGBlock *ConditionBlock = Block;
4710 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004711 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004712 TryResult NegatedVal = ConditionVal;
4713 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004714
Manuel Klimekdeb02622014-08-08 07:37:13 +00004715 TempDtorContext TrueContext(
4716 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004717 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004718 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004719
Manuel Klimekb5616c92014-08-07 10:42:17 +00004720 Block = ConditionBlock;
4721 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004722 TempDtorContext FalseContext(
4723 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004724 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004725
Manuel Klimekb5616c92014-08-07 10:42:17 +00004726 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004727 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004728 } else if (TrueContext.TerminatorExpr) {
4729 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004730 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004731 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004732 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004733 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004734 return Block;
4735}
4736
Alexey Bataevc2c21ef2019-07-11 14:54:17 +00004737CFGBlock *CFGBuilder::VisitOMPExecutableDirective(OMPExecutableDirective *D,
4738 AddStmtChoice asc) {
4739 if (asc.alwaysAdd(*this, D)) {
4740 autoCreateBlock();
4741 appendStmt(Block, D);
4742 }
4743
4744 // Iterate over all used expression in clauses.
4745 CFGBlock *B = Block;
4746
4747 // Reverse the elements to process them in natural order. Iterators are not
4748 // bidirectional, so we need to create temp vector.
Alexey Bataev655cb4a2019-07-16 14:51:46 +00004749 SmallVector<Stmt *, 8> Used(
4750 OMPExecutableDirective::used_clauses_children(D->clauses()));
4751 for (Stmt *S : llvm::reverse(Used)) {
Alexey Bataevc2c21ef2019-07-11 14:54:17 +00004752 assert(S && "Expected non-null used-in-clause child.");
4753 if (CFGBlock *R = Visit(S))
4754 B = R;
4755 }
4756 // Visit associated structured block if any.
4757 if (!D->isStandaloneDirective())
4758 if (Stmt *S = D->getStructuredBlock()) {
4759 if (!isa<CompoundStmt>(S))
4760 addLocalScopeAndDtors(S);
4761 if (CFGBlock *R = addStmt(S))
4762 B = R;
4763 }
4764
4765 return B;
4766}
4767
Mike Stump31feda52009-07-17 01:31:16 +00004768/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4769/// no successors or predecessors. If this is the first block created in the
4770/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004771CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004772 bool first_block = begin() == end();
4773
4774 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004775 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004776 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004777 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004778
4779 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004780 if (first_block)
4781 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004782
4783 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004784 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004785}
4786
David Blaikiee90195c2014-08-29 18:53:26 +00004787/// buildCFG - Constructs a CFG from an AST.
4788std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4789 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004790 CFGBuilder Builder(C, BO);
4791 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004792}
4793
Artem Dergachevab7747b2019-04-30 03:01:02 +00004794bool CFG::isLinear() const {
4795 // Quick path: if we only have the ENTRY block, the EXIT block, and some code
4796 // in between, then we have no room for control flow.
4797 if (size() <= 3)
4798 return true;
4799
4800 // Traverse the CFG until we find a branch.
4801 // TODO: While this should still be very fast,
4802 // maybe we should cache the answer.
4803 llvm::SmallPtrSet<const CFGBlock *, 4> Visited;
4804 const CFGBlock *B = Entry;
4805 while (B != Exit) {
4806 auto IteratorAndFlag = Visited.insert(B);
4807 if (!IteratorAndFlag.second) {
4808 // We looped back to a block that we've already visited. Not linear.
4809 return false;
4810 }
4811
4812 // Iterate over reachable successors.
4813 const CFGBlock *FirstReachableB = nullptr;
4814 for (const CFGBlock::AdjacentBlock &AB : B->succs()) {
4815 if (!AB.isReachable())
4816 continue;
4817
4818 if (FirstReachableB == nullptr) {
4819 FirstReachableB = &*AB;
4820 } else {
4821 // We've encountered a branch. It's not a linear CFG.
4822 return false;
4823 }
4824 }
4825
4826 if (!FirstReachableB) {
4827 // We reached a dead end. EXIT is unreachable. This is linear enough.
4828 return true;
4829 }
4830
4831 // There's only one way to move forward. Proceed.
4832 B = FirstReachableB;
4833 }
4834
4835 // We reached EXIT and found no branches.
4836 return true;
4837}
4838
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004839const CXXDestructorDecl *
4840CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004841 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004842 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004843 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004844 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004845 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004846 case CFGElement::Statement:
4847 case CFGElement::Constructor:
Artem Dergachev1527dec2018-03-12 23:12:40 +00004848 case CFGElement::CXXRecordTypedCall:
Maxim Ostapenkodebca452018-03-12 12:26:15 +00004849 case CFGElement::ScopeBegin:
4850 case CFGElement::ScopeEnd:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004851 llvm_unreachable("getDestructorDecl should only be used with "
4852 "ImplicitDtors");
4853 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004854 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004855 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004856
4857 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4858 //
4859 // Lifetime-extending constructs are handled here. This works for a single
4860 // temporary in an initializer expression.
4861 if (ty->isReferenceType()) {
4862 if (const Expr *Init = var->getInit()) {
Artem Dergacheva25809f2018-06-04 18:56:25 +00004863 ty = getReferenceInitTemporaryType(Init);
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004864 }
4865 }
4866
Ted Kremeneke7d78882012-03-19 23:48:41 +00004867 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004868 ty = arrayType->getElementType();
4869 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004870 const RecordType *recordType = ty->getAs<RecordType>();
4871 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004872 cast<CXXRecordDecl>(recordType->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004873 return classDecl->getDestructor();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004874 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004875 case CFGElement::DeleteDtor: {
4876 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4877 QualType DTy = DE->getDestroyedType();
4878 DTy = DTy.getNonReferenceType();
4879 const CXXRecordDecl *classDecl =
4880 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4881 return classDecl->getDestructor();
4882 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004883 case CFGElement::TemporaryDtor: {
4884 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004885 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004886 const CXXTemporary *temp = bindExpr->getTemporary();
4887 return temp->getDestructor();
4888 }
4889 case CFGElement::BaseDtor:
4890 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004891 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004892 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004893 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004894 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004895}
4896
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004897bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004898 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4899 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004900 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004901}
4902
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004903//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004904// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004905//===----------------------------------------------------------------------===//
4906
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004907CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004908 : ReachableBlock(IsReachable ? B : nullptr),
4909 UnreachableBlock(!IsReachable ? B : nullptr,
4910 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004911
4912CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004913 : ReachableBlock(B),
4914 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4915 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004916
4917void CFGBlock::addSuccessor(AdjacentBlock Succ,
4918 BumpVectorContext &C) {
4919 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004920 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004921
4922 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004923 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004924
4925 Succs.push_back(Succ, C);
4926}
4927
Ted Kremenekb0371852010-09-09 00:06:04 +00004928bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004929 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004930 if (F.IgnoreNullPredecessors && !From)
4931 return true;
4932
4933 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004934 // If the 'To' has no label or is labeled but the label isn't a
4935 // CaseStmt then filter this edge.
4936 if (const SwitchStmt *S =
Artem Dergachev4e530322019-05-24 01:34:22 +00004937 dyn_cast_or_null<SwitchStmt>(From->getTerminatorStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004938 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004939 const Stmt *L = To->getLabel();
4940 if (!L || !isa<CaseStmt>(L))
4941 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004942 }
4943 }
4944 }
4945
4946 return false;
4947}
4948
4949//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004950// CFG pretty printing
4951//===----------------------------------------------------------------------===//
4952
Ted Kremenek7e776b12007-08-22 18:22:34 +00004953namespace {
4954
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004955class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004956 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4957 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4958
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004959 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004960 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004961 signed currentBlock = 0;
4962 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004963 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004964
Eugene Zelenko38c70522017-12-07 21:55:09 +00004965public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004966 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004967 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004968 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4969 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004970 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Fangrui Song6907ce22018-07-30 19:24:48 +00004971 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004972 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4973 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004974 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004975 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004976
Ted Kremenek96a7a592011-03-01 03:15:10 +00004977 switch (stmt->getStmtClass()) {
4978 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004979 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4980 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004981 case Stmt::IfStmtClass: {
4982 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4983 if (var)
4984 DeclMap[var] = P;
4985 break;
4986 }
4987 case Stmt::ForStmtClass: {
4988 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4989 if (var)
4990 DeclMap[var] = P;
4991 break;
4992 }
4993 case Stmt::WhileStmtClass: {
4994 const VarDecl *var =
4995 cast<WhileStmt>(stmt)->getConditionVariable();
4996 if (var)
4997 DeclMap[var] = P;
4998 break;
4999 }
5000 case Stmt::SwitchStmtClass: {
5001 const VarDecl *var =
5002 cast<SwitchStmt>(stmt)->getConditionVariable();
5003 if (var)
5004 DeclMap[var] = P;
5005 break;
5006 }
5007 case Stmt::CXXCatchStmtClass: {
5008 const VarDecl *var =
5009 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
5010 if (var)
5011 DeclMap[var] = P;
5012 break;
5013 }
5014 default:
5015 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005016 }
5017 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005018 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00005019 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005020 }
Mike Stump31feda52009-07-17 01:31:16 +00005021
Eugene Zelenko38c70522017-12-07 21:55:09 +00005022 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00005023
Chris Lattnerc61089a2009-06-30 01:26:17 +00005024 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00005025 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00005026 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00005027
Craig Topperb45acb82014-03-14 06:02:07 +00005028 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005029 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005030
5031 if (I == StmtMap.end())
5032 return false;
Mike Stump31feda52009-07-17 01:31:16 +00005033
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00005034 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00005035 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005036 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00005037 }
Mike Stump31feda52009-07-17 01:31:16 +00005038
Ted Kremenek60983dc2010-01-19 20:52:05 +00005039 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005040 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005041 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005042
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005043 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005044 DeclMapTy::iterator I = DeclMap.find(D);
5045
5046 if (I == DeclMap.end())
5047 return false;
5048
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00005049 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00005050 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005051 return false;
5052 }
5053
5054 OS << "[B" << I->second.first << "." << I->second.second << "]";
5055 return true;
5056 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005057};
5058
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00005059class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00005060 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005061 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005062 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00005063 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00005064
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005065public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005066 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00005067 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00005068 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00005069 this->Policy.IncludeNewlines = false;
5070 }
Mike Stump31feda52009-07-17 01:31:16 +00005071
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005072 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005073 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005074 if (Stmt *C = I->getCond())
5075 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00005076 }
Mike Stump31feda52009-07-17 01:31:16 +00005077
Ted Kremenek9aae5132007-08-23 21:42:29 +00005078 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005079 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00005080 Terminator->printPretty(OS, Helper, Policy);
5081 }
5082
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00005083 void VisitDeclStmt(DeclStmt *DS) {
5084 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
5085 OS << "static init " << VD->getName();
5086 }
5087
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005088 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005089 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00005090 if (F->getInit())
5091 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00005092 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005093 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005094 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00005095 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00005096 if (F->getInc())
5097 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00005098 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00005099 }
Mike Stump31feda52009-07-17 01:31:16 +00005100
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005101 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005102 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005103 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005104 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00005105 }
Mike Stump31feda52009-07-17 01:31:16 +00005106
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005107 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00005108 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005109 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00005110 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00005111 }
Mike Stump31feda52009-07-17 01:31:16 +00005112
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005113 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00005114 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00005115 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00005116 }
Mike Stump31feda52009-07-17 01:31:16 +00005117
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005118 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005119 OS << "try ...";
5120 }
5121
Nico Weber699670e2017-08-23 15:33:16 +00005122 void VisitSEHTryStmt(SEHTryStmt *CS) {
5123 OS << "__try ...";
5124 }
5125
John McCallc07a0c72011-02-17 10:25:35 +00005126 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00005127 if (Stmt *Cond = C->getCond())
5128 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005129 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005130 }
Mike Stump31feda52009-07-17 01:31:16 +00005131
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005132 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00005133 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005134 if (Stmt *Cond = C->getCond())
5135 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00005136 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00005137 }
Mike Stump31feda52009-07-17 01:31:16 +00005138
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005139 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005140 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005141 if (Stmt *T = I->getTarget())
5142 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005143 }
Mike Stump31feda52009-07-17 01:31:16 +00005144
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005145 void VisitBinaryOperator(BinaryOperator* B) {
5146 if (!B->isLogicalOp()) {
5147 VisitExpr(B);
5148 return;
5149 }
Mike Stump31feda52009-07-17 01:31:16 +00005150
Richard Trieuddd01ce2014-06-09 22:53:25 +00005151 if (B->getLHS())
5152 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005153
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005154 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00005155 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00005156 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005157 return;
John McCalle3027922010-08-25 11:45:40 +00005158 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00005159 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005160 return;
5161 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005162 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00005163 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00005164 }
Mike Stump31feda52009-07-17 01:31:16 +00005165
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005166 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00005167 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00005168 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00005169
5170public:
5171 void print(CFGTerminator T) {
Artem Dergachev4e530322019-05-24 01:34:22 +00005172 switch (T.getKind()) {
5173 case CFGTerminator::StmtBranch:
5174 Visit(T.getStmt());
5175 break;
5176 case CFGTerminator::TemporaryDtorsBranch:
Ted Kremenekfcc14172014-03-08 02:22:29 +00005177 OS << "(Temp Dtor) ";
Artem Dergachev4e530322019-05-24 01:34:22 +00005178 Visit(T.getStmt());
5179 break;
Artem Dergachev192a7472019-05-24 23:37:08 +00005180 case CFGTerminator::VirtualBaseBranch:
5181 OS << "(See if most derived ctor has already initialized vbases)";
5182 break;
Artem Dergachev4e530322019-05-24 01:34:22 +00005183 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00005184 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00005185};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005186
5187} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00005188
Artem Dergachev5a281bb2018-02-10 02:18:04 +00005189static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
5190 const CXXCtorInitializer *I) {
5191 if (I->isBaseInitializer())
5192 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
5193 else if (I->isDelegatingInitializer())
5194 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
5195 else
5196 OS << I->getAnyMember()->getName();
5197 OS << "(";
5198 if (Expr *IE = I->getInit())
5199 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
5200 OS << ")";
5201
5202 if (I->isBaseInitializer())
5203 OS << " (Base initializer)";
5204 else if (I->isDelegatingInitializer())
5205 OS << " (Delegating initializer)";
5206 else
5207 OS << " (Member initializer)";
5208}
5209
Artem Dergachev1527dec2018-03-12 23:12:40 +00005210static void print_construction_context(raw_ostream &OS,
5211 StmtPrinterHelper &Helper,
5212 const ConstructionContext *CC) {
Artem Dergachevff267df2018-06-28 00:04:54 +00005213 SmallVector<const Stmt *, 3> Stmts;
Artem Dergachev1527dec2018-03-12 23:12:40 +00005214 switch (CC->getKind()) {
Artem Dergachev922455f2018-03-22 22:02:38 +00005215 case ConstructionContext::SimpleConstructorInitializerKind: {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005216 OS << ", ";
Artem Dergachev922455f2018-03-22 22:02:38 +00005217 const auto *SICC = cast<SimpleConstructorInitializerConstructionContext>(CC);
5218 print_initializer(OS, Helper, SICC->getCXXCtorInitializer());
Artem Dergacheva657a322018-07-31 20:45:53 +00005219 return;
Artem Dergachev922455f2018-03-22 22:02:38 +00005220 }
5221 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: {
5222 OS << ", ";
5223 const auto *CICC =
5224 cast<CXX17ElidedCopyConstructorInitializerConstructionContext>(CC);
5225 print_initializer(OS, Helper, CICC->getCXXCtorInitializer());
Artem Dergachevff267df2018-06-28 00:04:54 +00005226 Stmts.push_back(CICC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005227 break;
5228 }
5229 case ConstructionContext::SimpleVariableKind: {
Artem Dergachev317291e2018-03-22 21:37:39 +00005230 const auto *SDSCC = cast<SimpleVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005231 Stmts.push_back(SDSCC->getDeclStmt());
Artem Dergachev317291e2018-03-22 21:37:39 +00005232 break;
5233 }
5234 case ConstructionContext::CXX17ElidedCopyVariableKind: {
5235 const auto *CDSCC = cast<CXX17ElidedCopyVariableConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005236 Stmts.push_back(CDSCC->getDeclStmt());
5237 Stmts.push_back(CDSCC->getCXXBindTemporaryExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005238 break;
5239 }
5240 case ConstructionContext::NewAllocatedObjectKind: {
5241 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005242 Stmts.push_back(NECC->getCXXNewExpr());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005243 break;
5244 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005245 case ConstructionContext::SimpleReturnedValueKind: {
5246 const auto *RSCC = cast<SimpleReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005247 Stmts.push_back(RSCC->getReturnStmt());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005248 break;
5249 }
Artem Dergachev317291e2018-03-22 21:37:39 +00005250 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: {
5251 const auto *RSCC =
5252 cast<CXX17ElidedCopyReturnedValueConstructionContext>(CC);
Artem Dergachevff267df2018-06-28 00:04:54 +00005253 Stmts.push_back(RSCC->getReturnStmt());
5254 Stmts.push_back(RSCC->getCXXBindTemporaryExpr());
Artem Dergachev317291e2018-03-22 21:37:39 +00005255 break;
5256 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005257 case ConstructionContext::SimpleTemporaryObjectKind: {
5258 const auto *TOCC = cast<SimpleTemporaryObjectConstructionContext>(CC);
5259 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5260 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5261 break;
5262 }
5263 case ConstructionContext::ElidedTemporaryObjectKind: {
5264 const auto *TOCC = cast<ElidedTemporaryObjectConstructionContext>(CC);
5265 Stmts.push_back(TOCC->getCXXBindTemporaryExpr());
5266 Stmts.push_back(TOCC->getMaterializedTemporaryExpr());
5267 Stmts.push_back(TOCC->getConstructorAfterElision());
Artem Dergachev1527dec2018-03-12 23:12:40 +00005268 break;
5269 }
Artem Dergacheva657a322018-07-31 20:45:53 +00005270 case ConstructionContext::ArgumentKind: {
5271 const auto *ACC = cast<ArgumentConstructionContext>(CC);
5272 if (const Stmt *BTE = ACC->getCXXBindTemporaryExpr()) {
5273 OS << ", ";
5274 Helper.handledStmt(const_cast<Stmt *>(BTE), OS);
5275 }
5276 OS << ", ";
5277 Helper.handledStmt(const_cast<Expr *>(ACC->getCallLikeExpr()), OS);
5278 OS << "+" << ACC->getIndex();
5279 return;
5280 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005281 }
Artem Dergachevff267df2018-06-28 00:04:54 +00005282 for (auto I: Stmts)
5283 if (I) {
5284 OS << ", ";
5285 Helper.handledStmt(const_cast<Stmt *>(I), OS);
5286 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005287}
5288
Aaron Ballmanff924b02013-11-18 20:11:50 +00005289static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00005290 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00005291 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
5292 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00005293 assert(S != nullptr && "Expecting non-null Stmt");
5294
Aaron Ballmanff924b02013-11-18 20:11:50 +00005295 // special printing for statement-expressions.
5296 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
5297 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00005298
Benjamin Kramer5733e352015-07-18 17:09:36 +00005299 auto Children = Sub->children();
5300 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005301 OS << "({ ... ; ";
5302 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
5303 OS << " })\n";
5304 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00005305 }
5306 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00005307 // special printing for comma expressions.
5308 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
5309 if (B->getOpcode() == BO_Comma) {
5310 OS << "... , ";
5311 Helper.handledStmt(B->getRHS(),OS);
5312 OS << '\n';
5313 return;
5314 }
5315 }
5316 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00005317
Artem Dergachev1527dec2018-03-12 23:12:40 +00005318 if (auto VTC = E.getAs<CFGCXXRecordTypedCall>()) {
5319 if (isa<CXXOperatorCallExpr>(S))
5320 OS << " (OperatorCall)";
5321 OS << " (CXXRecordTypedCall";
5322 print_construction_context(OS, Helper, VTC->getConstructionContext());
5323 OS << ")";
5324 } else if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005325 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005326 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00005327 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005328 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005329 OS << " (CXXConstructExpr";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005330 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
Artem Dergachev1527dec2018-03-12 23:12:40 +00005331 print_construction_context(OS, Helper, CE->getConstructionContext());
Artem Dergachev41ffb302018-02-08 22:58:15 +00005332 }
Artem Dergachev1527dec2018-03-12 23:12:40 +00005333 OS << ", " << CCE->getType().getAsString() << ")";
Artem Dergachev41ffb302018-02-08 22:58:15 +00005334 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00005335 OS << " (" << CE->getStmtClassName() << ", "
5336 << CE->getCastKindName()
5337 << ", " << CE->getType().getAsString()
5338 << ")";
5339 }
Mike Stump31feda52009-07-17 01:31:16 +00005340
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005341 // Expressions need a newline.
5342 if (isa<Expr>(S))
5343 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005344 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00005345 print_initializer(OS, Helper, IE->getInitializer());
5346 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00005347 } else if (Optional<CFGAutomaticObjDtor> DE =
5348 E.getAs<CFGAutomaticObjDtor>()) {
5349 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00005350 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005351
Artem Dergacheva25809f2018-06-04 18:56:25 +00005352 ASTContext &ACtx = VD->getASTContext();
5353 QualType T = VD->getType();
5354 if (T->isReferenceType())
5355 T = getReferenceInitTemporaryType(VD->getInit(), nullptr);
5356 if (const ArrayType *AT = ACtx.getAsArrayType(T))
5357 T = ACtx.getBaseElementType(AT);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005358
5359 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
5360 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00005361 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
5362 const VarDecl *VD = DE->getVarDecl();
5363 Helper.handleDecl(VD, OS);
5364
5365 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00005366 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
5367 const Stmt *LoopStmt = LE->getLoopStmt();
5368 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Maxim Ostapenkodebca452018-03-12 12:26:15 +00005369 } else if (Optional<CFGScopeBegin> SB = E.getAs<CFGScopeBegin>()) {
5370 OS << "CFGScopeBegin(";
5371 if (const VarDecl *VD = SB->getVarDecl())
5372 OS << VD->getQualifiedNameAsString();
5373 OS << ")\n";
5374 } else if (Optional<CFGScopeEnd> SE = E.getAs<CFGScopeEnd>()) {
5375 OS << "CFGScopeEnd(";
5376 if (const VarDecl *VD = SE->getVarDecl())
5377 OS << VD->getQualifiedNameAsString();
5378 OS << ")\n";
Jordan Rosec9176072014-01-13 17:59:19 +00005379 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
5380 OS << "CFGNewAllocator(";
5381 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
5382 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
5383 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00005384 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
5385 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
5386 if (!RD)
5387 return;
5388 CXXDeleteExpr *DelExpr =
5389 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00005390 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00005391 OS << "->~" << RD->getName().str() << "()";
5392 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005393 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
5394 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005395 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005396 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005397 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
5398 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00005399 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00005400 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00005401 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00005402 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00005403 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
5404 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00005405 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005406 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00005407 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00005408 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00005409}
Mike Stump31feda52009-07-17 01:31:16 +00005410
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005411static void print_block(raw_ostream &OS, const CFG* cfg,
5412 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00005413 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005414 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00005415 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00005416
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005417 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005418 if (ShowColors)
5419 OS.changeColor(raw_ostream::YELLOW, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00005420
Ted Kremenek72be32a2011-12-22 23:33:52 +00005421 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00005422
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005423 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005424 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005425 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005426 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005427 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00005428 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00005429 else if (B.hasNoReturnElement())
5430 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005431 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00005432 OS << "]\n";
Fangrui Song6907ce22018-07-30 19:24:48 +00005433
Ted Kremenek72be32a2011-12-22 23:33:52 +00005434 if (ShowColors)
5435 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00005436
Ted Kremenek71eca012007-08-29 23:20:49 +00005437 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005438 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005439 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005440 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005441
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005442 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005443 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005444 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005445 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00005446 if (C->getLHS())
5447 C->getLHS()->printPretty(OS, &Helper,
5448 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005449 if (C->getRHS()) {
5450 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00005451 C->getRHS()->printPretty(OS, &Helper,
5452 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00005453 }
Mike Stump92244b02010-01-19 22:00:14 +00005454 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00005455 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00005456 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005457 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00005458 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00005459 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00005460 0);
5461 else
5462 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005463 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00005464 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
5465 OS << "__except (";
5466 ES->getFilterExpr()->printPretty(OS, &Helper,
5467 PrintingPolicy(Helper.getLangOpts()), 0);
5468 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00005469 } else
David Blaikie83d382b2011-09-23 05:06:16 +00005470 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00005471
Ted Kremenek71eca012007-08-29 23:20:49 +00005472 OS << ":\n";
5473 }
Mike Stump31feda52009-07-17 01:31:16 +00005474
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005475 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005476 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00005477
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005478 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
5479 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00005480 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005481 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005482 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00005483
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005484 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00005485
Aaron Ballmanff924b02013-11-18 20:11:50 +00005486 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00005487
Ted Kremenek72be32a2011-12-22 23:33:52 +00005488 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005489 }
Mike Stump31feda52009-07-17 01:31:16 +00005490
Ted Kremenek71eca012007-08-29 23:20:49 +00005491 // Print the terminator of this block.
Artem Dergachev4e530322019-05-24 01:34:22 +00005492 if (B.getTerminator().isValid()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00005493 if (ShowColors)
5494 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00005495
Ted Kremenek72be32a2011-12-22 23:33:52 +00005496 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00005497
Aaron Ballmanff924b02013-11-18 20:11:50 +00005498 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00005499
Aaron Ballmanff924b02013-11-18 20:11:50 +00005500 PrintingPolicy PP(Helper.getLangOpts());
5501 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00005502 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005503 OS << '\n';
Fangrui Song6907ce22018-07-30 19:24:48 +00005504
Ted Kremenek72be32a2011-12-22 23:33:52 +00005505 if (ShowColors)
5506 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005507 }
Mike Stump31feda52009-07-17 01:31:16 +00005508
Ted Kremenek71eca012007-08-29 23:20:49 +00005509 if (print_edges) {
5510 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005511 if (!B.pred_empty()) {
Rui Ueyama4d41c332019-08-02 07:22:34 +00005512 const raw_ostream::Colors Color = raw_ostream::BLUE;
Ted Kremenek72be32a2011-12-22 23:33:52 +00005513 if (ShowColors)
5514 OS.changeColor(Color);
5515 OS << " Preds " ;
5516 if (ShowColors)
5517 OS.resetColor();
5518 OS << '(' << B.pred_size() << "):";
5519 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00005520
Ted Kremenek72be32a2011-12-22 23:33:52 +00005521 if (ShowColors)
5522 OS.changeColor(Color);
Fangrui Song6907ce22018-07-30 19:24:48 +00005523
Ted Kremenek72be32a2011-12-22 23:33:52 +00005524 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
5525 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005526 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005527 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00005528
Ted Kremenek4b6fee62014-02-27 00:24:00 +00005529 CFGBlock *B = *I;
5530 bool Reachable = true;
5531 if (!B) {
5532 Reachable = false;
5533 B = I->getPossiblyUnreachableBlock();
5534 }
5535
5536 OS << " B" << B->getBlockID();
5537 if (!Reachable)
5538 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00005539 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005540
Ted Kremenek72be32a2011-12-22 23:33:52 +00005541 if (ShowColors)
5542 OS.resetColor();
5543
5544 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00005545 }
Mike Stump31feda52009-07-17 01:31:16 +00005546
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005547 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005548 if (!B.succ_empty()) {
Rui Ueyama4d41c332019-08-02 07:22:34 +00005549 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
Ted Kremenek72be32a2011-12-22 23:33:52 +00005550 if (ShowColors)
5551 OS.changeColor(Color);
5552 OS << " Succs ";
5553 if (ShowColors)
5554 OS.resetColor();
5555 OS << '(' << B.succ_size() << "):";
5556 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005557
Ted Kremenek72be32a2011-12-22 23:33:52 +00005558 if (ShowColors)
5559 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00005560
Ted Kremenek72be32a2011-12-22 23:33:52 +00005561 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
5562 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00005563 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00005564 OS << "\n ";
5565
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005566 CFGBlock *B = *I;
5567
5568 bool Reachable = true;
5569 if (!B) {
5570 Reachable = false;
5571 B = I->getPossiblyUnreachableBlock();
5572 }
5573
5574 if (B) {
5575 OS << " B" << B->getBlockID();
5576 if (!Reachable)
5577 OS << "(Unreachable)";
5578 }
5579 else {
5580 OS << " NULL";
5581 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00005582 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00005583
Ted Kremenek72be32a2011-12-22 23:33:52 +00005584 if (ShowColors)
5585 OS.resetColor();
5586 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005587 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00005588 }
Mike Stump31feda52009-07-17 01:31:16 +00005589}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005590
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005591/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005592void CFG::dump(const LangOptions &LO, bool ShowColors) const {
5593 print(llvm::errs(), LO, ShowColors);
5594}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005595
5596/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005597void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005598 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00005599
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005600 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005601 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00005602
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005603 // Iterate through the CFGBlocks and print them one by one.
5604 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
5605 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00005606 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005607 continue;
Mike Stump31feda52009-07-17 01:31:16 +00005608
Aaron Ballmanff924b02013-11-18 20:11:50 +00005609 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005610 }
Mike Stump31feda52009-07-17 01:31:16 +00005611
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005612 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00005613 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005614 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00005615 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00005616}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005617
5618/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00005619void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
5620 bool ShowColors) const {
5621 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00005622}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005623
Yaron Kerencdae9412016-01-29 19:38:18 +00005624LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00005625 dump(getParent(), LangOptions(), false);
5626}
5627
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005628/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
5629/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005630void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00005631 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00005632 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005633 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005634 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00005635}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005636
Ted Kremenek15647632008-01-30 23:02:42 +00005637/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005638void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00005639 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00005640 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00005641 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005642}
5643
Csaba Dabisdea605e2019-05-29 18:29:31 +00005644/// printTerminatorJson - Pretty-prints the terminator in JSON format.
5645void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
5646 bool AddQuotes) const {
5647 std::string Buf;
5648 llvm::raw_string_ostream TempOut(Buf);
5649
5650 printTerminator(TempOut, LO);
5651
5652 Out << JsonFormat(TempOut.str(), AddQuotes);
5653}
5654
Kristof Umanndd53bdb2019-08-14 12:20:08 +00005655// Returns true if by simply looking at the block, we can be sure that it
5656// results in a sink during analysis. This is useful to know when the analysis
5657// was interrupted, and we try to figure out if it would sink eventually.
5658// There may be many more reasons why a sink would appear during analysis
5659// (eg. checkers may generate sinks arbitrarily), but here we only consider
5660// sinks that would be obvious by looking at the CFG.
5661static bool isImmediateSinkBlock(const CFGBlock *Blk) {
5662 if (Blk->hasNoReturnElement())
5663 return true;
5664
5665 // FIXME: Throw-expressions are currently generating sinks during analysis:
5666 // they're not supported yet, and also often used for actually terminating
5667 // the program. So we should treat them as sinks in this analysis as well,
5668 // at least for now, but once we have better support for exceptions,
5669 // we'd need to carefully handle the case when the throw is being
5670 // immediately caught.
5671 if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
5672 if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
5673 if (isa<CXXThrowExpr>(StmtElm->getStmt()))
5674 return true;
5675 return false;
5676 }))
5677 return true;
5678
5679 return false;
5680}
5681
5682bool CFGBlock::isInevitablySinking() const {
5683 const CFG &Cfg = *getParent();
5684
5685 const CFGBlock *StartBlk = this;
5686 if (isImmediateSinkBlock(StartBlk))
5687 return true;
5688
5689 llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
5690 llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
5691
5692 DFSWorkList.push_back(StartBlk);
5693 while (!DFSWorkList.empty()) {
5694 const CFGBlock *Blk = DFSWorkList.back();
5695 DFSWorkList.pop_back();
5696 Visited.insert(Blk);
5697
5698 // If at least one path reaches the CFG exit, it means that control is
5699 // returned to the caller. For now, say that we are not sure what
5700 // happens next. If necessary, this can be improved to analyze
5701 // the parent StackFrameContext's call site in a similar manner.
5702 if (Blk == &Cfg.getExit())
5703 return false;
5704
5705 for (const auto &Succ : Blk->succs()) {
5706 if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
5707 if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
5708 // If the block has reachable child blocks that aren't no-return,
5709 // add them to the worklist.
5710 DFSWorkList.push_back(SuccBlk);
5711 }
5712 }
5713 }
5714 }
5715
5716 // Nothing reached the exit. It can only mean one thing: there's no return.
5717 return true;
5718}
5719
Kristof Umannd5c9d9b2019-07-05 09:52:00 +00005720const Expr *CFGBlock::getLastCondition() const {
5721 // If the terminator is a temporary dtor or a virtual base, etc, we can't
5722 // retrieve a meaningful condition, bail out.
5723 if (Terminator.getKind() != CFGTerminator::StmtBranch)
5724 return nullptr;
5725
5726 // Also, if this method was called on a block that doesn't have 2 successors,
5727 // this block doesn't have retrievable condition.
5728 if (succ_size() < 2)
5729 return nullptr;
5730
5731 auto StmtElem = rbegin()->getAs<CFGStmt>();
5732 if (!StmtElem)
5733 return nullptr;
5734
5735 const Stmt *Cond = StmtElem->getStmt();
5736 if (isa<ObjCForCollectionStmt>(Cond))
5737 return nullptr;
5738
5739 // Only ObjCForCollectionStmt is known not to be a non-Expr terminator, hence
5740 // the cast<>.
5741 return cast<Expr>(Cond)->IgnoreParens();
5742}
5743
Kristof Umann9854d772019-07-03 13:03:33 +00005744Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
5745 Stmt *Terminator = getTerminatorStmt();
5746 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00005747 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005748
Kristof Umann9854d772019-07-03 13:03:33 +00005749 Expr *E = nullptr;
5750
5751 switch (Terminator->getStmtClass()) {
5752 default:
5753 break;
5754
5755 case Stmt::CXXForRangeStmtClass:
5756 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5757 break;
5758
5759 case Stmt::ForStmtClass:
5760 E = cast<ForStmt>(Terminator)->getCond();
5761 break;
5762
5763 case Stmt::WhileStmtClass:
5764 E = cast<WhileStmt>(Terminator)->getCond();
5765 break;
5766
5767 case Stmt::DoStmtClass:
5768 E = cast<DoStmt>(Terminator)->getCond();
5769 break;
5770
5771 case Stmt::IfStmtClass:
5772 E = cast<IfStmt>(Terminator)->getCond();
5773 break;
5774
5775 case Stmt::ChooseExprClass:
5776 E = cast<ChooseExpr>(Terminator)->getCond();
5777 break;
5778
5779 case Stmt::IndirectGotoStmtClass:
5780 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5781 break;
5782
5783 case Stmt::SwitchStmtClass:
5784 E = cast<SwitchStmt>(Terminator)->getCond();
5785 break;
5786
5787 case Stmt::BinaryConditionalOperatorClass:
5788 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5789 break;
5790
5791 case Stmt::ConditionalOperatorClass:
5792 E = cast<ConditionalOperator>(Terminator)->getCond();
5793 break;
5794
5795 case Stmt::BinaryOperatorClass: // '&&' and '||'
5796 E = cast<BinaryOperator>(Terminator)->getLHS();
5797 break;
5798
5799 case Stmt::ObjCForCollectionStmtClass:
5800 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005801 }
Mike Stump31feda52009-07-17 01:31:16 +00005802
Kristof Umann9854d772019-07-03 13:03:33 +00005803 if (!StripParens)
5804 return E;
5805
5806 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005807}
5808
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005809//===----------------------------------------------------------------------===//
5810// CFG Graphviz Visualization
5811//===----------------------------------------------------------------------===//
5812
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005813#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005814static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005815#endif
5816
Chris Lattnerc61089a2009-06-30 01:26:17 +00005817void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005818#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005819 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005820 GraphHelper = &H;
5821 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005822 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005823#endif
5824}
5825
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005826namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005827
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005828template<>
5829struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005830 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005831
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005832 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005833#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005834 std::string OutSStr;
5835 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005836 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005837 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005838
5839 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5840
5841 // Process string output to make it nicer...
5842 for (unsigned i = 0; i != OutStr.length(); ++i)
5843 if (OutStr[i] == '\n') { // Left justify
5844 OutStr[i] = '\\';
5845 OutStr.insert(OutStr.begin()+i+1, 'l');
5846 }
Mike Stump31feda52009-07-17 01:31:16 +00005847
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005848 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005849#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005850 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005851#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005852 }
5853};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005854
5855} // namespace llvm