blob: 7431c19cceed4504771e8e3188d1cd6044721885 [file] [log] [blame]
Eugene Zelenko38c70522017-12-07 21:55:09 +00001//===- CFG.cpp - Classes for representing and building CFGs ---------------===//
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
Ted Kremenek6796fbd2009-07-16 18:13:04 +000015#include "clang/Analysis/CFG.h"
Benjamin Kramer1ea8e092012-07-04 17:04:04 +000016#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000020#include "clang/AST/DeclCXX.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000021#include "clang/AST/DeclGroup.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/OperationKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/PrettyPrinter.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000026#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/AST/StmtVisitor.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000030#include "clang/AST/Type.h"
31#include "clang/Analysis/Support/BumpVector.h"
Jordan Rose5374c072013-08-19 16:27:28 +000032#include "clang/Basic/Builtins.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000033#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/SourceLocation.h"
37#include "clang/Basic/Specifiers.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/APSInt.h"
40#include "llvm/ADT/ArrayRef.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000041#include "llvm/ADT/DenseMap.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000042#include "llvm/ADT/Optional.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SetVector.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000045#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000046#include "llvm/ADT/SmallVector.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000047#include "llvm/Support/Allocator.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000048#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/DOTGraphTraits.h"
51#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000052#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000053#include "llvm/Support/GraphWriter.h"
54#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenko38c70522017-12-07 21:55:09 +000055#include "llvm/Support/raw_ostream.h"
56#include <cassert>
57#include <memory>
58#include <string>
59#include <tuple>
60#include <utility>
61#include <vector>
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000062
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000063using namespace clang;
64
Ted Kremenek5ef32db2011-08-12 23:37:29 +000065static SourceLocation GetEndLoc(Decl *D) {
66 if (VarDecl *VD = dyn_cast<VarDecl>(D))
67 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000068 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000069 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000070}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000071
George Burgess IVced56e62015-10-01 18:47:52 +000072/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
73/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
Eugene Zelenko38c70522017-12-07 21:55:09 +000074static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
George Burgess IVced56e62015-10-01 18:47:52 +000075 E = E->IgnoreParens();
76 if (isa<IntegerLiteral>(E))
77 return E;
78 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
79 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
80 return nullptr;
81}
82
83/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
84/// an integer literal or an enum constant.
85///
86/// If this fails, at least one of the returned DeclRefExpr or Expr will be
87/// null.
88static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
89tryNormalizeBinaryOperator(const BinaryOperator *B) {
90 BinaryOperatorKind Op = B->getOpcode();
91
92 const Expr *MaybeDecl = B->getLHS();
93 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
94 // Expr looked like `0 == Foo` instead of `Foo == 0`
95 if (Constant == nullptr) {
96 // Flip the operator
97 if (Op == BO_GT)
98 Op = BO_LT;
99 else if (Op == BO_GE)
100 Op = BO_LE;
101 else if (Op == BO_LT)
102 Op = BO_GT;
103 else if (Op == BO_LE)
104 Op = BO_GE;
105
106 MaybeDecl = B->getRHS();
107 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
108 }
109
110 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
111 return std::make_tuple(D, Op, Constant);
112}
113
114/// For an expression `x == Foo && x == Bar`, this determines whether the
115/// `Foo` and `Bar` are either of the same enumeration type, or both integer
116/// literals.
117///
118/// It's an error to pass this arguments that are not either IntegerLiterals
119/// or DeclRefExprs (that have decls of type EnumConstantDecl)
120static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
121 // User intent isn't clear if they're mixing int literals with enum
122 // constants.
123 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
124 return false;
125
126 // Integer literal comparisons, regardless of literal type, are acceptable.
127 if (isa<IntegerLiteral>(E1))
128 return true;
129
130 // IntegerLiterals are handled above and only EnumConstantDecls are expected
131 // beyond this point
132 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
133 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
134 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
135
136 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
137 const DeclContext *DC1 = Decl1->getDeclContext();
138 const DeclContext *DC2 = Decl2->getDeclContext();
139
140 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
141 return DC1 == DC2;
142}
143
Eugene Zelenko38c70522017-12-07 21:55:09 +0000144namespace {
145
Ted Kremenek7c58d352011-03-10 01:14:11 +0000146class CFGBuilder;
147
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000148/// The CFG builder uses a recursive algorithm to build the CFG. When
149/// we process an expression, sometimes we know that we must add the
150/// subexpressions as block-level expressions. For example:
151///
152/// exp1 || exp2
153///
154/// When processing the '||' expression, we know that exp1 and exp2
155/// need to be added as block-level expressions, even though they
156/// might not normally need to be. AddStmtChoice records this
157/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
158/// the builder has an option not to add a subexpression as a
159/// block-level expression.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000160class AddStmtChoice {
161public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000162 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000163
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000164 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000165
Ted Kremenek7c58d352011-03-10 01:14:11 +0000166 bool alwaysAdd(CFGBuilder &builder,
167 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000168
169 /// Return a copy of this object, except with the 'always-add' bit
170 /// set as specified.
171 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000172 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000173 }
174
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000175private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000176 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000177};
Mike Stump31feda52009-07-17 01:31:16 +0000178
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000179/// LocalScope - Node in tree of local scopes created for C++ implicit
180/// destructor calls generation. It contains list of automatic variables
181/// declared in the scope and link to position in previous scope this scope
182/// began in.
183///
184/// The process of creating local scopes is as follows:
185/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
186/// - Before processing statements in scope (e.g. CompoundStmt) create
187/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
188/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000189/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000190/// at this VarDecl,
191/// - For every normal (without jump) end of scope add to CFGBlock destructors
192/// for objects in the current scope,
193/// - For every jump add to CFGBlock destructors for objects
194/// between CFGBuilder::ScopePos and local scope position saved for jump
195/// target. Thanks to C++ restrictions on goto jumps we can be sure that
196/// jump target position will be on the path to root from CFGBuilder::ScopePos
197/// (adding any variable that doesn't need constructor to be called to
198/// LocalScope can break this assumption),
199///
200class LocalScope {
201public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000202 friend class const_iterator;
203
204 using AutomaticVarsTy = BumpVector<VarDecl *>;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000205
206 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000207 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000208 class const_iterator {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000209 const LocalScope* Scope = nullptr;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000210
211 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
212 /// Invalid iterator (with null Scope) has VarIter equal to 0.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000213 unsigned VarIter = 0;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000214
215 public:
216 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
217 /// Incrementing invalid iterator is allowed and will result in invalid
218 /// iterator.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000219 const_iterator() = default;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000220
221 /// Create valid iterator. In case when S.Prev is an invalid iterator and
222 /// I is equal to 0, this will create invalid iterator.
223 const_iterator(const LocalScope& S, unsigned I)
224 : Scope(&S), VarIter(I) {
225 // Iterator to "end" of scope is not allowed. Handle it by going up
226 // in scopes tree possibly up to invalid iterator in the root.
227 if (VarIter == 0 && Scope)
228 *this = Scope->Prev;
229 }
230
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000231 VarDecl *const* operator->() const {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000232 assert(Scope && "Dereferencing invalid iterator is not allowed");
233 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000234 return &Scope->Vars[VarIter - 1];
235 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000236 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000237 return *this->operator->();
238 }
239
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000240 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000241 if (!Scope)
242 return *this;
243
Eugene Zelenko38c70522017-12-07 21:55:09 +0000244 assert(VarIter != 0 && "Iterator has invalid value of VarIter member");
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000245 --VarIter;
246 if (VarIter == 0)
247 *this = Scope->Prev;
248 return *this;
249 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000250 const_iterator operator++(int) {
251 const_iterator P = *this;
252 ++*this;
253 return P;
254 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000255
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000256 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000257 return Scope == rhs.Scope && VarIter == rhs.VarIter;
258 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000259 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000260 return !(*this == rhs);
261 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000262
Aaron Ballman67347662015-02-15 22:00:28 +0000263 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000264 return *this != const_iterator();
265 }
266
267 int distance(const_iterator L);
Matthias Gehre351c2182017-07-12 07:04:19 +0000268 const_iterator shared_parent(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000269 };
270
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000271private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000272 BumpVectorContext ctx;
273
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000274 /// Automatic variables in order of declaration.
275 AutomaticVarsTy Vars;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000276
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000277 /// Iterator to variable in previous scope that was declared just before
278 /// begin of this scope.
279 const_iterator Prev;
280
281public:
282 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000283 LocalScope(BumpVectorContext ctx, const_iterator P)
284 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000285
286 /// Begin of scope in direction of CFG building (backwards).
287 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000288
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000289 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000290 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000291 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000292};
293
Eugene Zelenko38c70522017-12-07 21:55:09 +0000294} // namespace
295
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000296/// distance - Calculates distance from this to L. L must be reachable from this
297/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
298/// number of scopes between this and L.
299int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
300 int D = 0;
301 const_iterator F = *this;
302 while (F.Scope != L.Scope) {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000303 assert(F != const_iterator() &&
304 "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000305 D += F.VarIter;
306 F = F.Scope->Prev;
307 }
308 D += F.VarIter - L.VarIter;
309 return D;
310}
311
Matthias Gehre351c2182017-07-12 07:04:19 +0000312/// Calculates the closest parent of this iterator
313/// that is in a scope reachable through the parents of L.
314/// I.e. when using 'goto' from this to L, the lifetime of all variables
315/// between this and shared_parent(L) end.
316LocalScope::const_iterator
317LocalScope::const_iterator::shared_parent(LocalScope::const_iterator L) {
318 llvm::SmallPtrSet<const LocalScope *, 4> ScopesOfL;
319 while (true) {
320 ScopesOfL.insert(L.Scope);
321 if (L == const_iterator())
322 break;
323 L = L.Scope->Prev;
324 }
325
326 const_iterator F = *this;
327 while (true) {
328 if (ScopesOfL.count(F.Scope))
329 return F;
330 assert(F != const_iterator() &&
331 "L iterator is not reachable from F iterator.");
332 F = F.Scope->Prev;
333 }
334}
335
Eugene Zelenko38c70522017-12-07 21:55:09 +0000336namespace {
337
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000338/// Structure for specifying position in CFG during its build process. It
339/// consists of CFGBlock that specifies position in CFG and
340/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000341struct BlockScopePosPair {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000342 CFGBlock *block = nullptr;
343 LocalScope::const_iterator scopePosition;
344
345 BlockScopePosPair() = default;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000346 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000347 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000348};
349
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000350/// TryResult - a class representing a variant over the values
351/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
352/// and is used by the CFGBuilder to decide if a branch condition
353/// can be decided up front during CFG construction.
354class TryResult {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000355 int X = -1;
356
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000357public:
Eugene Zelenko38c70522017-12-07 21:55:09 +0000358 TryResult() = default;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000359 TryResult(bool b) : X(b ? 1 : 0) {}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000360
361 bool isTrue() const { return X == 1; }
362 bool isFalse() const { return X == 0; }
363 bool isKnown() const { return X >= 0; }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000364
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000365 void negate() {
366 assert(isKnown());
367 X ^= 0x1;
368 }
369};
370
Eugene Zelenko38c70522017-12-07 21:55:09 +0000371} // namespace
372
373static TryResult bothKnownTrue(TryResult R1, TryResult R2) {
Manuel Klimekdeb02622014-08-08 07:37:13 +0000374 if (!R1.isKnown() || !R2.isKnown())
375 return TryResult();
376 return TryResult(R1.isTrue() && R2.isTrue());
377}
378
Eugene Zelenko38c70522017-12-07 21:55:09 +0000379namespace {
380
Ted Kremenek8ae67872013-02-05 22:00:19 +0000381class reverse_children {
382 llvm::SmallVector<Stmt *, 12> childrenBuf;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000383 ArrayRef<Stmt *> children;
384
Ted Kremenek8ae67872013-02-05 22:00:19 +0000385public:
386 reverse_children(Stmt *S);
387
Eugene Zelenko38c70522017-12-07 21:55:09 +0000388 using iterator = ArrayRef<Stmt *>::reverse_iterator;
389
Ted Kremenek8ae67872013-02-05 22:00:19 +0000390 iterator begin() const { return children.rbegin(); }
391 iterator end() const { return children.rend(); }
392};
393
Eugene Zelenko38c70522017-12-07 21:55:09 +0000394} // namespace
Ted Kremenek8ae67872013-02-05 22:00:19 +0000395
396reverse_children::reverse_children(Stmt *S) {
397 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
398 children = CE->getRawSubExprs();
399 return;
400 }
401 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000402 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000403 case Stmt::InitListExprClass: {
404 InitListExpr *IE = cast<InitListExpr>(S);
405 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
406 IE->getNumInits());
407 return;
408 }
409 default:
410 break;
411 }
412
413 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000414 for (Stmt *SubStmt : S->children())
415 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000416
417 // This needs to be done *after* childrenBuf has been populated.
418 children = childrenBuf;
419}
420
Eugene Zelenko38c70522017-12-07 21:55:09 +0000421namespace {
422
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000423/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000424/// The builder is stateful: an instance of the builder should be used to only
425/// construct a single CFG.
426///
427/// Example usage:
428///
429/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000430/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000431///
Mike Stump31feda52009-07-17 01:31:16 +0000432/// CFG construction is done via a recursive walk of an AST. We actually parse
433/// the AST in reverse order so that the successor of a basic block is
434/// constructed prior to its predecessor. This allows us to nicely capture
435/// implicit fall-throughs without extra basic blocks.
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000436class CFGBuilder {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000437 using JumpTarget = BlockScopePosPair;
438 using JumpSource = BlockScopePosPair;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000439
Mike Stump0d76d072009-07-20 23:24:15 +0000440 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000441 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000442
Eugene Zelenko38c70522017-12-07 21:55:09 +0000443 // Current block.
444 CFGBlock *Block = nullptr;
445
446 // Block after the current block.
447 CFGBlock *Succ = nullptr;
448
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000449 JumpTarget ContinueJumpTarget;
450 JumpTarget BreakJumpTarget;
Nico Weber699670e2017-08-23 15:33:16 +0000451 JumpTarget SEHLeaveJumpTarget;
Eugene Zelenko38c70522017-12-07 21:55:09 +0000452 CFGBlock *SwitchTerminatedBlock = nullptr;
453 CFGBlock *DefaultCaseBlock = nullptr;
Nico Weber699670e2017-08-23 15:33:16 +0000454
455 // This can point either to a try or a __try block. The frontend forbids
456 // mixing both kinds in one function, so having one for both is enough.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000457 CFGBlock *TryTerminatedBlock = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000458
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000459 // Current position in local scope.
460 LocalScope::const_iterator ScopePos;
461
462 // LabelMap records the mapping from Label expressions to their jump targets.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000463 using LabelMapTy = llvm::DenseMap<LabelDecl *, JumpTarget>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000464 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000465
466 // A list of blocks that end with a "goto" that must be backpatched to their
467 // resolved targets upon completion of CFG construction.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000468 using BackpatchBlocksTy = std::vector<JumpSource>;
Ted Kremenek8a632182007-08-21 23:26:17 +0000469 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000470
Ted Kremenekeda180e22007-08-28 19:26:49 +0000471 // A list of labels whose address has been taken (for indirect gotos).
Eugene Zelenko38c70522017-12-07 21:55:09 +0000472 using LabelSetTy = llvm::SmallSetVector<LabelDecl *, 8>;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000473 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000474
Artem Dergachev41ffb302018-02-08 22:58:15 +0000475 // Information about the currently visited C++ object construction site.
476 // This is set in the construction trigger and read when the constructor
477 // itself is being visited.
Artem Dergachev783a4572018-02-23 22:20:39 +0000478 llvm::DenseMap<CXXConstructExpr *, const ConstructionContext *>
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000479 ConstructionContextMap;
Artem Dergachev41ffb302018-02-08 22:58:15 +0000480
Eugene Zelenko38c70522017-12-07 21:55:09 +0000481 bool badCFG = false;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000482 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000483
484 // State to track for building switch statements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000485 bool switchExclusivelyCovered = false;
486 Expr::EvalResult *switchCond = nullptr;
Ted Kremeneka099c592011-03-10 03:50:34 +0000487
Eugene Zelenko38c70522017-12-07 21:55:09 +0000488 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry = nullptr;
489 const Stmt *lastLookup = nullptr;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000490
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000491 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
492 // during construction of branches for chained logical operators.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000493 using CachedBoolEvalsTy = llvm::DenseMap<Expr *, TryResult>;
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000494 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000495
Mike Stump31feda52009-07-17 01:31:16 +0000496public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000497 explicit CFGBuilder(ASTContext *astContext,
Nico Weber699670e2017-08-23 15:33:16 +0000498 const CFG::BuildOptions &buildOpts)
499 : Context(astContext), cfg(new CFG()), // crew a new CFG
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +0000500 ConstructionContextMap(), BuildOpts(buildOpts) {}
501
Mike Stump31feda52009-07-17 01:31:16 +0000502
Ted Kremenek9aae5132007-08-23 21:42:29 +0000503 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000504 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000505
Ted Kremeneka099c592011-03-10 03:50:34 +0000506 bool alwaysAdd(const Stmt *stmt);
507
Ted Kremenek93668002009-07-17 22:18:43 +0000508private:
509 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000510 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
511 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000512 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000513 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000514 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000515 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000516 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000517 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
518 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000519 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000520 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
521 AddStmtChoice asc);
522 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
523 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000524 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000525 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000526 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
527 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
528 AddStmtChoice asc);
529 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
530 AddStmtChoice asc);
531 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
532 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000533 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000534 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000535 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
536 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000537 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000538 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000539 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000540 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000541 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000542 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
543 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000544 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000545 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000546 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000547 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
548 Stmt *Term,
549 CFGBlock *TrueBlock,
550 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000551 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000552 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
553 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
554 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
555 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000556 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000557 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000558 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000559 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Nico Weber699670e2017-08-23 15:33:16 +0000560 CFGBlock *VisitSEHExceptStmt(SEHExceptStmt *S);
561 CFGBlock *VisitSEHFinallyStmt(SEHFinallyStmt *S);
562 CFGBlock *VisitSEHLeaveStmt(SEHLeaveStmt *S);
563 CFGBlock *VisitSEHTryStmt(SEHTryStmt *S);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000564 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000565 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000566 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
567 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000568 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000569 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000570
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000571 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
572 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000573 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000574 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000575
Manuel Klimekb5616c92014-08-07 10:42:17 +0000576 /// When creating the CFG for temporary destructors, we want to mirror the
577 /// branch structure of the corresponding constructor calls.
578 /// Thus, while visiting a statement for temporary destructors, we keep a
579 /// context to keep track of the following information:
580 /// - whether a subexpression is executed unconditionally
581 /// - if a subexpression is executed conditionally, the first
582 /// CXXBindTemporaryExpr we encounter in that subexpression (which
583 /// corresponds to the last temporary destructor we have to call for this
584 /// subexpression) and the CFG block at that point (which will become the
585 /// successor block when inserting the decision point).
586 ///
587 /// That way, we can build the branch structure for temporary destructors as
588 /// follows:
589 /// 1. If a subexpression is executed unconditionally, we add the temporary
590 /// destructor calls to the current block.
591 /// 2. If a subexpression is executed conditionally, when we encounter a
592 /// CXXBindTemporaryExpr:
593 /// a) If it is the first temporary destructor call in the subexpression,
594 /// we remember the CXXBindTemporaryExpr and the current block in the
595 /// TempDtorContext; we start a new block, and insert the temporary
596 /// destructor call.
597 /// b) Otherwise, add the temporary destructor call to the current block.
598 /// 3. When we finished visiting a conditionally executed subexpression,
599 /// and we found at least one temporary constructor during the visitation
600 /// (2.a has executed), we insert a decision block that uses the
601 /// CXXBindTemporaryExpr as terminator, and branches to the current block
602 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
603 /// branches to the stored successor.
604 struct TempDtorContext {
Eugene Zelenko38c70522017-12-07 21:55:09 +0000605 TempDtorContext() = default;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000606 TempDtorContext(TryResult KnownExecuted)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000607 : IsConditional(true), KnownExecuted(KnownExecuted) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000608
609 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000610 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000611 /// conditionally executed, and it is the first one we encounter while
612 /// visiting a subexpression - other temporary destructors at the same level
613 /// will be added to the same block and are executed under the same
614 /// condition.
615 bool needsTempDtorBranch() const {
616 return IsConditional && !TerminatorExpr;
617 }
618
619 /// Remember the successor S of a temporary destructor decision branch for
620 /// the corresponding CXXBindTemporaryExpr E.
621 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
622 Succ = S;
623 TerminatorExpr = E;
624 }
625
Eugene Zelenko38c70522017-12-07 21:55:09 +0000626 const bool IsConditional = false;
627 const TryResult KnownExecuted = true;
628 CFGBlock *Succ = nullptr;
629 CXXBindTemporaryExpr *TerminatorExpr = nullptr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000630 };
631
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000632 // Visitors to walk an AST and generate destructors of temporaries in
633 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000634 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
635 TempDtorContext &Context);
636 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
637 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
638 TempDtorContext &Context);
639 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
640 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
641 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
642 AbstractConditionalOperator *E, bool BindToTemporary,
643 TempDtorContext &Context);
644 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
645 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000646
Ted Kremenek6065ef62008-04-28 18:00:46 +0000647 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000648 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000649 badCFG = true;
650 return Block;
651 }
Mike Stump31feda52009-07-17 01:31:16 +0000652
Artem Dergachev41ffb302018-02-08 22:58:15 +0000653 // Scan the child statement \p Child to find the constructor that might
654 // have been directly triggered by the current node, \p Trigger. If such
655 // constructor has been found, set current construction context to point
656 // to the trigger statement. The construction context will be unset once
657 // it is consumed when the CFG building procedure processes the
658 // construct-expression and adds the respective CFGConstructor element.
Artem Dergachev783a4572018-02-23 22:20:39 +0000659 void findConstructionContexts(const ConstructionContext *ContextSoFar,
660 Stmt *Child);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000661 // Unset the construction context after consuming it. This is done immediately
662 // after adding the CFGConstructor element, so there's no need to
663 // do this manually in every Visit... function.
Artem Dergachev783a4572018-02-23 22:20:39 +0000664 void cleanupConstructionContext(CXXConstructExpr *CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000665
Ted Kremenek93668002009-07-17 22:18:43 +0000666 void autoCreateBlock() { if (!Block) Block = createBlock(); }
667 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000668 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000669
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000670 CFGBlock *addStmt(Stmt *S) {
671 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000672 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000673
Alexis Hunt1d792652011-01-08 20:30:50 +0000674 CFGBlock *addInitializer(CXXCtorInitializer *I);
Peter Szecsi999a25f2017-08-19 11:19:16 +0000675 void addLoopExit(const Stmt *LoopStmt);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000676 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000677 LocalScope::const_iterator E, Stmt *S);
Matthias Gehre351c2182017-07-12 07:04:19 +0000678 void addLifetimeEnds(LocalScope::const_iterator B,
679 LocalScope::const_iterator E, Stmt *S);
680 void addAutomaticObjHandling(LocalScope::const_iterator B,
681 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000682 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000683
Marcin Swiderski5e415732010-09-30 23:05:00 +0000684 // Local scopes creation.
685 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
686
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000687 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000688 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
689 LocalScope* Scope = nullptr);
690 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000691
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000692 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000693
694 // Interface to CFGBlock - adding CFGElements.
Eugene Zelenko38c70522017-12-07 21:55:09 +0000695
Ted Kremenek37881932011-04-04 23:29:12 +0000696 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000697 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000698 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000699
Jordy Rose17347372011-06-10 08:49:37 +0000700 // All block-level expressions should have already been IgnoreParens()ed.
701 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000702 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000703 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000704
Artem Dergachev41ffb302018-02-08 22:58:15 +0000705 void appendConstructor(CFGBlock *B, CXXConstructExpr *CE) {
706 if (BuildOpts.AddRichCXXConstructors) {
Artem Dergachev783a4572018-02-23 22:20:39 +0000707 if (const ConstructionContext *CC = ConstructionContextMap.lookup(CE)) {
708 B->appendConstructor(CE, CC, cfg->getBumpVectorContext());
709 cleanupConstructionContext(CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +0000710 return;
711 }
712 }
713
714 // No valid construction context found. Fall back to statement.
715 B->appendStmt(CE, cfg->getBumpVectorContext());
716 }
717
Alexis Hunt1d792652011-01-08 20:30:50 +0000718 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000719 B->appendInitializer(I, cfg->getBumpVectorContext());
720 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000721
Jordan Rosec9176072014-01-13 17:59:19 +0000722 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
723 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
724 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000725
Marcin Swiderski20b88732010-10-05 05:37:00 +0000726 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
727 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
728 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000729
Marcin Swiderski20b88732010-10-05 05:37:00 +0000730 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
731 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
732 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000733
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000734 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
735 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
736 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000737
Chandler Carruthad747252011-09-13 06:09:01 +0000738 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
739 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
740 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000741
Matthias Gehre351c2182017-07-12 07:04:19 +0000742 void appendLifetimeEnds(CFGBlock *B, VarDecl *VD, Stmt *S) {
743 B->appendLifetimeEnds(VD, S, cfg->getBumpVectorContext());
744 }
745
Peter Szecsi999a25f2017-08-19 11:19:16 +0000746 void appendLoopExit(CFGBlock *B, const Stmt *LoopStmt) {
747 B->appendLoopExit(LoopStmt, cfg->getBumpVectorContext());
748 }
749
Jordan Rosed2f40792013-09-03 17:00:57 +0000750 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
751 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
752 }
753
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000754 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000755 LocalScope::const_iterator B, LocalScope::const_iterator E);
756
Matthias Gehre351c2182017-07-12 07:04:19 +0000757 void prependAutomaticObjLifetimeWithTerminator(CFGBlock *Blk,
758 LocalScope::const_iterator B,
759 LocalScope::const_iterator E);
760
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000761 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
762 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
763 cfg->getBumpVectorContext());
764 }
765
766 /// Add a reachable successor to a block, with the alternate variant that is
767 /// unreachable.
768 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
769 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
770 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000771 }
Mike Stump11289f42009-09-09 15:08:12 +0000772
Richard Trieuf935b562014-04-05 05:17:01 +0000773 /// \brief Find a relational comparison with an expression evaluating to a
774 /// boolean and a constant other than 0 and 1.
775 /// e.g. if ((x < y) == 10)
776 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
777 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
778 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
779
780 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
781 const Expr *BoolExpr = RHSExpr;
782 bool IntFirst = true;
783 if (!IntLiteral) {
784 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
785 BoolExpr = LHSExpr;
786 IntFirst = false;
787 }
788
789 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
790 return TryResult();
791
792 llvm::APInt IntValue = IntLiteral->getValue();
793 if ((IntValue == 1) || (IntValue == 0))
794 return TryResult();
795
796 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
797 !IntValue.isNegative();
798
799 BinaryOperatorKind Bok = B->getOpcode();
800 if (Bok == BO_GT || Bok == BO_GE) {
801 // Always true for 10 > bool and bool > -1
802 // Always false for -1 > bool and bool > 10
803 return TryResult(IntFirst == IntLarger);
804 } else {
805 // Always true for -1 < bool and bool < 10
806 // Always false for 10 < bool and bool < -1
807 return TryResult(IntFirst != IntLarger);
808 }
809 }
810
Jordan Rose7afd71e2014-05-20 17:31:11 +0000811 /// Find an incorrect equality comparison. Either with an expression
812 /// evaluating to a boolean and a constant other than 0 and 1.
813 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
814 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000815 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
816 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
817 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
818
819 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
820 const Expr *BoolExpr = RHSExpr;
821
822 if (!IntLiteral) {
823 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
824 BoolExpr = LHSExpr;
825 }
826
Jordan Rose7afd71e2014-05-20 17:31:11 +0000827 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000828 return TryResult();
829
Jordan Rose7afd71e2014-05-20 17:31:11 +0000830 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
831 if (BitOp && (BitOp->getOpcode() == BO_And ||
832 BitOp->getOpcode() == BO_Or)) {
833 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
834 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
835
836 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
837
838 if (!IntLiteral2)
839 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
840
841 if (!IntLiteral2)
842 return TryResult();
843
844 llvm::APInt L1 = IntLiteral->getValue();
845 llvm::APInt L2 = IntLiteral2->getValue();
846 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
847 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
848 if (BuildOpts.Observer)
849 BuildOpts.Observer->compareBitwiseEquality(B,
850 B->getOpcode() != BO_EQ);
851 TryResult(B->getOpcode() != BO_EQ);
852 }
853 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
854 llvm::APInt IntValue = IntLiteral->getValue();
855 if ((IntValue == 1) || (IntValue == 0)) {
856 return TryResult();
857 }
858 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000859 }
860
Jordan Rose7afd71e2014-05-20 17:31:11 +0000861 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000862 }
863
864 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
865 const llvm::APSInt &Value1,
866 const llvm::APSInt &Value2) {
867 assert(Value1.isSigned() == Value2.isSigned());
868 switch (Relation) {
869 default:
870 return TryResult();
871 case BO_EQ:
872 return TryResult(Value1 == Value2);
873 case BO_NE:
874 return TryResult(Value1 != Value2);
875 case BO_LT:
876 return TryResult(Value1 < Value2);
877 case BO_LE:
878 return TryResult(Value1 <= Value2);
879 case BO_GT:
880 return TryResult(Value1 > Value2);
881 case BO_GE:
882 return TryResult(Value1 >= Value2);
883 }
884 }
885
886 /// \brief Find a pair of comparison expressions with or without parentheses
887 /// with a shared variable and constants and a logical operator between them
888 /// that always evaluates to either true or false.
889 /// e.g. if (x != 3 || x != 4)
890 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
891 assert(B->isLogicalOp());
892 const BinaryOperator *LHS =
893 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
894 const BinaryOperator *RHS =
895 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
896 if (!LHS || !RHS)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000897 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000898
899 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000900 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000901
George Burgess IVced56e62015-10-01 18:47:52 +0000902 const DeclRefExpr *Decl1;
903 const Expr *Expr1;
904 BinaryOperatorKind BO1;
905 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000906
George Burgess IVced56e62015-10-01 18:47:52 +0000907 if (!Decl1 || !Expr1)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000908 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000909
George Burgess IVced56e62015-10-01 18:47:52 +0000910 const DeclRefExpr *Decl2;
911 const Expr *Expr2;
912 BinaryOperatorKind BO2;
913 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000914
George Burgess IVced56e62015-10-01 18:47:52 +0000915 if (!Decl2 || !Expr2)
Eugene Zelenko38c70522017-12-07 21:55:09 +0000916 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000917
918 // Check that it is the same variable on both sides.
919 if (Decl1->getDecl() != Decl2->getDecl())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000920 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000921
George Burgess IVced56e62015-10-01 18:47:52 +0000922 // Make sure the user's intent is clear (e.g. they're comparing against two
923 // int literals, or two things from the same enum)
924 if (!areExprTypesCompatible(Expr1, Expr2))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000925 return {};
George Burgess IVced56e62015-10-01 18:47:52 +0000926
Richard Trieuf935b562014-04-05 05:17:01 +0000927 llvm::APSInt L1, L2;
928
George Burgess IVced56e62015-10-01 18:47:52 +0000929 if (!Expr1->EvaluateAsInt(L1, *Context) ||
930 !Expr2->EvaluateAsInt(L2, *Context))
Eugene Zelenko38c70522017-12-07 21:55:09 +0000931 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000932
933 // Can't compare signed with unsigned or with different bit width.
934 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000935 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000936
937 // Values that will be used to determine if result of logical
938 // operator is always true/false
939 const llvm::APSInt Values[] = {
940 // Value less than both Value1 and Value2
941 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
942 // L1
943 L1,
944 // Value between Value1 and Value2
945 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
946 L1.isUnsigned()),
947 // L2
948 L2,
949 // Value greater than both Value1 and Value2
950 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
951 };
952
953 // Check whether expression is always true/false by evaluating the following
954 // * variable x is less than the smallest literal.
955 // * variable x is equal to the smallest literal.
956 // * Variable x is between smallest and largest literal.
957 // * Variable x is equal to the largest literal.
958 // * Variable x is greater than largest literal.
959 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +0000960 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +0000961 TryResult Res1, Res2;
962 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
963 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
964
965 if (!Res1.isKnown() || !Res2.isKnown())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000966 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000967
968 if (B->getOpcode() == BO_LAnd) {
969 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
970 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
971 } else {
972 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
973 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
974 }
975 }
976
977 if (AlwaysTrue || AlwaysFalse) {
978 if (BuildOpts.Observer)
979 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
980 return TryResult(AlwaysTrue);
981 }
Eugene Zelenko38c70522017-12-07 21:55:09 +0000982 return {};
Richard Trieuf935b562014-04-05 05:17:01 +0000983 }
984
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000985 /// Try and evaluate an expression to an integer constant.
986 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
987 if (!BuildOpts.PruneTriviallyFalseEdges)
988 return false;
989 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000990 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000991 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000994 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000995 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000996 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000997 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000998 S->isTypeDependent() || S->isValueDependent())
Eugene Zelenko38c70522017-12-07 21:55:09 +0000999 return {};
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001000
1001 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
1002 if (Bop->isLogicalOp()) {
1003 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +00001004 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
1005 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001006 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +00001007
1008 // Retrieve result at first, or the map might be updated.
1009 TryResult Result = evaluateAsBooleanConditionNoCache(S);
1010 CachedBoolEvals[S] = Result; // update or insert
1011 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001012 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001013 else {
1014 switch (Bop->getOpcode()) {
1015 default: break;
1016 // For 'x & 0' and 'x * 0', we can determine that
1017 // the value is always false.
1018 case BO_Mul:
1019 case BO_And: {
1020 // If either operand is zero, we know the value
1021 // must be false.
1022 llvm::APSInt IntVal;
1023 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001024 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001025 return TryResult(false);
1026 }
1027 }
1028 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00001029 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +00001030 return TryResult(false);
1031 }
1032 }
1033 }
1034 break;
1035 }
1036 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001037 }
1038
1039 return evaluateAsBooleanConditionNoCache(S);
1040 }
1041
1042 /// \brief Evaluate as boolean \param E without using the cache.
1043 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
1044 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
1045 if (Bop->isLogicalOp()) {
1046 TryResult LHS = tryEvaluateBool(Bop->getLHS());
1047 if (LHS.isKnown()) {
1048 // We were able to evaluate the LHS, see if we can get away with not
1049 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1050 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1051 return LHS.isTrue();
1052
1053 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1054 if (RHS.isKnown()) {
1055 if (Bop->getOpcode() == BO_LOr)
1056 return LHS.isTrue() || RHS.isTrue();
1057 else
1058 return LHS.isTrue() && RHS.isTrue();
1059 }
1060 } else {
1061 TryResult RHS = tryEvaluateBool(Bop->getRHS());
1062 if (RHS.isKnown()) {
1063 // We can't evaluate the LHS; however, sometimes the result
1064 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1065 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
1066 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +00001067 } else {
1068 TryResult BopRes = checkIncorrectLogicOperator(Bop);
1069 if (BopRes.isKnown())
1070 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001071 }
1072 }
1073
Eugene Zelenko38c70522017-12-07 21:55:09 +00001074 return {};
Richard Trieuf935b562014-04-05 05:17:01 +00001075 } else if (Bop->isEqualityOp()) {
1076 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
1077 if (BopRes.isKnown())
1078 return BopRes.isTrue();
1079 } else if (Bop->isRelationalOp()) {
1080 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
1081 if (BopRes.isKnown())
1082 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +00001083 }
1084 }
1085
1086 bool Result;
1087 if (E->EvaluateAsBooleanCondition(Result, *Context))
1088 return Result;
1089
Eugene Zelenko38c70522017-12-07 21:55:09 +00001090 return {};
Mike Stump773582d2009-07-23 23:25:26 +00001091 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001092
1093 bool hasTrivialDestructor(VarDecl *VD);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00001094};
Mike Stump31feda52009-07-17 01:31:16 +00001095
Eugene Zelenko38c70522017-12-07 21:55:09 +00001096} // namespace
1097
Ted Kremeneka099c592011-03-10 03:50:34 +00001098inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
1099 const Stmt *stmt) const {
1100 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
1101}
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001102
Ted Kremeneka099c592011-03-10 03:50:34 +00001103bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +00001104 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
1105
Ted Kremeneka099c592011-03-10 03:50:34 +00001106 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +00001107 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001108
1109 if (lastLookup == stmt) {
1110 if (cachedEntry) {
1111 assert(cachedEntry->first == stmt);
1112 return true;
1113 }
Ted Kremenek8b46c002011-07-19 14:18:43 +00001114 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001115 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001116
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001117 lastLookup = stmt;
1118
1119 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +00001120 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
1121
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001122 if (!fb) {
1123 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +00001124 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +00001125 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001126 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001127
1128 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001129 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +00001130 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +00001131 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +00001132 }
1133
Ted Kremeneka099c592011-03-10 03:50:34 +00001134 cachedEntry = &*itr;
1135 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001136}
1137
Douglas Gregor4619e432008-12-05 23:32:09 +00001138// FIXME: Add support for dependent-sized array types in C++?
1139// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001140static const VariableArrayType *FindVA(const Type *t) {
1141 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1142 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001143 if (vat->getSizeExpr())
1144 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001145
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001146 t = vt->getElementType().getTypePtr();
1147 }
Mike Stump31feda52009-07-17 01:31:16 +00001148
Craig Topper25542942014-05-20 04:30:07 +00001149 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001150}
Mike Stump31feda52009-07-17 01:31:16 +00001151
Artem Dergachev783a4572018-02-23 22:20:39 +00001152void CFGBuilder::findConstructionContexts(
1153 const ConstructionContext *ContextSoFar, Stmt *Child) {
Artem Dergachev41ffb302018-02-08 22:58:15 +00001154 if (!BuildOpts.AddRichCXXConstructors)
1155 return;
1156 if (!Child)
1157 return;
Artem Dergachev783a4572018-02-23 22:20:39 +00001158 if (auto *CE = dyn_cast<CXXConstructExpr>(Child)) {
1159 if (const ConstructionContext *PreviousContext =
1160 ConstructionContextMap.lookup(CE)) {
1161 // We might have visited this child when we were finding construction
1162 // contexts within its parents.
1163 assert(PreviousContext->isStrictlyMoreSpecificThan(ContextSoFar) &&
1164 "Already within a different construction context!");
1165 } else {
Artem Dergachev5e2f6ba2018-02-23 22:49:25 +00001166 auto Pair =
1167 ConstructionContextMap.insert(std::make_pair(CE, ContextSoFar));
1168 assert(Pair.second && "Already within a construction context!");
Artem Dergachev783a4572018-02-23 22:20:39 +00001169 }
Artem Dergachev08225bb2018-02-10 02:46:14 +00001170 } else if (auto *Cleanups = dyn_cast<ExprWithCleanups>(Child)) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001171 findConstructionContexts(ContextSoFar, Cleanups->getSubExpr());
1172 } else if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Child)) {
1173 findConstructionContexts(
1174 ConstructionContext::create(cfg->getBumpVectorContext(), BTE,
1175 ContextSoFar),
1176 BTE->getSubExpr());
Artem Dergachev41ffb302018-02-08 22:58:15 +00001177 }
1178}
1179
Artem Dergachev783a4572018-02-23 22:20:39 +00001180void CFGBuilder::cleanupConstructionContext(CXXConstructExpr *CE) {
1181 assert(BuildOpts.AddRichCXXConstructors &&
1182 "We should not be managing construction contexts!");
1183 assert(ConstructionContextMap.count(CE) &&
Artem Dergachev41ffb302018-02-08 22:58:15 +00001184 "Cannot exit construction context without the context!");
Artem Dergachev783a4572018-02-23 22:20:39 +00001185 ConstructionContextMap.erase(CE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00001186}
1187
1188
Mike Stump31feda52009-07-17 01:31:16 +00001189/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1190/// arbitrary statement. Examples include a single expression or a function
1191/// body (compound statement). The ownership of the returned CFG is
1192/// transferred to the caller. If CFG construction fails, this method returns
1193/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001194std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001195 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001196 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001197 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001198
Mike Stump31feda52009-07-17 01:31:16 +00001199 // Create an empty block that will serve as the exit block for the CFG. Since
1200 // this is the first block added to the CFG, it will be implicitly registered
1201 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001202 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001203 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001204 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001205
Matthias Gehre351c2182017-07-12 07:04:19 +00001206 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1207 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1208
Marcin Swiderski20b88732010-10-05 05:37:00 +00001209 if (BuildOpts.AddImplicitDtors)
1210 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1211 addImplicitDtorsForDestructor(DD);
1212
Ted Kremenek9aae5132007-08-23 21:42:29 +00001213 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001214 CFGBlock *B = addStmt(Statement);
1215
1216 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001217 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001218
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001219 // For C++ constructor add initializers to CFG.
1220 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001221 for (auto *I : llvm::reverse(CD->inits())) {
1222 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001223 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001224 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001225 }
1226 }
1227
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001228 if (B)
1229 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001230
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001231 // Backpatch the gotos whose label -> block mappings we didn't know when we
1232 // encountered them.
1233 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1234 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001235
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001236 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001237 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001238 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001239
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001240 // If there is no target for the goto, then we are looking at an
1241 // incomplete AST. Handle this by not registering a successor.
1242 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001243
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001244 JumpTarget JT = LI->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00001245 prependAutomaticObjLifetimeWithTerminator(B, I->scopePosition,
1246 JT.scopePosition);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001247 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1248 JT.scopePosition);
1249 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001250 }
1251
1252 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001253 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001254 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1255 E = AddressTakenLabels.end(); I != E; ++I ) {
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001256 // Lookup the target block.
1257 LabelMapTy::iterator LI = LabelMap.find(*I);
1258
1259 // If there is no target block that contains label, then we are looking
1260 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001261 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001262
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001263 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001264 }
Mike Stump31feda52009-07-17 01:31:16 +00001265
Mike Stump31feda52009-07-17 01:31:16 +00001266 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001267 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001268
Artem Dergachev783a4572018-02-23 22:20:39 +00001269 if (BuildOpts.AddRichCXXConstructors)
1270 assert(ConstructionContextMap.empty() &&
1271 "Not all construction contexts were cleaned up!");
1272
David Blaikiee90195c2014-08-29 18:53:26 +00001273 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001274}
Mike Stump31feda52009-07-17 01:31:16 +00001275
Ted Kremenek9aae5132007-08-23 21:42:29 +00001276/// createBlock - Used to lazily create blocks that are connected
1277/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001278CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1279 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001280 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001281 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001282 return B;
1283}
Mike Stump31feda52009-07-17 01:31:16 +00001284
Chandler Carrutha70991b2011-09-13 09:13:49 +00001285/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1286/// CFG. It is *not* connected to the current (global) successor, and instead
1287/// directly tied to the exit block in order to be reachable.
1288CFGBlock *CFGBuilder::createNoReturnBlock() {
1289 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001290 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001291 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001292 return B;
1293}
1294
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001295/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001296CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001297 if (!BuildOpts.AddInitializers)
1298 return Block;
1299
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001300 bool HasTemporaries = false;
1301
1302 // Destructors of temporaries in initialization expression should be called
1303 // after initialization finishes.
1304 Expr *Init = I->getInit();
1305 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001306 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001307
Jordan Rose6d671cc2012-09-05 22:55:23 +00001308 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001309 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001310 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001311 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1312 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001313 }
1314 }
1315
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001316 autoCreateBlock();
1317 appendInitializer(Block, I);
1318
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001319 if (Init) {
Artem Dergachev783a4572018-02-23 22:20:39 +00001320 findConstructionContexts(
1321 ConstructionContext::create(cfg->getBumpVectorContext(), I),
1322 Init);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00001323
Ted Kremenek8219b822010-12-16 07:46:53 +00001324 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001325 // For expression with temporaries go directly to subexpression to omit
1326 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001327 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1328 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001329 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1330 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1331 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1332 // may cause the same Expr to appear more than once in the CFG. Doing it
1333 // here is safe because there's only one initializer per field.
1334 autoCreateBlock();
1335 appendStmt(Block, Default);
1336 if (Stmt *Child = Default->getExpr())
1337 if (CFGBlock *R = Visit(Child))
1338 Block = R;
1339 return Block;
1340 }
1341 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001342 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001343 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001344
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001345 return Block;
1346}
1347
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001348/// \brief Retrieve the type of the temporary object whose lifetime was
1349/// extended by a local reference with the given initializer.
1350static QualType getReferenceInitTemporaryType(ASTContext &Context,
Richard Smithb8c0f552016-12-09 18:49:13 +00001351 const Expr *Init,
1352 bool *FoundMTE = nullptr) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001353 while (true) {
1354 // Skip parentheses.
1355 Init = Init->IgnoreParens();
1356
1357 // Skip through cleanups.
1358 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1359 Init = EWC->getSubExpr();
1360 continue;
1361 }
1362
1363 // Skip through the temporary-materialization expression.
1364 if (const MaterializeTemporaryExpr *MTE
1365 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1366 Init = MTE->GetTemporaryExpr();
Richard Smithb8c0f552016-12-09 18:49:13 +00001367 if (FoundMTE)
1368 *FoundMTE = true;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001369 continue;
1370 }
1371
1372 // Skip derived-to-base and no-op casts.
1373 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1374 if ((CE->getCastKind() == CK_DerivedToBase ||
1375 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1376 CE->getCastKind() == CK_NoOp) &&
1377 Init->getType()->isRecordType()) {
1378 Init = CE->getSubExpr();
1379 continue;
1380 }
1381 }
1382
1383 // Skip member accesses into rvalues.
1384 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1385 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1386 Init = ME->getBase();
1387 continue;
1388 }
1389 }
1390
1391 break;
1392 }
1393
1394 return Init->getType();
1395}
Matthias Gehre351c2182017-07-12 07:04:19 +00001396
Peter Szecsi999a25f2017-08-19 11:19:16 +00001397// TODO: Support adding LoopExit element to the CFG in case where the loop is
1398// ended by ReturnStmt, GotoStmt or ThrowExpr.
1399void CFGBuilder::addLoopExit(const Stmt *LoopStmt){
1400 if(!BuildOpts.AddLoopExit)
1401 return;
1402 autoCreateBlock();
1403 appendLoopExit(Block, LoopStmt);
1404}
1405
Matthias Gehre351c2182017-07-12 07:04:19 +00001406void CFGBuilder::addAutomaticObjHandling(LocalScope::const_iterator B,
1407 LocalScope::const_iterator E,
1408 Stmt *S) {
1409 if (BuildOpts.AddImplicitDtors)
1410 addAutomaticObjDtors(B, E, S);
1411 if (BuildOpts.AddLifetime)
1412 addLifetimeEnds(B, E, S);
1413}
1414
1415/// Add to current block automatic objects that leave the scope.
1416void CFGBuilder::addLifetimeEnds(LocalScope::const_iterator B,
1417 LocalScope::const_iterator E, Stmt *S) {
1418 if (!BuildOpts.AddLifetime)
1419 return;
1420
1421 if (B == E)
1422 return;
1423
1424 // To go from B to E, one first goes up the scopes from B to P
1425 // then sideways in one scope from P to P' and then down
1426 // the scopes from P' to E.
1427 // The lifetime of all objects between B and P end.
1428 LocalScope::const_iterator P = B.shared_parent(E);
1429 int dist = B.distance(P);
1430 if (dist <= 0)
1431 return;
1432
1433 // We need to perform the scope leaving in reverse order
1434 SmallVector<VarDecl *, 10> DeclsTrivial;
1435 SmallVector<VarDecl *, 10> DeclsNonTrivial;
1436 DeclsTrivial.reserve(dist);
1437 DeclsNonTrivial.reserve(dist);
1438
1439 for (LocalScope::const_iterator I = B; I != P; ++I)
1440 if (hasTrivialDestructor(*I))
1441 DeclsTrivial.push_back(*I);
1442 else
1443 DeclsNonTrivial.push_back(*I);
1444
1445 autoCreateBlock();
1446 // object with trivial destructor end their lifetime last (when storage
1447 // duration ends)
1448 for (SmallVectorImpl<VarDecl *>::reverse_iterator I = DeclsTrivial.rbegin(),
1449 E = DeclsTrivial.rend();
1450 I != E; ++I)
1451 appendLifetimeEnds(Block, *I, S);
1452
1453 for (SmallVectorImpl<VarDecl *>::reverse_iterator
1454 I = DeclsNonTrivial.rbegin(),
1455 E = DeclsNonTrivial.rend();
1456 I != E; ++I)
1457 appendLifetimeEnds(Block, *I, S);
1458}
1459
Marcin Swiderski5e415732010-09-30 23:05:00 +00001460/// addAutomaticObjDtors - Add to current block automatic objects destructors
1461/// for objects in range of local scope positions. Use S as trigger statement
1462/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001463void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001464 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001465 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001466 return;
1467
Marcin Swiderski5e415732010-09-30 23:05:00 +00001468 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001469 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001470
Chandler Carruthad747252011-09-13 06:09:01 +00001471 // We need to append the destructors in reverse order, but any one of them
1472 // may be a no-return destructor which changes the CFG. As a result, buffer
1473 // this sequence up and replay them in reverse order when appending onto the
1474 // CFGBlock(s).
1475 SmallVector<VarDecl*, 10> Decls;
1476 Decls.reserve(B.distance(E));
1477 for (LocalScope::const_iterator I = B; I != E; ++I)
1478 Decls.push_back(*I);
1479
1480 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1481 E = Decls.rend();
1482 I != E; ++I) {
1483 // If this destructor is marked as a no-return destructor, we need to
1484 // create a new block for the destructor which does not have as a successor
1485 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001486 QualType Ty = (*I)->getType();
1487 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001488 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001489 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001490 Ty = Context->getBaseElementType(Ty);
1491
Richard Trieu95a192a2015-05-28 00:14:02 +00001492 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001493 Block = createNoReturnBlock();
1494 else
Chandler Carruthad747252011-09-13 06:09:01 +00001495 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001496
1497 appendAutomaticObjDtor(Block, *I, S);
1498 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001499}
1500
Marcin Swiderski20b88732010-10-05 05:37:00 +00001501/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1502/// base and member objects in destructor.
1503void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
Eugene Zelenko38c70522017-12-07 21:55:09 +00001504 assert(BuildOpts.AddImplicitDtors &&
1505 "Can be called only when dtors should be added");
Marcin Swiderski20b88732010-10-05 05:37:00 +00001506 const CXXRecordDecl *RD = DD->getParent();
1507
1508 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001509 for (const auto &VI : RD->vbases()) {
1510 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001511 if (!CD->hasTrivialDestructor()) {
1512 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001513 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001514 }
1515 }
1516
1517 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001518 for (const auto &BI : RD->bases()) {
1519 if (!BI.isVirtual()) {
1520 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001521 if (!CD->hasTrivialDestructor()) {
1522 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001523 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001524 }
1525 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001526 }
1527
1528 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001529 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001530 // Check for constant size array. Set type to array element type.
1531 QualType QT = FI->getType();
1532 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1533 if (AT->getSize() == 0)
1534 continue;
1535 QT = AT->getElementType();
1536 }
1537
1538 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001539 if (!CD->hasTrivialDestructor()) {
1540 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001541 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001542 }
1543 }
1544}
1545
Marcin Swiderski5e415732010-09-30 23:05:00 +00001546/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1547/// way return valid LocalScope object.
1548LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001549 if (Scope)
1550 return Scope;
1551 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1552 return new (alloc.Allocate<LocalScope>())
1553 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001554}
1555
1556/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001557/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001558void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001559 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001560 return;
1561
Craig Topper25542942014-05-20 04:30:07 +00001562 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001563
1564 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001565 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001566 for (auto *BI : CS->body()) {
1567 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001568 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001569 Scope = addLocalScopeForDeclStmt(DS, Scope);
1570 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001571 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001572 }
1573
1574 // For any other statement scope will be implicit and as such will be
1575 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001576 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001577 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001578}
1579
1580/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1581/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001582LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001583 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001584 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001585 return Scope;
1586
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001587 for (auto *DI : DS->decls())
1588 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001589 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001590 return Scope;
1591}
1592
Matthias Gehre351c2182017-07-12 07:04:19 +00001593bool CFGBuilder::hasTrivialDestructor(VarDecl *VD) {
1594 // Check for const references bound to temporary. Set type to pointee.
1595 QualType QT = VD->getType();
1596 if (QT.getTypePtr()->isReferenceType()) {
1597 // Attempt to determine whether this declaration lifetime-extends a
1598 // temporary.
1599 //
1600 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1601 // temporaries, and a single declaration can extend multiple temporaries.
1602 // We should look at the storage duration on each nested
1603 // MaterializeTemporaryExpr instead.
1604
1605 const Expr *Init = VD->getInit();
1606 if (!Init)
1607 return true;
1608
1609 // Lifetime-extending a temporary.
1610 bool FoundMTE = false;
1611 QT = getReferenceInitTemporaryType(*Context, Init, &FoundMTE);
1612 if (!FoundMTE)
1613 return true;
1614 }
1615
1616 // Check for constant size array. Set type to array element type.
1617 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1618 if (AT->getSize() == 0)
1619 return true;
1620 QT = AT->getElementType();
1621 }
1622
1623 // Check if type is a C++ class with non-trivial destructor.
1624 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
1625 return !CD->hasDefinition() || CD->hasTrivialDestructor();
1626 return true;
1627}
1628
Marcin Swiderski5e415732010-09-30 23:05:00 +00001629/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1630/// create add scope for automatic objects and temporary objects bound to
1631/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001632LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001633 LocalScope* Scope) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001634 assert(!(BuildOpts.AddImplicitDtors && BuildOpts.AddLifetime) &&
1635 "AddImplicitDtors and AddLifetime cannot be used at the same time");
1636 if (!BuildOpts.AddImplicitDtors && !BuildOpts.AddLifetime)
Marcin Swiderski5e415732010-09-30 23:05:00 +00001637 return Scope;
1638
1639 // Check if variable is local.
1640 switch (VD->getStorageClass()) {
1641 case SC_None:
1642 case SC_Auto:
1643 case SC_Register:
1644 break;
1645 default: return Scope;
1646 }
1647
Matthias Gehre351c2182017-07-12 07:04:19 +00001648 if (BuildOpts.AddImplicitDtors) {
1649 if (!hasTrivialDestructor(VD)) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001650 // Add the variable to scope
1651 Scope = createOrReuseLocalScope(Scope);
1652 Scope->addVar(VD);
1653 ScopePos = Scope->begin();
1654 }
Matthias Gehre351c2182017-07-12 07:04:19 +00001655 return Scope;
1656 }
1657
1658 assert(BuildOpts.AddLifetime);
1659 // Add the variable to scope
1660 Scope = createOrReuseLocalScope(Scope);
1661 Scope->addVar(VD);
1662 ScopePos = Scope->begin();
Marcin Swiderski5e415732010-09-30 23:05:00 +00001663 return Scope;
1664}
1665
1666/// addLocalScopeAndDtors - For given statement add local scope for it and
1667/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001668void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001669 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001670 addLocalScopeForStmt(S);
Matthias Gehre351c2182017-07-12 07:04:19 +00001671 addAutomaticObjHandling(ScopePos, scopeBeginPos, S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001672}
1673
Marcin Swiderski321a7072010-09-30 22:54:37 +00001674/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1675/// variables with automatic storage duration to CFGBlock's elements vector.
1676/// Elements will be prepended to physical beginning of the vector which
1677/// happens to be logical end. Use blocks terminator as statement that specifies
1678/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001679/// FIXME: This mechanism for adding automatic destructors doesn't handle
1680/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001681void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001682 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Matthias Gehre351c2182017-07-12 07:04:19 +00001683 if (!BuildOpts.AddImplicitDtors)
1684 return;
Chandler Carruthad747252011-09-13 06:09:01 +00001685 BumpVectorContext &C = cfg->getBumpVectorContext();
1686 CFGBlock::iterator InsertPos
1687 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1688 for (LocalScope::const_iterator I = B; I != E; ++I)
1689 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1690 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001691}
1692
Matthias Gehre351c2182017-07-12 07:04:19 +00001693/// prependAutomaticObjLifetimeWithTerminator - Prepend lifetime CFGElements for
1694/// variables with automatic storage duration to CFGBlock's elements vector.
1695/// Elements will be prepended to physical beginning of the vector which
1696/// happens to be logical end. Use blocks terminator as statement that specifies
1697/// where lifetime ends.
1698void CFGBuilder::prependAutomaticObjLifetimeWithTerminator(
1699 CFGBlock *Blk, LocalScope::const_iterator B, LocalScope::const_iterator E) {
1700 if (!BuildOpts.AddLifetime)
1701 return;
1702 BumpVectorContext &C = cfg->getBumpVectorContext();
1703 CFGBlock::iterator InsertPos =
1704 Blk->beginLifetimeEndsInsert(Blk->end(), B.distance(E), C);
1705 for (LocalScope::const_iterator I = B; I != E; ++I)
1706 InsertPos = Blk->insertLifetimeEnds(InsertPos, *I, Blk->getTerminator());
1707}
Eugene Zelenko38c70522017-12-07 21:55:09 +00001708
Ted Kremenek93668002009-07-17 22:18:43 +00001709/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001710/// blocks for ternary operators, &&, and ||. We also process "," and
1711/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001712CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001713 if (!S) {
1714 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001715 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001716 }
Jordy Rose17347372011-06-10 08:49:37 +00001717
1718 if (Expr *E = dyn_cast<Expr>(S))
1719 S = E->IgnoreParens();
1720
Ted Kremenek93668002009-07-17 22:18:43 +00001721 switch (S->getStmtClass()) {
1722 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001723 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001724
1725 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001726 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001727
John McCallc07a0c72011-02-17 10:25:35 +00001728 case Stmt::BinaryConditionalOperatorClass:
1729 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1730
Ted Kremenek93668002009-07-17 22:18:43 +00001731 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001732 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Ted Kremenek93668002009-07-17 22:18:43 +00001734 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00001735 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001736
Ted Kremenek93668002009-07-17 22:18:43 +00001737 case Stmt::BreakStmtClass:
1738 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001739
Ted Kremenek93668002009-07-17 22:18:43 +00001740 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001741 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001742 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001743 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001744 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001745
Ted Kremenek93668002009-07-17 22:18:43 +00001746 case Stmt::CaseStmtClass:
1747 return VisitCaseStmt(cast<CaseStmt>(S));
1748
1749 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001750 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001751
Ted Kremenek93668002009-07-17 22:18:43 +00001752 case Stmt::CompoundStmtClass:
1753 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001754
Ted Kremenek93668002009-07-17 22:18:43 +00001755 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001756 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001757
Ted Kremenek93668002009-07-17 22:18:43 +00001758 case Stmt::ContinueStmtClass:
1759 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001760
Ted Kremenekb27378c2010-01-19 20:40:33 +00001761 case Stmt::CXXCatchStmtClass:
1762 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1763
John McCall5d413782010-12-06 08:20:24 +00001764 case Stmt::ExprWithCleanupsClass:
1765 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001766
Jordan Rosee5d53932012-08-23 18:10:53 +00001767 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001768 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001769 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1770 // called function's declaration, not by the caller. If we simply add
1771 // this expression to the CFG, we could end up with the same Expr
1772 // appearing multiple times.
1773 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001774 //
1775 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1776 // expression to be used in the same function (through aggregate
1777 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001778 return VisitStmt(S, asc);
1779
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001780 case Stmt::CXXBindTemporaryExprClass:
1781 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1782
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001783 case Stmt::CXXConstructExprClass:
1784 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1785
Jordan Rosec9176072014-01-13 17:59:19 +00001786 case Stmt::CXXNewExprClass:
1787 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1788
Jordan Rosed2f40792013-09-03 17:00:57 +00001789 case Stmt::CXXDeleteExprClass:
1790 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1791
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001792 case Stmt::CXXFunctionalCastExprClass:
1793 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1794
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001795 case Stmt::CXXTemporaryObjectExprClass:
1796 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1797
Ted Kremenekb27378c2010-01-19 20:40:33 +00001798 case Stmt::CXXThrowExprClass:
1799 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001800
Ted Kremenekb27378c2010-01-19 20:40:33 +00001801 case Stmt::CXXTryStmtClass:
1802 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001803
Richard Smith02e85f32011-04-14 22:09:26 +00001804 case Stmt::CXXForRangeStmtClass:
1805 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1806
Ted Kremenek93668002009-07-17 22:18:43 +00001807 case Stmt::DeclStmtClass:
1808 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001809
Ted Kremenek93668002009-07-17 22:18:43 +00001810 case Stmt::DefaultStmtClass:
1811 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001812
Ted Kremenek93668002009-07-17 22:18:43 +00001813 case Stmt::DoStmtClass:
1814 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001815
Ted Kremenek93668002009-07-17 22:18:43 +00001816 case Stmt::ForStmtClass:
1817 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001818
Ted Kremenek93668002009-07-17 22:18:43 +00001819 case Stmt::GotoStmtClass:
1820 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001821
Ted Kremenek93668002009-07-17 22:18:43 +00001822 case Stmt::IfStmtClass:
1823 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001824
Ted Kremenek8219b822010-12-16 07:46:53 +00001825 case Stmt::ImplicitCastExprClass:
1826 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001827
Ted Kremenek93668002009-07-17 22:18:43 +00001828 case Stmt::IndirectGotoStmtClass:
1829 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001830
Ted Kremenek93668002009-07-17 22:18:43 +00001831 case Stmt::LabelStmtClass:
1832 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001833
Ted Kremenekda76a942012-04-12 20:34:52 +00001834 case Stmt::LambdaExprClass:
1835 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1836
Ted Kremenek5868ec62010-04-11 17:02:10 +00001837 case Stmt::MemberExprClass:
1838 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1839
Ted Kremenek04268232011-11-05 00:10:15 +00001840 case Stmt::NullStmtClass:
1841 return Block;
1842
Ted Kremenek93668002009-07-17 22:18:43 +00001843 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001844 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1845
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001846 case Stmt::ObjCAutoreleasePoolStmtClass:
1847 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1848
Ted Kremenek93668002009-07-17 22:18:43 +00001849 case Stmt::ObjCAtSynchronizedStmtClass:
1850 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001851
Ted Kremenek93668002009-07-17 22:18:43 +00001852 case Stmt::ObjCAtThrowStmtClass:
1853 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001854
Ted Kremenek93668002009-07-17 22:18:43 +00001855 case Stmt::ObjCAtTryStmtClass:
1856 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001857
Ted Kremenek93668002009-07-17 22:18:43 +00001858 case Stmt::ObjCForCollectionStmtClass:
1859 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001860
Ted Kremenek04268232011-11-05 00:10:15 +00001861 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001862 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001863
John McCallfe96e0b2011-11-06 09:01:30 +00001864 case Stmt::PseudoObjectExprClass:
1865 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1866
Ted Kremenek93668002009-07-17 22:18:43 +00001867 case Stmt::ReturnStmtClass:
1868 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001869
Nico Weber699670e2017-08-23 15:33:16 +00001870 case Stmt::SEHExceptStmtClass:
1871 return VisitSEHExceptStmt(cast<SEHExceptStmt>(S));
1872
1873 case Stmt::SEHFinallyStmtClass:
1874 return VisitSEHFinallyStmt(cast<SEHFinallyStmt>(S));
1875
1876 case Stmt::SEHLeaveStmtClass:
1877 return VisitSEHLeaveStmt(cast<SEHLeaveStmt>(S));
1878
1879 case Stmt::SEHTryStmtClass:
1880 return VisitSEHTryStmt(cast<SEHTryStmt>(S));
1881
Peter Collingbournee190dee2011-03-11 19:24:49 +00001882 case Stmt::UnaryExprOrTypeTraitExprClass:
1883 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1884 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001885
Ted Kremenek93668002009-07-17 22:18:43 +00001886 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001887 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001888
Ted Kremenek93668002009-07-17 22:18:43 +00001889 case Stmt::SwitchStmtClass:
1890 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001891
Zhanyong Wan6dace612010-11-22 08:45:56 +00001892 case Stmt::UnaryOperatorClass:
1893 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1894
Ted Kremenek93668002009-07-17 22:18:43 +00001895 case Stmt::WhileStmtClass:
1896 return VisitWhileStmt(cast<WhileStmt>(S));
1897 }
1898}
Mike Stump11289f42009-09-09 15:08:12 +00001899
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001900CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001901 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001902 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001903 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Ted Kremenek93668002009-07-17 22:18:43 +00001906 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001907}
Mike Stump31feda52009-07-17 01:31:16 +00001908
Ted Kremenek93668002009-07-17 22:18:43 +00001909/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001910CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1911 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001912
Ted Kremenek8ae67872013-02-05 22:00:19 +00001913 // Visit the children in their reverse order so that they appear in
1914 // left-to-right (natural) order in the CFG.
1915 reverse_children RChildren(S);
1916 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1917 I != E; ++I) {
1918 if (Stmt *Child = *I)
1919 if (CFGBlock *R = Visit(Child))
1920 B = R;
1921 }
1922 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001923}
Mike Stump11289f42009-09-09 15:08:12 +00001924
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001925CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1926 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001927 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001928
Ted Kremenek7c58d352011-03-10 01:14:11 +00001929 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001930 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001931 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001932 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001933
Ted Kremenek9aae5132007-08-23 21:42:29 +00001934 return Block;
1935}
Mike Stump11289f42009-09-09 15:08:12 +00001936
Zhanyong Wan6dace612010-11-22 08:45:56 +00001937CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001938 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001939 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001940 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001941 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001942 }
1943
Ted Kremenek8219b822010-12-16 07:46:53 +00001944 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001945}
1946
Ted Kremeneka16436f2012-07-14 05:04:06 +00001947CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1948 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1949 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Ted Kremeneka16436f2012-07-14 05:04:06 +00001951 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001952 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001953
Craig Topper25542942014-05-20 04:30:07 +00001954 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1955 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001956}
1957
1958std::pair<CFGBlock*, CFGBlock*>
1959CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1960 Stmt *Term,
1961 CFGBlock *TrueBlock,
1962 CFGBlock *FalseBlock) {
Ted Kremenekb50e7162012-07-14 05:04:10 +00001963 // Introspect the RHS. If it is a nested logical operation, we recursively
1964 // build the CFG using this function. Otherwise, resort to default
1965 // CFG construction behavior.
1966 Expr *RHS = B->getRHS()->IgnoreParens();
1967 CFGBlock *RHSBlock, *ExitBlock;
1968
1969 do {
1970 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1971 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001972 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001973 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1974 break;
1975 }
1976
1977 // The RHS is not a nested logical operation. Don't push the terminator
1978 // down further, but instead visit RHS and construct the respective
1979 // pieces of the CFG, and link up the RHSBlock with the terminator
1980 // we have been provided.
1981 ExitBlock = RHSBlock = createBlock(false);
1982
Richard Trieu6a6af522017-01-04 00:46:30 +00001983 // Even though KnownVal is only used in the else branch of the next
1984 // conditional, tryEvaluateBool performs additional checking on the
1985 // Expr, so it should be called unconditionally.
1986 TryResult KnownVal = tryEvaluateBool(RHS);
1987 if (!KnownVal.isKnown())
1988 KnownVal = tryEvaluateBool(B);
1989
Ted Kremenekb50e7162012-07-14 05:04:10 +00001990 if (!Term) {
1991 assert(TrueBlock == FalseBlock);
1992 addSuccessor(RHSBlock, TrueBlock);
1993 }
1994 else {
1995 RHSBlock->setTerminator(Term);
Ted Kremenek782f0032014-03-07 02:25:53 +00001996 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1997 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001998 }
1999
2000 Block = RHSBlock;
2001 RHSBlock = addStmt(RHS);
2002 }
2003 while (false);
2004
2005 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002006 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002007
2008 // Generate the blocks for evaluating the LHS.
2009 Expr *LHS = B->getLHS()->IgnoreParens();
2010
2011 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
2012 if (B_LHS->isLogicalOp()) {
2013 if (B->getOpcode() == BO_LOr)
2014 FalseBlock = RHSBlock;
2015 else
2016 TrueBlock = RHSBlock;
2017
2018 // For the LHS, treat 'B' as the terminator that we want to sink
2019 // into the nested branch. The RHS always gets the top-most
2020 // terminator.
2021 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
2022 }
2023
2024 // Create the block evaluating the LHS.
2025 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00002026 CFGBlock *LHSBlock = createBlock(false);
2027 LHSBlock->setTerminator(B);
2028
Ted Kremeneka16436f2012-07-14 05:04:06 +00002029 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002030 CFGBlock *EntryLHSBlock = addStmt(LHS);
2031
2032 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002033 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002034
2035 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002036 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002037
2038 // Now link the LHSBlock with RHSBlock.
2039 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00002040 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
2041 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002042 } else {
2043 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00002044 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
2045 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00002046 }
2047
Ted Kremenekb50e7162012-07-14 05:04:10 +00002048 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00002049}
2050
2051CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
2052 AddStmtChoice asc) {
2053 // && or ||
2054 if (B->isLogicalOp())
2055 return VisitLogicalOperator(B);
2056
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002057 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00002058 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002059 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00002060 addStmt(B->getRHS());
2061 return addStmt(B->getLHS());
2062 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002063
2064 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002065 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002066 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002067 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002068 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002069 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00002070 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00002071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Ted Kremenek7c58d352011-03-10 01:14:11 +00002073 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00002074 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002075 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00002076 }
2077
Zhongxing Xud95ccd52010-10-27 03:23:10 +00002078 CFGBlock *RBlock = Visit(B->getRHS());
2079 CFGBlock *LBlock = Visit(B->getLHS());
2080 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
2081 // containing a DoStmt, and the LHS doesn't create a new block, then we should
2082 // return RBlock. Otherwise we'll incorrectly return NULL.
2083 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00002084}
2085
Ted Kremeneke2499842012-04-12 20:03:44 +00002086CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002087 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00002088 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002089 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00002090 }
2091 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002092}
2093
Ted Kremenek93668002009-07-17 22:18:43 +00002094CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
2095 // "break" is a control-flow statement. Thus we stop processing the current
2096 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002097 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002098 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002099
Ted Kremenek93668002009-07-17 22:18:43 +00002100 // Now create a new block that ends with the break statement.
2101 Block = createBlock(false);
2102 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Ted Kremenek93668002009-07-17 22:18:43 +00002104 // If there is no target for the break, then we are looking at an incomplete
2105 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002106 if (BreakJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00002107 addAutomaticObjHandling(ScopePos, BreakJumpTarget.scopePosition, B);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002108 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002109 } else
Ted Kremenek93668002009-07-17 22:18:43 +00002110 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenek9aae5132007-08-23 21:42:29 +00002112 return Block;
2113}
Mike Stump11289f42009-09-09 15:08:12 +00002114
Sebastian Redl31ad7542011-03-13 17:09:40 +00002115static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00002116 QualType Ty = E->getType();
2117 if (Ty->isFunctionPointerType())
2118 Ty = Ty->getAs<PointerType>()->getPointeeType();
2119 else if (Ty->isBlockPointerType())
2120 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002121
Mike Stump04c68512010-01-21 15:20:48 +00002122 const FunctionType *FT = Ty->getAs<FunctionType>();
2123 if (FT) {
2124 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00002125 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00002126 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00002127 return false;
2128 }
2129 return true;
2130}
2131
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002132CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00002133 // Compute the callee type.
2134 QualType calleeType = C->getCallee()->getType();
2135 if (calleeType == Context->BoundMemberTy) {
2136 QualType boundType = Expr::findBoundMemberType(C->getCallee());
2137
2138 // We should only get a null bound type if processing a dependent
2139 // CFG. Recover by assuming nothing.
2140 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00002141 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002142
John McCallc67067f2011-05-11 07:19:11 +00002143 // If this is a call to a no-return function, this stops the block here.
2144 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
2145
Mike Stump04c68512010-01-21 15:20:48 +00002146 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00002147
2148 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002149 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00002150 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00002151 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00002152 }
2153
Jordan Rose5374c072013-08-19 16:27:28 +00002154 // If this is a call to a builtin function, it might not actually evaluate
2155 // its arguments. Don't add them to the CFG if this is the case.
2156 bool OmitArguments = false;
2157
Mike Stump92244b02010-01-19 22:00:14 +00002158 if (FunctionDecl *FD = C->getDirectCallee()) {
Nico Weber758fbac2018-02-13 21:31:47 +00002159 if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context))
Mike Stump8c5d7992009-07-25 21:26:53 +00002160 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00002161 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00002162 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00002163 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
2164 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00002165 }
Mike Stump8c5d7992009-07-25 21:26:53 +00002166
Sebastian Redl31ad7542011-03-13 17:09:40 +00002167 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00002168 AddEHEdge = false;
2169
Jordan Rose5374c072013-08-19 16:27:28 +00002170 if (OmitArguments) {
2171 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
2172 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
2173 autoCreateBlock();
2174 appendStmt(Block, C);
2175 return Visit(C->getCallee());
2176 }
2177
2178 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002179 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00002180 }
Mike Stump11289f42009-09-09 15:08:12 +00002181
Mike Stump92244b02010-01-19 22:00:14 +00002182 if (Block) {
2183 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002184 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002185 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00002186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chandler Carrutha70991b2011-09-13 09:13:49 +00002188 if (NoReturn)
2189 Block = createNoReturnBlock();
2190 else
2191 Block = createBlock();
2192
Ted Kremenek2866bab2011-03-10 01:14:08 +00002193 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00002194
Mike Stump04c68512010-01-21 15:20:48 +00002195 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00002196 // Add exceptional edges.
2197 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002198 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00002199 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002200 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00002201 }
Mike Stump11289f42009-09-09 15:08:12 +00002202
Mike Stump8c5d7992009-07-25 21:26:53 +00002203 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00002204}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002205
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002206CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
2207 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002208 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002209 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002210 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002211 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002213 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00002214 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002215 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002216 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002217 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002218 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002219
Ted Kremenek21822592009-07-17 18:20:32 +00002220 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002221 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002222 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002223 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002224 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002225
Ted Kremenek21822592009-07-17 18:20:32 +00002226 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00002227 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002228 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00002229 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
2230 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00002231 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00002232 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00002233}
Mike Stump11289f42009-09-09 15:08:12 +00002234
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002235CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00002236 LocalScope::const_iterator scopeBeginPos = ScopePos;
Matthias Gehre351c2182017-07-12 07:04:19 +00002237 addLocalScopeForStmt(C);
2238
Matthias Gehre09a134e2015-11-14 00:36:50 +00002239 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00002240 // If the body ends with a ReturnStmt, the dtors will be added in
2241 // VisitReturnStmt.
Matthias Gehre351c2182017-07-12 07:04:19 +00002242 addAutomaticObjHandling(ScopePos, scopeBeginPos, C);
Matthias Gehre09a134e2015-11-14 00:36:50 +00002243 }
2244
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002245 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002246
2247 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
2248 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00002249 // If we hit a segment of code just containing ';' (NullStmts), we can
2250 // get a null block back. In such cases, just use the LastBlock
2251 if (CFGBlock *newBlock = addStmt(*I))
2252 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002253
Ted Kremenekce499c22009-08-27 23:16:26 +00002254 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002255 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002256 }
Mike Stump92244b02010-01-19 22:00:14 +00002257
Ted Kremenek93668002009-07-17 22:18:43 +00002258 return LastBlock;
2259}
Mike Stump11289f42009-09-09 15:08:12 +00002260
John McCallc07a0c72011-02-17 10:25:35 +00002261CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002262 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00002263 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00002264 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00002265
Ted Kremenek51d40b02009-07-17 18:15:54 +00002266 // Create the confluence block that will "merge" the results of the ternary
2267 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002268 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002269 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002270 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002271 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00002273 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002274
Ted Kremenek51d40b02009-07-17 18:15:54 +00002275 // Create a block for the LHS expression if there is an LHS expression. A
2276 // GCC extension allows LHS to be NULL, causing the condition to be the
2277 // value that is returned instead.
2278 // e.g: x ?: y is shorthand for: x ? x : y;
2279 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00002280 Block = nullptr;
2281 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00002282 const Expr *trueExpr = C->getTrueExpr();
2283 if (trueExpr != opaqueValue) {
2284 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002285 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002286 return nullptr;
2287 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00002288 }
Ted Kremenekd8138012011-02-24 03:09:15 +00002289 else
2290 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00002291
Ted Kremenek51d40b02009-07-17 18:15:54 +00002292 // Create the block for the RHS expression.
2293 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002294 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002295 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002296 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002297
Richard Smithf676e452012-07-24 21:02:14 +00002298 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2299 if (BinaryOperator *Cond =
2300 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2301 if (Cond->isLogicalOp())
2302 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2303
Ted Kremenek51d40b02009-07-17 18:15:54 +00002304 // Create the block that will contain the condition.
2305 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002306
Mike Stump773582d2009-07-23 23:25:26 +00002307 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002308 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002309 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2310 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002311 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002312 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002313
Ted Kremenekd8138012011-02-24 03:09:15 +00002314 if (opaqueValue) {
2315 // Run the condition expression if it's not trivially expressed in
2316 // terms of the opaque value (or if there is no opaque value).
2317 if (condExpr != opaqueValue)
2318 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002319
Ted Kremenekd8138012011-02-24 03:09:15 +00002320 // Before that, run the common subexpression if there was one.
2321 // At least one of this or the above will be run.
2322 return addStmt(BCO->getCommon());
2323 }
2324
2325 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002326}
2327
Ted Kremenek93668002009-07-17 22:18:43 +00002328CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002329 // Check if the Decl is for an __label__. If so, elide it from the
2330 // CFG entirely.
2331 if (isa<LabelDecl>(*DS->decl_begin()))
2332 return Block;
2333
Ted Kremenek3a601142011-05-24 20:41:31 +00002334 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002335 if (DS->isSingleDecl())
2336 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002337
Craig Topper25542942014-05-20 04:30:07 +00002338 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002339
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002340 // Build an individual DeclStmt for each decl.
2341 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2342 E = DS->decl_rend();
2343 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002344 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
Benjamin Kramerc3f89252016-10-20 14:27:22 +00002345 unsigned A = alignof(DeclStmt) < 8 ? 8 : alignof(DeclStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002346
Ted Kremenek93668002009-07-17 22:18:43 +00002347 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2348 // automatically freed with the CFG.
2349 DeclGroupRef DG(*I);
2350 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002351 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002352 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002353 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002354
Ted Kremenek93668002009-07-17 22:18:43 +00002355 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002356 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002357 }
Mike Stump11289f42009-09-09 15:08:12 +00002358
2359 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002360}
Mike Stump11289f42009-09-09 15:08:12 +00002361
Ted Kremenek93668002009-07-17 22:18:43 +00002362/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002363/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002364CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002365 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002366 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002367
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002368 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002369 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2370 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002371 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002372 }
Mike Stump11289f42009-09-09 15:08:12 +00002373
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002374 bool HasTemporaries = false;
2375
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002376 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002377 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002378
2379 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2380 // For static variables, we need to create a branch to track
2381 // whether or not they are initialized.
2382 if (Block) {
2383 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002384 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002385 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002386 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002387 }
2388 blockAfterStaticInit = Succ;
2389 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002390
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002391 // Destructors of temporaries in initialization expression should be called
2392 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002393 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002394 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002395 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002396
Jordan Rose6d671cc2012-09-05 22:55:23 +00002397 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002398 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002399 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002400 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2401 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002402 }
2403 }
2404
2405 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002406 appendStmt(Block, DS);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002407
Artem Dergachev783a4572018-02-23 22:20:39 +00002408 findConstructionContexts(
2409 ConstructionContext::create(cfg->getBumpVectorContext(), DS),
2410 Init);
Artem Dergachev5fc10332018-02-10 01:55:23 +00002411
Ted Kremenek213d0532012-03-22 05:57:43 +00002412 // Keep track of the last non-null block, as 'Block' can be nulled out
2413 // if the initializer expression is something like a 'while' in a
2414 // statement-expression.
2415 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002416
Ted Kremenek93668002009-07-17 22:18:43 +00002417 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002418 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002419 // For expression with temporaries go directly to subexpression to omit
2420 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002421 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2422 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2423 LastBlock = newBlock;
2424 }
2425 else {
2426 if (CFGBlock *newBlock = Visit(Init))
2427 LastBlock = newBlock;
2428 }
Ted Kremenek93668002009-07-17 22:18:43 +00002429 }
Mike Stump11289f42009-09-09 15:08:12 +00002430
Ted Kremenek93668002009-07-17 22:18:43 +00002431 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002432 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002433 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002434 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2435 LastBlock = newBlock;
2436 }
Mike Stump11289f42009-09-09 15:08:12 +00002437
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002438 // Remove variable from local scope.
2439 if (ScopePos && VD == *ScopePos)
2440 ++ScopePos;
2441
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002442 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002443 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002444 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002445 Block = createBlock(false);
2446 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002447 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002448 addSuccessor(Block, B);
2449 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002450 }
2451
2452 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002453}
2454
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002455CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002456 // We may see an if statement in the middle of a basic block, or it may be the
2457 // first statement we are processing. In either case, we create a new basic
2458 // block. First, we create the blocks for the then...else statements, and
2459 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002460 // middle of a block, we stop processing that block. That block is then the
2461 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002462
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002463 // Save local scope position because in case of condition variable ScopePos
2464 // won't be restored when traversing AST.
2465 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2466
Richard Smitha547eb22016-07-14 00:11:03 +00002467 // Create local scope for C++17 if init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00002468 if (Stmt *Init = I->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00002469 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00002470
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002471 // Create local scope for possible condition variable.
2472 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00002473 if (VarDecl *VD = I->getConditionVariable())
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002474 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00002475
Matthias Gehre351c2182017-07-12 07:04:19 +00002476 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), I);
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002477
Chris Lattner57540c52011-04-15 05:22:18 +00002478 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002479 // block.
2480 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002481 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002482 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002483 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002484 }
Mike Stump31feda52009-07-17 01:31:16 +00002485
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002486 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002487 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002488
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002489 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002490 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002491
Ted Kremenek9aae5132007-08-23 21:42:29 +00002492 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002493 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002494 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002495
2496 // If branch is not a compound statement create implicit scope
2497 // and add destructors.
2498 if (!isa<CompoundStmt>(Else))
2499 addLocalScopeAndDtors(Else);
2500
Ted Kremenek93668002009-07-17 22:18:43 +00002501 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002502
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002503 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2504 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002505 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002506 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002507 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002508 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002509 }
Mike Stump31feda52009-07-17 01:31:16 +00002510
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002511 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002512 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002513 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002514 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002515 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002516 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002517 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002518
2519 // If branch is not a compound statement create implicit scope
2520 // and add destructors.
2521 if (!isa<CompoundStmt>(Then))
2522 addLocalScopeAndDtors(Then);
2523
Ted Kremenek93668002009-07-17 22:18:43 +00002524 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002525
Ted Kremenek1b379512009-04-01 03:52:47 +00002526 if (!ThenBlock) {
2527 // We can reach here if the "then" body has all NullStmts.
2528 // Create an empty block so we can distinguish between true and false
2529 // branches in path-sensitive analyses.
2530 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002531 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002532 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002533 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002534 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002535 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002536 }
2537
Ted Kremenekb50e7162012-07-14 05:04:10 +00002538 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2539 // having these handle the actual control-flow jump. Note that
2540 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2541 // we resort to the old control-flow behavior. This special handling
2542 // removes infeasible paths from the control-flow graph by having the
2543 // control-flow transfer of '&&' or '||' go directly into the then/else
2544 // blocks directly.
Richard Smith509bbd12017-01-13 22:16:41 +00002545 BinaryOperator *Cond =
2546 I->getConditionVariable()
2547 ? nullptr
2548 : dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens());
2549 CFGBlock *LastBlock;
2550 if (Cond && Cond->isLogicalOp())
2551 LastBlock = VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2552 else {
2553 // Now create a new block containing the if statement.
2554 Block = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002555
Richard Smith509bbd12017-01-13 22:16:41 +00002556 // Set the terminator of the new block to the If statement.
2557 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002558
Richard Smith509bbd12017-01-13 22:16:41 +00002559 // See if this is a known constant.
2560 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002561
Richard Smith509bbd12017-01-13 22:16:41 +00002562 // Add the successors. If we know that specific branches are
2563 // unreachable, inform addSuccessor() of that knowledge.
2564 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2565 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump773582d2009-07-23 23:25:26 +00002566
Richard Smith509bbd12017-01-13 22:16:41 +00002567 // Add the condition as the last statement in the new block. This may
2568 // create new blocks as the condition may contain control-flow. Any newly
2569 // created blocks will be pointed to be "Block".
2570 LastBlock = addStmt(I->getCond());
Mike Stump31feda52009-07-17 01:31:16 +00002571
Richard Smith509bbd12017-01-13 22:16:41 +00002572 // If the IfStmt contains a condition variable, add it and its
2573 // initializer to the CFG.
2574 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2575 autoCreateBlock();
2576 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
2577 }
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002578 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002579
Richard Smitha547eb22016-07-14 00:11:03 +00002580 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2581 if (Stmt *Init = I->getInit()) {
2582 autoCreateBlock();
2583 LastBlock = addStmt(Init);
2584 }
2585
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002586 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002587}
Mike Stump31feda52009-07-17 01:31:16 +00002588
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002589CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002590 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002591 //
Mike Stump31feda52009-07-17 01:31:16 +00002592 // NOTE: If a "return" appears in the middle of a block, this means that the
2593 // code afterwards is DEAD (unreachable). We still keep a basic block
2594 // for that code; a simple "mark-and-sweep" from the entry block will be
2595 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002596
2597 // Create the new block.
2598 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002599
Matthias Gehre351c2182017-07-12 07:04:19 +00002600 addAutomaticObjHandling(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002601
Artem Dergachev783a4572018-02-23 22:20:39 +00002602 findConstructionContexts(
2603 ConstructionContext::create(cfg->getBumpVectorContext(), R),
2604 R->getRetValue());
Artem Dergachev9ac2e112018-02-12 22:36:36 +00002605
Pavel Labath921e7652013-09-06 08:12:48 +00002606 // If the one of the destructors does not return, we already have the Exit
2607 // block as a successor.
2608 if (!Block->hasNoReturnElement())
2609 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002610
2611 // Add the return statement to the block. This may create new blocks if R
2612 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002613 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002614}
2615
Nico Weber699670e2017-08-23 15:33:16 +00002616CFGBlock *CFGBuilder::VisitSEHExceptStmt(SEHExceptStmt *ES) {
2617 // SEHExceptStmt are treated like labels, so they are the first statement in a
2618 // block.
2619
2620 // Save local scope position because in case of exception variable ScopePos
2621 // won't be restored when traversing AST.
2622 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2623
2624 addStmt(ES->getBlock());
2625 CFGBlock *SEHExceptBlock = Block;
2626 if (!SEHExceptBlock)
2627 SEHExceptBlock = createBlock();
2628
2629 appendStmt(SEHExceptBlock, ES);
2630
2631 // Also add the SEHExceptBlock as a label, like with regular labels.
2632 SEHExceptBlock->setLabel(ES);
2633
2634 // Bail out if the CFG is bad.
2635 if (badCFG)
2636 return nullptr;
2637
2638 // We set Block to NULL to allow lazy creation of a new block (if necessary).
2639 Block = nullptr;
2640
2641 return SEHExceptBlock;
2642}
2643
2644CFGBlock *CFGBuilder::VisitSEHFinallyStmt(SEHFinallyStmt *FS) {
2645 return VisitCompoundStmt(FS->getBlock());
2646}
2647
2648CFGBlock *CFGBuilder::VisitSEHLeaveStmt(SEHLeaveStmt *LS) {
2649 // "__leave" is a control-flow statement. Thus we stop processing the current
2650 // block.
2651 if (badCFG)
2652 return nullptr;
2653
2654 // Now create a new block that ends with the __leave statement.
2655 Block = createBlock(false);
2656 Block->setTerminator(LS);
2657
2658 // If there is no target for the __leave, then we are looking at an incomplete
2659 // AST. This means that the CFG cannot be constructed.
2660 if (SEHLeaveJumpTarget.block) {
2661 addAutomaticObjHandling(ScopePos, SEHLeaveJumpTarget.scopePosition, LS);
2662 addSuccessor(Block, SEHLeaveJumpTarget.block);
2663 } else
2664 badCFG = true;
2665
2666 return Block;
2667}
2668
2669CFGBlock *CFGBuilder::VisitSEHTryStmt(SEHTryStmt *Terminator) {
2670 // "__try"/"__except"/"__finally" is a control-flow statement. Thus we stop
2671 // processing the current block.
2672 CFGBlock *SEHTrySuccessor = nullptr;
2673
2674 if (Block) {
2675 if (badCFG)
2676 return nullptr;
2677 SEHTrySuccessor = Block;
2678 } else SEHTrySuccessor = Succ;
2679
2680 // FIXME: Implement __finally support.
2681 if (Terminator->getFinallyHandler())
2682 return NYS();
2683
2684 CFGBlock *PrevSEHTryTerminatedBlock = TryTerminatedBlock;
2685
2686 // Create a new block that will contain the __try statement.
2687 CFGBlock *NewTryTerminatedBlock = createBlock(false);
2688
2689 // Add the terminator in the __try block.
2690 NewTryTerminatedBlock->setTerminator(Terminator);
2691
2692 if (SEHExceptStmt *Except = Terminator->getExceptHandler()) {
2693 // The code after the try is the implicit successor if there's an __except.
2694 Succ = SEHTrySuccessor;
2695 Block = nullptr;
2696 CFGBlock *ExceptBlock = VisitSEHExceptStmt(Except);
2697 if (!ExceptBlock)
2698 return nullptr;
2699 // Add this block to the list of successors for the block with the try
2700 // statement.
2701 addSuccessor(NewTryTerminatedBlock, ExceptBlock);
2702 }
2703 if (PrevSEHTryTerminatedBlock)
2704 addSuccessor(NewTryTerminatedBlock, PrevSEHTryTerminatedBlock);
2705 else
2706 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
2707
2708 // The code after the try is the implicit successor.
2709 Succ = SEHTrySuccessor;
2710
2711 // Save the current "__try" context.
2712 SaveAndRestore<CFGBlock *> save_try(TryTerminatedBlock,
2713 NewTryTerminatedBlock);
2714 cfg->addTryDispatchBlock(TryTerminatedBlock);
2715
2716 // Save the current value for the __leave target.
2717 // All __leaves should go to the code following the __try
2718 // (FIXME: or if the __try has a __finally, to the __finally.)
2719 SaveAndRestore<JumpTarget> save_break(SEHLeaveJumpTarget);
2720 SEHLeaveJumpTarget = JumpTarget(SEHTrySuccessor, ScopePos);
2721
2722 assert(Terminator->getTryBlock() && "__try must contain a non-NULL body");
2723 Block = nullptr;
2724 return addStmt(Terminator->getTryBlock());
2725}
2726
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002727CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002728 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002729 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002730 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002731
Ted Kremenek93668002009-07-17 22:18:43 +00002732 if (!LabelBlock) // This can happen when the body is empty, i.e.
2733 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002734
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002735 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2736 "label already in map");
2737 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002738
2739 // Labels partition blocks, so this is the end of the basic block we were
2740 // processing (L is the block's label). Because this is label (and we have
2741 // already processed the substatement) there is no extra control-flow to worry
2742 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002743 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002744 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002745 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002746
2747 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002748 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002749
Ted Kremenek9aae5132007-08-23 21:42:29 +00002750 // This block is now the implicit successor of other blocks.
2751 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002752
Ted Kremenek9aae5132007-08-23 21:42:29 +00002753 return LabelBlock;
2754}
2755
Devin Coughlinb6029b72015-11-25 22:35:37 +00002756CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2757 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2758 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2759 if (Expr *CopyExpr = CI.getCopyExpr()) {
2760 CFGBlock *Tmp = Visit(CopyExpr);
2761 if (Tmp)
2762 LastBlock = Tmp;
2763 }
2764 }
2765 return LastBlock;
2766}
2767
Ted Kremenekda76a942012-04-12 20:34:52 +00002768CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2769 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2770 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2771 et = E->capture_init_end(); it != et; ++it) {
2772 if (Expr *Init = *it) {
2773 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002774 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002775 LastBlock = Tmp;
2776 }
2777 }
2778 return LastBlock;
2779}
2780
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002781CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002782 // Goto is a control-flow statement. Thus we stop processing the current
2783 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002784
Ted Kremenek9aae5132007-08-23 21:42:29 +00002785 Block = createBlock(false);
2786 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002787
2788 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002789 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002790
Ted Kremenek9aae5132007-08-23 21:42:29 +00002791 if (I == LabelMap.end())
2792 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002793 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2794 else {
2795 JumpTarget JT = I->second;
Matthias Gehre351c2182017-07-12 07:04:19 +00002796 addAutomaticObjHandling(ScopePos, JT.scopePosition, G);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002797 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002798 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002799
Mike Stump31feda52009-07-17 01:31:16 +00002800 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002801}
2802
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002803CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002804 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002805
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002806 // Save local scope position because in case of condition variable ScopePos
2807 // won't be restored when traversing AST.
2808 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2809
2810 // Create local scope for init statement and possible condition variable.
2811 // Add destructor for init statement and condition variable.
2812 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002813 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002814 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002815 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2816
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002817 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002818 addLocalScopeForVarDecl(VD);
2819 LocalScope::const_iterator ContinueScopePos = ScopePos;
2820
Matthias Gehre351c2182017-07-12 07:04:19 +00002821 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), F);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002822
Peter Szecsi999a25f2017-08-19 11:19:16 +00002823 addLoopExit(F);
2824
Mike Stump014b3ea2009-07-21 01:12:51 +00002825 // "for" is a control-flow statement. Thus we stop processing the current
2826 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002827 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002828 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002829 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002830 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002831 } else
2832 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002833
Ted Kremenek304a9532010-05-21 20:30:15 +00002834 // Save the current value for the break targets.
2835 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002836 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002837 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002838
Craig Topper25542942014-05-20 04:30:07 +00002839 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002840
Ted Kremenek9aae5132007-08-23 21:42:29 +00002841 // Now create the loop body.
2842 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002843 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002844
Ted Kremenekb50e7162012-07-14 05:04:10 +00002845 // Save the current values for Block, Succ, continue and break targets.
2846 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2847 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002848
Ted Kremenekb50e7162012-07-14 05:04:10 +00002849 // Create an empty block to represent the transition block for looping back
2850 // to the head of the loop. If we have increment code, it will
2851 // go in this block as well.
2852 Block = Succ = TransitionBlock = createBlock(false);
2853 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002854
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002855 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002856 // Generate increment code in its own basic block. This is the target of
2857 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002858 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002859 }
Mike Stump31feda52009-07-17 01:31:16 +00002860
Ted Kremenek902393b2009-04-28 00:51:56 +00002861 // Finish up the increment (or empty) block if it hasn't been already.
2862 if (Block) {
2863 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002864 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002865 return nullptr;
2866 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002867 }
Mike Stump31feda52009-07-17 01:31:16 +00002868
Ted Kremenekb50e7162012-07-14 05:04:10 +00002869 // The starting block for the loop increment is the block that should
2870 // represent the 'loop target' for looping back to the start of the loop.
2871 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2872 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002873
Ted Kremenekb50e7162012-07-14 05:04:10 +00002874 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00002875 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002876
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002877 // If body is not a compound statement create implicit scope
2878 // and add destructors.
2879 if (!isa<CompoundStmt>(F->getBody()))
2880 addLocalScopeAndDtors(F->getBody());
2881
Mike Stump31feda52009-07-17 01:31:16 +00002882 // Now populate the body block, and in the process create new blocks as we
2883 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002884 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002885
Ted Kremenekb50e7162012-07-14 05:04:10 +00002886 if (!BodyBlock) {
2887 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2888 // Use the continue jump target as the proxy for the body.
2889 BodyBlock = ContinueJumpTarget.block;
2890 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002891 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002892 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002893 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002894
2895 // Because of short-circuit evaluation, the condition of the loop can span
2896 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2897 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002898 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002899
Ted Kremenekb50e7162012-07-14 05:04:10 +00002900 do {
2901 Expr *C = F->getCond();
2902
2903 // Specially handle logical operators, which have a slightly
2904 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002905 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002906 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002907 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002908 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002909 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2910 break;
2911 }
2912
2913 // The default case when not handling logical operators.
2914 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2915 ExitConditionBlock->setTerminator(F);
2916
2917 // See if this is a known constant.
2918 TryResult KnownVal(true);
2919
2920 if (C) {
2921 // Now add the actual condition to the condition block.
2922 // Because the condition itself may contain control-flow, new blocks may
2923 // be created. Thus we update "Succ" after adding the condition.
2924 Block = ExitConditionBlock;
2925 EntryConditionBlock = addStmt(C);
2926
2927 // If this block contains a condition variable, add both the condition
2928 // variable and initializer to the CFG.
2929 if (VarDecl *VD = F->getConditionVariable()) {
2930 if (Expr *Init = VD->getInit()) {
2931 autoCreateBlock();
2932 appendStmt(Block, F->getConditionVariableDeclStmt());
2933 EntryConditionBlock = addStmt(Init);
2934 assert(Block == EntryConditionBlock);
2935 }
2936 }
2937
2938 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002939 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002940
2941 KnownVal = tryEvaluateBool(C);
2942 }
2943
2944 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002945 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002946 // Link up the condition block with the code that follows the loop. (the
2947 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002948 addSuccessor(ExitConditionBlock,
2949 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002950 } while (false);
2951
2952 // Link up the loop-back block to the entry condition block.
2953 addSuccessor(TransitionBlock, EntryConditionBlock);
2954
2955 // The condition block is the implicit successor for any code above the loop.
2956 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002957
Ted Kremenek9aae5132007-08-23 21:42:29 +00002958 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002959 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002960 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002961 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002962 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002963 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002964
2965 // There is no loop initialization. We are thus basically a while loop.
2966 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002967 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002968 Succ = EntryConditionBlock;
2969 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002970}
2971
Ted Kremenek5868ec62010-04-11 17:02:10 +00002972CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002973 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002974 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002975 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002976 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002977 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002978}
2979
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002980CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002981 // Objective-C fast enumeration 'for' statements:
2982 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2983 //
2984 // for ( Type newVariable in collection_expression ) { statements }
2985 //
2986 // becomes:
2987 //
2988 // prologue:
2989 // 1. collection_expression
2990 // T. jump to loop_entry
2991 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002992 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002993 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2994 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2995 // TB:
2996 // statements
2997 // T. jump to loop_entry
2998 // FB:
2999 // what comes after
3000 //
3001 // and
3002 //
3003 // Type existingItem;
3004 // for ( existingItem in expression ) { statements }
3005 //
3006 // becomes:
3007 //
Mike Stump31feda52009-07-17 01:31:16 +00003008 // the same with newVariable replaced with existingItem; the binding works
3009 // the same except that for one ObjCForCollectionStmt::getElement() returns
3010 // a DeclStmt and the other returns a DeclRefExpr.
Mike Stump31feda52009-07-17 01:31:16 +00003011
Craig Topper25542942014-05-20 04:30:07 +00003012 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003013
Ted Kremenek9d56e642008-11-11 17:10:00 +00003014 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003015 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003016 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00003017 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003018 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003019 } else
3020 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003021
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003022 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003023 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003024
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003025 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003026 ExitConditionBlock->setTerminator(S);
3027
3028 // The last statement in the block should be the ObjCForCollectionStmt, which
3029 // performs the actual binding to 'element' and determines if there are any
3030 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00003031 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003032 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003033
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003034 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00003035 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00003036 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00003037 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
3038 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00003039 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003040 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003041 return nullptr;
3042 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003043 }
Mike Stump31feda52009-07-17 01:31:16 +00003044
3045 // The condition block is the implicit successor for the loop body as well as
3046 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003047 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003048
Ted Kremenek9d56e642008-11-11 17:10:00 +00003049 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00003050 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003051 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00003052 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003053 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00003054 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003055
Anna Zaks56b49752013-06-22 00:23:20 +00003056 // Add an intermediate block between the BodyBlock and the
3057 // EntryConditionBlock to represent the "loop back" transition, for looping
3058 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00003059 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00003060 Succ = LoopBackBlock = createBlock();
3061 LoopBackBlock->setLoopTarget(S);
3062
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003063 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00003064 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003065
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003066 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003067
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003068 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00003069 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00003070 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003071 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003072 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003073 }
Mike Stump31feda52009-07-17 01:31:16 +00003074
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003075 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003076 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003077 }
Mike Stump31feda52009-07-17 01:31:16 +00003078
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003079 // Link up the condition block with the code that follows the loop.
3080 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003081 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003082
Ted Kremenek9d56e642008-11-11 17:10:00 +00003083 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00003084 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00003085 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00003086}
3087
Ted Kremenek5022f1d2012-03-06 23:40:47 +00003088CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
3089 // Inline the body.
3090 return addStmt(S->getSubStmt());
3091 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
3092}
3093
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003094CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00003095 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00003096
Ted Kremenek49805452009-05-02 01:49:13 +00003097 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00003098 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00003099
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003100 // The sync body starts its own basic block. This makes it a little easier
3101 // for diagnostic clients.
3102 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003103 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003104 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003105
Craig Topper25542942014-05-20 04:30:07 +00003106 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00003107 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00003108 }
Mike Stump31feda52009-07-17 01:31:16 +00003109
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003110 // Add the @synchronized to the CFG.
3111 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003112 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00003113
Ted Kremenek49805452009-05-02 01:49:13 +00003114 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00003115 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00003116}
Mike Stump31feda52009-07-17 01:31:16 +00003117
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003118CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003119 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00003120 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00003121}
Ted Kremenek9d56e642008-11-11 17:10:00 +00003122
John McCallfe96e0b2011-11-06 09:01:30 +00003123CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
3124 autoCreateBlock();
3125
3126 // Add the PseudoObject as the last thing.
3127 appendStmt(Block, E);
3128
3129 CFGBlock *lastBlock = Block;
3130
3131 // Before that, evaluate all of the semantics in order. In
3132 // CFG-land, that means appending them in reverse order.
3133 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
3134 Expr *Semantic = E->getSemanticExpr(--i);
3135
3136 // If the semantic is an opaque value, we're being asked to bind
3137 // it to its source expression.
3138 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
3139 Semantic = OVE->getSourceExpr();
3140
3141 if (CFGBlock *B = Visit(Semantic))
3142 lastBlock = B;
3143 }
3144
3145 return lastBlock;
3146}
3147
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003148CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00003149 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003150
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003151 // Save local scope position because in case of condition variable ScopePos
3152 // won't be restored when traversing AST.
3153 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3154
3155 // Create local scope for possible condition variable.
3156 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003157 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003158 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003159 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003160 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003161 }
Peter Szecsi999a25f2017-08-19 11:19:16 +00003162 addLoopExit(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003163
Mike Stump014b3ea2009-07-21 01:12:51 +00003164 // "while" is a control-flow statement. Thus we stop processing the current
3165 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003166 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003167 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003168 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003169 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00003170 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003171 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00003172 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00003173 }
Mike Stump31feda52009-07-17 01:31:16 +00003174
Craig Topper25542942014-05-20 04:30:07 +00003175 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00003176
Ted Kremenek9aae5132007-08-23 21:42:29 +00003177 // Process the loop body.
3178 {
Ted Kremenek49936f72009-04-28 03:09:44 +00003179 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00003180
Ted Kremenekb50e7162012-07-14 05:04:10 +00003181 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003182 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3183 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00003184 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00003185
Mike Stump31feda52009-07-17 01:31:16 +00003186 // Create an empty block to represent the transition block for looping back
3187 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003188 Succ = TransitionBlock = createBlock(false);
3189 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003190 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003191
Ted Kremenek9aae5132007-08-23 21:42:29 +00003192 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003193 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003194
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003195 // Loop body should end with destructor of Condition variable (if any).
Matthias Gehre351c2182017-07-12 07:04:19 +00003196 addAutomaticObjHandling(ScopePos, LoopBeginScopePos, W);
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003197
3198 // If body is not a compound statement create implicit scope
3199 // and add destructors.
3200 if (!isa<CompoundStmt>(W->getBody()))
3201 addLocalScopeAndDtors(W->getBody());
3202
Ted Kremenek9aae5132007-08-23 21:42:29 +00003203 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00003204 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003205
Ted Kremeneke9610502007-08-30 18:39:40 +00003206 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003207 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00003208 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003209 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003210 }
3211
3212 // Because of short-circuit evaluation, the condition of the loop can span
3213 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3214 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00003215 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003216
3217 do {
3218 Expr *C = W->getCond();
3219
3220 // Specially handle logical operators, which have a slightly
3221 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00003222 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00003223 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003224 std::tie(EntryConditionBlock, ExitConditionBlock) =
3225 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003226 break;
3227 }
3228
3229 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00003230 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003231 ExitConditionBlock->setTerminator(W);
3232
3233 // Now add the actual condition to the condition block.
3234 // Because the condition itself may contain control-flow, new blocks may
3235 // be created. Thus we update "Succ" after adding the condition.
3236 Block = ExitConditionBlock;
3237 Block = EntryConditionBlock = addStmt(C);
3238
3239 // If this block contains a condition variable, add both the condition
3240 // variable and initializer to the CFG.
3241 if (VarDecl *VD = W->getConditionVariable()) {
3242 if (Expr *Init = VD->getInit()) {
3243 autoCreateBlock();
3244 appendStmt(Block, W->getConditionVariableDeclStmt());
3245 EntryConditionBlock = addStmt(Init);
3246 assert(Block == EntryConditionBlock);
3247 }
Ted Kremenek55957a82009-05-02 00:13:27 +00003248 }
Mike Stump31feda52009-07-17 01:31:16 +00003249
Ted Kremenekb50e7162012-07-14 05:04:10 +00003250 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003251 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00003252
3253 // See if this is a known constant.
3254 const TryResult& KnownVal = tryEvaluateBool(C);
3255
Ted Kremenek30754282009-07-24 04:47:11 +00003256 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00003257 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003258 // Link up the condition block with the code that follows the loop. (the
3259 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003260 addSuccessor(ExitConditionBlock,
3261 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00003262 } while(false);
3263
3264 // Link up the loop-back block to the entry condition block.
3265 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00003266
3267 // There can be no more statements in the condition block since we loop back
3268 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003269 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003270
Ted Kremenek1ce53c42009-12-24 01:34:10 +00003271 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003272 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00003273 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003274}
Mike Stump11289f42009-09-09 15:08:12 +00003275
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003276CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00003277 // FIXME: For now we pretend that @catch and the code it contains does not
3278 // exit.
3279 return Block;
3280}
Mike Stump31feda52009-07-17 01:31:16 +00003281
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003282CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00003283 // FIXME: This isn't complete. We basically treat @throw like a return
3284 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00003285
Ted Kremenek0868eea2009-09-24 18:45:41 +00003286 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003287 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003288 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003289
Ted Kremenek93041ba2008-12-09 20:20:09 +00003290 // Create the new block.
3291 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003292
Ted Kremenek93041ba2008-12-09 20:20:09 +00003293 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003294 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00003295
3296 // Add the statement to the block. This may create new blocks if S contains
3297 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003298 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00003299}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003300
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003301CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00003302 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003303 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003304 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003305
3306 // Create the new block.
3307 Block = createBlock(false);
3308
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003309 if (TryTerminatedBlock)
3310 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003311 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003312 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003313 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003314 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003315
3316 // Add the statement to the block. This may create new blocks if S contains
3317 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00003318 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00003319}
3320
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003321CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00003322 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003323
Peter Szecsi999a25f2017-08-19 11:19:16 +00003324 addLoopExit(D);
3325
Mike Stump8d50b6a2009-07-21 01:27:50 +00003326 // "do...while" is a control-flow statement. Thus we stop processing the
3327 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00003328 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003329 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003330 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003331 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003332 } else
3333 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00003334
3335 // Because of short-circuit evaluation, the condition of the loop can span
3336 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
3337 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003338 CFGBlock *ExitConditionBlock = createBlock(false);
3339 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003340
Ted Kremenek81e14852007-08-27 19:46:09 +00003341 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00003342 ExitConditionBlock->setTerminator(D);
3343
3344 // Now add the actual condition to the condition block. Because the condition
3345 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003346 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00003347 Block = ExitConditionBlock;
3348 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00003349 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003350 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003351 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003352 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003353 }
Mike Stump31feda52009-07-17 01:31:16 +00003354
Ted Kremeneka1523a32008-02-27 07:20:00 +00003355 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00003356 Succ = EntryConditionBlock;
3357
Mike Stump773582d2009-07-23 23:25:26 +00003358 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003359 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00003360
Ted Kremenek9aae5132007-08-23 21:42:29 +00003361 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00003362 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003363 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003364 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003365
Ted Kremenek9aae5132007-08-23 21:42:29 +00003366 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003367 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3368 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
3369 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00003370
Ted Kremenek9aae5132007-08-23 21:42:29 +00003371 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003372 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003373
Ted Kremenek9aae5132007-08-23 21:42:29 +00003374 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003375 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003376
Ted Kremenek9aae5132007-08-23 21:42:29 +00003377 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00003378 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003379
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00003380 // If body is not a compound statement create implicit scope
3381 // and add destructors.
3382 if (!isa<CompoundStmt>(D->getBody()))
3383 addLocalScopeAndDtors(D->getBody());
3384
Ted Kremenek9aae5132007-08-23 21:42:29 +00003385 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00003386 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00003387
Ted Kremeneke9610502007-08-30 18:39:40 +00003388 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00003389 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00003390 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003391 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003392 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003393 }
Mike Stump31feda52009-07-17 01:31:16 +00003394
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003395 // Add an intermediate block between the BodyBlock and the
3396 // ExitConditionBlock to represent the "loop back" transition. Create an
3397 // empty block to represent the transition block for looping back to the
3398 // head of the loop.
3399 // FIXME: Can we do this more efficiently without adding another block?
3400 Block = nullptr;
3401 Succ = BodyBlock;
3402 CFGBlock *LoopBackBlock = createBlock();
3403 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00003404
Daniel Marjamaki042a3c52016-10-03 08:28:51 +00003405 if (!KnownVal.isFalse())
Ted Kremenek110974d2010-08-17 20:59:56 +00003406 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003407 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00003408 else
Craig Topper25542942014-05-20 04:30:07 +00003409 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003410 }
Mike Stump31feda52009-07-17 01:31:16 +00003411
Ted Kremenek30754282009-07-24 04:47:11 +00003412 // Link up the condition block with the code that follows the loop.
3413 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003414 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003415
3416 // There can be no more statements in the body block(s) since we loop back to
3417 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003418 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003419
Ted Kremenek9aae5132007-08-23 21:42:29 +00003420 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003421 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003422 return BodyBlock;
3423}
3424
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003425CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003426 // "continue" is a control-flow statement. Thus we stop processing the
3427 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003428 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003429 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003430
Ted Kremenek9aae5132007-08-23 21:42:29 +00003431 // Now create a new block that ends with the continue statement.
3432 Block = createBlock(false);
3433 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003434
Ted Kremenek9aae5132007-08-23 21:42:29 +00003435 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003436 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003437 if (ContinueJumpTarget.block) {
Matthias Gehre351c2182017-07-12 07:04:19 +00003438 addAutomaticObjHandling(ScopePos, ContinueJumpTarget.scopePosition, C);
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003439 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003440 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003441 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003442
Ted Kremenek9aae5132007-08-23 21:42:29 +00003443 return Block;
3444}
Mike Stump11289f42009-09-09 15:08:12 +00003445
Peter Collingbournee190dee2011-03-11 19:24:49 +00003446CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3447 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003448 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003449 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003450 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Ted Kremenek93668002009-07-17 22:18:43 +00003453 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003454 CFGBlock *lastBlock = Block;
3455
Ted Kremenek93668002009-07-17 22:18:43 +00003456 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003457 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003458 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003459 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003460 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003461 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003462}
Mike Stump11289f42009-09-09 15:08:12 +00003463
Ted Kremenek93668002009-07-17 22:18:43 +00003464/// VisitStmtExpr - Utility method to handle (nested) statement
3465/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003466CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003467 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003468 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003469 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003470 }
Ted Kremenek93668002009-07-17 22:18:43 +00003471 return VisitCompoundStmt(SE->getSubStmt());
3472}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003473
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003474CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003475 // "switch" is a control-flow statement. Thus we stop processing the current
3476 // block.
Craig Topper25542942014-05-20 04:30:07 +00003477 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003478
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003479 // Save local scope position because in case of condition variable ScopePos
3480 // won't be restored when traversing AST.
3481 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3482
Richard Smitha547eb22016-07-14 00:11:03 +00003483 // Create local scope for C++17 switch init-stmt if one exists.
Richard Smith509bbd12017-01-13 22:16:41 +00003484 if (Stmt *Init = Terminator->getInit())
Richard Smitha547eb22016-07-14 00:11:03 +00003485 addLocalScopeForStmt(Init);
Richard Smitha547eb22016-07-14 00:11:03 +00003486
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003487 // Create local scope for possible condition variable.
3488 // Store scope position. Add implicit destructor.
Richard Smith509bbd12017-01-13 22:16:41 +00003489 if (VarDecl *VD = Terminator->getConditionVariable())
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003490 addLocalScopeForVarDecl(VD);
Richard Smith509bbd12017-01-13 22:16:41 +00003491
Matthias Gehre351c2182017-07-12 07:04:19 +00003492 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), Terminator);
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003493
Ted Kremenek9aae5132007-08-23 21:42:29 +00003494 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003495 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003496 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003497 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003498 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003499
3500 // Save the current "switch" context.
3501 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003502 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003503 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003504
Mike Stump31feda52009-07-17 01:31:16 +00003505 // Set the "default" case to be the block after the switch statement. If the
3506 // switch statement contains a "default:", this value will be overwritten with
3507 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003508 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003509
Ted Kremenek9aae5132007-08-23 21:42:29 +00003510 // Create a new block that will contain the switch statement.
3511 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003512
Ted Kremenek9aae5132007-08-23 21:42:29 +00003513 // Now process the switch body. The code after the switch is the implicit
3514 // successor.
3515 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003516 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003517
3518 // When visiting the body, the case statements should automatically get linked
3519 // up to the switch. We also don't keep a pointer to the body, since all
3520 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003521 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003522 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003523
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003524 // For pruning unreachable case statements, save the current state
3525 // for tracking the condition value.
3526 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3527 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003528
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003529 // Determine if the switch condition can be explicitly evaluated.
3530 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003531 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003532 bool b = tryEvaluate(Terminator->getCond(), result);
3533 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003534 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003535
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003536 // If body is not a compound statement create implicit scope
3537 // and add destructors.
3538 if (!isa<CompoundStmt>(Terminator->getBody()))
3539 addLocalScopeAndDtors(Terminator->getBody());
3540
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003541 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003542 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003543 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003544 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003545 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003546
Mike Stump31feda52009-07-17 01:31:16 +00003547 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003548 // following the switch body. Moreover, take into account if all the
3549 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003550 //
3551 // Note: We add a successor to a switch that is considered covered yet has no
3552 // case statements if the enumeration has no enumerators.
3553 bool SwitchAlwaysHasSuccessor = false;
3554 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3555 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3556 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003557 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3558 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003559
Ted Kremenek81e14852007-08-27 19:46:09 +00003560 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003561 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003562 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003563 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003564
Richard Smitha547eb22016-07-14 00:11:03 +00003565 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003566 // SwitchStmt and the condition variable initialization to the CFG.
3567 if (VarDecl *VD = Terminator->getConditionVariable()) {
3568 if (Expr *Init = VD->getInit()) {
3569 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003570 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003571 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003572 }
3573 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003574
Richard Smitha547eb22016-07-14 00:11:03 +00003575 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3576 if (Stmt *Init = Terminator->getInit()) {
3577 autoCreateBlock();
3578 LastBlock = addStmt(Init);
3579 }
3580
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003581 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003582}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003583
3584static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003585 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003586 const CaseStmt *CS,
3587 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003588 if (!switchCond)
3589 return true;
3590
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003591 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003592
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003593 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003594 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003595 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003596 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003597 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003598
3599 if (condInt == lhsInt) {
3600 addCase = true;
3601 switchExclusivelyCovered = true;
3602 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003603 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003604 if (const Expr *RHS = CS->getRHS()) {
3605 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003606 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003607 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003608 addCase = true;
3609 switchExclusivelyCovered = true;
3610 }
3611 }
3612 }
3613 }
3614 else
3615 addCase = true;
3616 }
3617 return addCase;
3618}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003619
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003620CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003621 // CaseStmts are essentially labels, so they are the first statement in a
3622 // block.
Craig Topper25542942014-05-20 04:30:07 +00003623 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003624
Ted Kremenek60fa6572010-08-04 23:54:30 +00003625 if (Stmt *Sub = CS->getSubStmt()) {
3626 // For deeply nested chains of CaseStmts, instead of doing a recursion
3627 // (which can blow out the stack), manually unroll and create blocks
3628 // along the way.
3629 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003630 CFGBlock *currentBlock = createBlock(false);
3631 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003632
Ted Kremenek60fa6572010-08-04 23:54:30 +00003633 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003634 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003635 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003636 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003637
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003638 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003639 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003640 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003641 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003642
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003643 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003644 CS = cast<CaseStmt>(Sub);
3645 Sub = CS->getSubStmt();
3646 }
3647
3648 addStmt(Sub);
3649 }
Mike Stump11289f42009-09-09 15:08:12 +00003650
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003651 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003652 if (!CaseBlock)
3653 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003654
3655 // Cases statements partition blocks, so this is the top of the basic block we
3656 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003657 CaseBlock->setLabel(CS);
3658
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003659 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003660 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003661
3662 // Add this block to the list of successors for the block with the switch
3663 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003664 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003665 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003666 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003667 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003668
Ted Kremenek9aae5132007-08-23 21:42:29 +00003669 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003670 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003671
Ted Kremenek60fa6572010-08-04 23:54:30 +00003672 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003673 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003674 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003675 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003676 // This block is now the implicit successor of other blocks.
3677 Succ = CaseBlock;
3678 }
Mike Stump31feda52009-07-17 01:31:16 +00003679
Ted Kremenek60fa6572010-08-04 23:54:30 +00003680 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003681}
Mike Stump31feda52009-07-17 01:31:16 +00003682
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003683CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003684 if (Terminator->getSubStmt())
3685 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003686
Ted Kremenek654c78f2008-02-13 22:05:39 +00003687 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003688
3689 if (!DefaultCaseBlock)
3690 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003691
3692 // Default statements partition blocks, so this is the top of the basic block
3693 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003694 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003695
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003696 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003697 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003698
Mike Stump31feda52009-07-17 01:31:16 +00003699 // Unlike case statements, we don't add the default block to the successors
3700 // for the switch statement immediately. This is done when we finish
3701 // processing the switch statement. This allows for the default case
3702 // (including a fall-through to the code after the switch statement) to always
3703 // be the last successor of a switch-terminated block.
3704
Ted Kremenek654c78f2008-02-13 22:05:39 +00003705 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003706 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003707
Ted Kremenek654c78f2008-02-13 22:05:39 +00003708 // This block is now the implicit successor of other blocks.
3709 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003710
3711 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003712}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003713
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003714CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3715 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3716 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003717 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003718
3719 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003720 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003721 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003722 TrySuccessor = Block;
3723 } else TrySuccessor = Succ;
3724
Mike Stump0bdba6c2010-01-20 01:15:34 +00003725 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003726
3727 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003728 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003729 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003730 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003731
Mike Stump0bdba6c2010-01-20 01:15:34 +00003732 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003733 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3734 // The code after the try is the implicit successor.
3735 Succ = TrySuccessor;
3736 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003737 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003738 HasCatchAll = true;
3739 }
Craig Topper25542942014-05-20 04:30:07 +00003740 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003741 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003742 if (!CatchBlock)
3743 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003744 // Add this block to the list of successors for the block with the try
3745 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003746 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003747 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003748 if (!HasCatchAll) {
3749 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003750 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003751 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003752 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003753 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003754
3755 // The code after the try is the implicit successor.
3756 Succ = TrySuccessor;
3757
Mike Stump845384a2010-01-20 01:30:58 +00003758 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003759 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3760 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003761
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003762 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003763 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003764 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003765}
3766
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003767CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003768 // CXXCatchStmt are treated like labels, so they are the first statement in a
3769 // block.
3770
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003771 // Save local scope position because in case of exception variable ScopePos
3772 // won't be restored when traversing AST.
3773 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3774
3775 // Create local scope for possible exception variable.
3776 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003777 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003778 LocalScope::const_iterator BeginScopePos = ScopePos;
3779 addLocalScopeForVarDecl(VD);
Matthias Gehre351c2182017-07-12 07:04:19 +00003780 addAutomaticObjHandling(ScopePos, BeginScopePos, CS);
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003781 }
3782
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003783 if (CS->getHandlerBlock())
3784 addStmt(CS->getHandlerBlock());
3785
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003786 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003787 if (!CatchBlock)
3788 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003789
3790 // CXXCatchStmt is more than just a label. They have semantic meaning
3791 // as well, as they implicitly "initialize" the catch variable. Add
3792 // it to the CFG as a CFGElement so that the control-flow of these
3793 // semantics gets captured.
3794 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003795
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003796 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3797 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003798 CatchBlock->setLabel(CS);
3799
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003800 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003801 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003802 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003803
3804 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003805 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003806
3807 return CatchBlock;
3808}
3809
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003810CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003811 // C++0x for-range statements are specified as [stmt.ranged]:
3812 //
3813 // {
3814 // auto && __range = range-init;
3815 // for ( auto __begin = begin-expr,
3816 // __end = end-expr;
3817 // __begin != __end;
3818 // ++__begin ) {
3819 // for-range-declaration = *__begin;
3820 // statement
3821 // }
3822 // }
3823
3824 // Save local scope position before the addition of the implicit variables.
3825 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3826
3827 // Create local scopes and destructors for range, begin and end variables.
3828 if (Stmt *Range = S->getRangeStmt())
3829 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00003830 if (Stmt *Begin = S->getBeginStmt())
3831 addLocalScopeForStmt(Begin);
3832 if (Stmt *End = S->getEndStmt())
3833 addLocalScopeForStmt(End);
Matthias Gehre351c2182017-07-12 07:04:19 +00003834 addAutomaticObjHandling(ScopePos, save_scope_pos.get(), S);
Richard Smith02e85f32011-04-14 22:09:26 +00003835
3836 LocalScope::const_iterator ContinueScopePos = ScopePos;
3837
3838 // "for" is a control-flow statement. Thus we stop processing the current
3839 // block.
Craig Topper25542942014-05-20 04:30:07 +00003840 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003841 if (Block) {
3842 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003843 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003844 LoopSuccessor = Block;
3845 } else
3846 LoopSuccessor = Succ;
3847
3848 // Save the current value for the break targets.
3849 // All breaks should go to the code following the loop.
3850 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3851 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3852
3853 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003854 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003855 ConditionBlock->setTerminator(S);
3856
3857 // Now add the actual condition to the condition block.
3858 if (Expr *C = S->getCond()) {
3859 Block = ConditionBlock;
3860 CFGBlock *BeginConditionBlock = addStmt(C);
3861 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003862 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003863 assert(BeginConditionBlock == ConditionBlock &&
3864 "condition block in for-range was unexpectedly complex");
3865 (void)BeginConditionBlock;
3866 }
3867
3868 // The condition block is the implicit successor for the loop body as well as
3869 // any code above the loop.
3870 Succ = ConditionBlock;
3871
3872 // See if this is a known constant.
3873 TryResult KnownVal(true);
3874
3875 if (S->getCond())
3876 KnownVal = tryEvaluateBool(S->getCond());
3877
3878 // Now create the loop body.
3879 {
3880 assert(S->getBody());
3881
3882 // Save the current values for Block, Succ, and continue targets.
3883 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3884 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3885
3886 // Generate increment code in its own basic block. This is the target of
3887 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003888 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003889 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00003890 if (badCFG)
3891 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003892 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3893
3894 // The starting block for the loop increment is the block that should
3895 // represent the 'loop target' for looping back to the start of the loop.
3896 ContinueJumpTarget.block->setLoopTarget(S);
3897
3898 // Finish up the increment block and prepare to start the loop body.
3899 assert(Block);
3900 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003901 return nullptr;
3902 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003903
3904 // Add implicit scope and dtors for loop variable.
3905 addLocalScopeAndDtors(S->getLoopVarStmt());
3906
3907 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003908 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003909 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003910 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003911 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003912 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003913 return nullptr;
3914
Richard Smith02e85f32011-04-14 22:09:26 +00003915 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003916 addSuccessor(ConditionBlock,
3917 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003918 }
3919
3920 // Link up the condition block with the code that follows the loop (the
3921 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003922 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003923
3924 // Add the initialization statements.
3925 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00003926 addStmt(S->getBeginStmt());
3927 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00003928 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003929}
3930
John McCall5d413782010-12-06 08:20:24 +00003931CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003932 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003933 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003934 // If adding implicit destructors visit the full expression for adding
3935 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003936 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003937 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003938
3939 // Full expression has to be added as CFGStmt so it will be sequenced
3940 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003941 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003942 }
3943 return Visit(E->getSubExpr(), asc);
3944}
3945
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003946CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3947 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003948 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003949 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003950 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003951
Artem Dergachev783a4572018-02-23 22:20:39 +00003952 findConstructionContexts(
3953 ConstructionContext::create(cfg->getBumpVectorContext(), E),
3954 E->getSubExpr());
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00003955
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003956 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003957 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003958 }
3959 return Visit(E->getSubExpr(), asc);
3960}
3961
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003962CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3963 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003964 autoCreateBlock();
Artem Dergachev41ffb302018-02-08 22:58:15 +00003965 appendConstructor(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003966
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003967 return VisitChildren(C);
3968}
3969
Jordan Rosec9176072014-01-13 17:59:19 +00003970CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3971 AddStmtChoice asc) {
Jordan Rosec9176072014-01-13 17:59:19 +00003972 autoCreateBlock();
3973 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003974
Artem Dergachev783a4572018-02-23 22:20:39 +00003975 findConstructionContexts(
3976 ConstructionContext::create(cfg->getBumpVectorContext(), NE),
3977 const_cast<CXXConstructExpr *>(NE->getConstructExpr()));
Artem Dergachev41ffb302018-02-08 22:58:15 +00003978
Jordan Rosec9176072014-01-13 17:59:19 +00003979 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003980 Block = Visit(NE->getInitializer());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003981
Jordan Rosec9176072014-01-13 17:59:19 +00003982 if (BuildOpts.AddCXXNewAllocator)
3983 appendNewAllocator(Block, NE);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003984
Jordan Rosec9176072014-01-13 17:59:19 +00003985 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003986 Block = Visit(NE->getArraySize());
Artem Dergachev41ffb302018-02-08 22:58:15 +00003987
Jordan Rosec9176072014-01-13 17:59:19 +00003988 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3989 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003990 Block = Visit(*I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00003991
Jordan Rosec9176072014-01-13 17:59:19 +00003992 return Block;
3993}
Jordan Rosed2f40792013-09-03 17:00:57 +00003994
3995CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3996 AddStmtChoice asc) {
3997 autoCreateBlock();
3998 appendStmt(Block, DE);
3999 QualType DTy = DE->getDestroyedType();
Martin Bohmef44cde82016-12-05 11:33:19 +00004000 if (!DTy.isNull()) {
4001 DTy = DTy.getNonReferenceType();
4002 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
4003 if (RD) {
4004 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
4005 appendDeleteDtor(Block, RD, DE);
4006 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004007 }
4008
4009 return VisitChildren(DE);
4010}
4011
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004012CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
4013 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004014 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004015 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004016 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004017 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00004018 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004019 }
4020 return Visit(E->getSubExpr(), asc);
4021}
4022
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004023CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
4024 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004025 autoCreateBlock();
Artem Dergachev1f68d9d2018-02-15 03:13:36 +00004026 appendConstructor(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004027 return VisitChildren(C);
4028}
4029
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004030CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
4031 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00004032 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004033 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00004034 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004035 }
Ted Kremenek8219b822010-12-16 07:46:53 +00004036 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00004037}
4038
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004039CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00004040 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004041 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00004042
Ted Kremenekeda180e22007-08-28 19:26:49 +00004043 if (!IBlock) {
4044 IBlock = createBlock(false);
4045 cfg->setIndirectGotoBlock(IBlock);
4046 }
Mike Stump31feda52009-07-17 01:31:16 +00004047
Ted Kremenekeda180e22007-08-28 19:26:49 +00004048 // IndirectGoto is a control-flow statement. Thus we stop processing the
4049 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00004050 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00004051 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00004052
Ted Kremenekeda180e22007-08-28 19:26:49 +00004053 Block = createBlock(false);
4054 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004055 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00004056 return addStmt(I->getTarget());
4057}
4058
Manuel Klimekb5616c92014-08-07 10:42:17 +00004059CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
4060 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00004061 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
4062
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004063tryAgain:
4064 if (!E) {
4065 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00004066 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004067 }
4068 switch (E->getStmtClass()) {
4069 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004070 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004071
4072 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00004073 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
4074 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004075
4076 case Stmt::CXXBindTemporaryExprClass:
4077 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004078 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004079
John McCallc07a0c72011-02-17 10:25:35 +00004080 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004081 case Stmt::ConditionalOperatorClass:
4082 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004083 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004084
4085 case Stmt::ImplicitCastExprClass:
4086 // For implicit cast we want BindToTemporary to be passed further.
4087 E = cast<CastExpr>(E)->getSubExpr();
4088 goto tryAgain;
4089
Manuel Klimekb0042c42014-07-30 08:34:42 +00004090 case Stmt::CXXFunctionalCastExprClass:
4091 // For functional cast we want BindToTemporary to be passed further.
4092 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
4093 goto tryAgain;
4094
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004095 case Stmt::ParenExprClass:
4096 E = cast<ParenExpr>(E)->getSubExpr();
4097 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00004098
Manuel Klimekb0042c42014-07-30 08:34:42 +00004099 case Stmt::MaterializeTemporaryExprClass: {
4100 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
4101 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
4102 SmallVector<const Expr *, 2> CommaLHSs;
4103 SmallVector<SubobjectAdjustment, 2> Adjustments;
4104 // Find the expression whose lifetime needs to be extended.
4105 E = const_cast<Expr *>(
4106 cast<MaterializeTemporaryExpr>(E)
4107 ->GetTemporaryExpr()
4108 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
4109 // Visit the skipped comma operator left-hand sides for other temporaries.
4110 for (const Expr *CommaLHS : CommaLHSs) {
4111 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00004112 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00004113 }
Douglas Gregorfe314812011-06-21 17:03:29 +00004114 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00004115 }
Richard Smith4137af22014-07-27 05:12:49 +00004116
4117 case Stmt::BlockExprClass:
4118 // Don't recurse into blocks; their subexpressions don't get evaluated
4119 // here.
4120 return Block;
4121
4122 case Stmt::LambdaExprClass: {
4123 // For lambda expressions, only recurse into the capture initializers,
4124 // and not the body.
4125 auto *LE = cast<LambdaExpr>(E);
4126 CFGBlock *B = Block;
4127 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004128 if (CFGBlock *R = VisitForTemporaryDtors(
4129 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00004130 B = R;
4131 }
4132 return B;
4133 }
4134
4135 case Stmt::CXXDefaultArgExprClass:
4136 E = cast<CXXDefaultArgExpr>(E)->getExpr();
4137 goto tryAgain;
4138
4139 case Stmt::CXXDefaultInitExprClass:
4140 E = cast<CXXDefaultInitExpr>(E)->getExpr();
4141 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004142 }
4143}
4144
Manuel Klimekb5616c92014-08-07 10:42:17 +00004145CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
4146 TempDtorContext &Context) {
4147 if (isa<LambdaExpr>(E)) {
4148 // Do not visit the children of lambdas; they have their own CFGs.
4149 return Block;
4150 }
4151
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004152 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00004153 // order that they will appear in the CFG. Because the CFG is built
4154 // bottom-up, this means we visit them in their natural order, which
4155 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004156 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004157 for (Stmt *Child : E->children())
4158 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00004159 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00004160 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00004161
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004162 return B;
4163}
4164
Manuel Klimekb5616c92014-08-07 10:42:17 +00004165CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
4166 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004167 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004168 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00004169 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
4170 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
4171 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00004172
Manuel Klimekedf925b92014-08-07 18:44:19 +00004173 // We do not know at CFG-construction time whether the right-hand-side was
4174 // executed, thus we add a branch node that depends on the temporary
4175 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00004176 TempDtorContext RHSContext(
4177 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00004178 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00004179 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00004180
Manuel Klimekb5616c92014-08-07 10:42:17 +00004181 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004182 }
4183
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004184 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004185 // For assignment operator (=) LHS expression is visited
4186 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004187 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
4188 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004189 return LHSBlock ? LHSBlock : RHSBlock;
4190 }
4191
4192 // For any other binary operator RHS expression is visited before
4193 // LHS expression (order of children). For destructors visit them in reverse
4194 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004195 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
4196 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004197 return RHSBlock ? RHSBlock : LHSBlock;
4198}
4199
4200CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004201 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004202 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00004203 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00004204 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004205 // If lifetime of temporary is not prolonged (by assigning to constant
4206 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00004207
Chandler Carruthad747252011-09-13 06:09:01 +00004208 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004209
Richard Trieu95a192a2015-05-28 00:14:02 +00004210 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00004211 // If the destructor is marked as a no-return destructor, we need to
4212 // create a new block for the destructor which does not have as a
4213 // successor anything built thus far. Control won't flow out of this
4214 // block.
4215 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00004216 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00004217 } else if (Context.needsTempDtorBranch()) {
4218 // If we need to introduce a branch, we add a new block that we will hook
4219 // up to a decision block later.
4220 if (B) Succ = B;
4221 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004222 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00004223 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00004224 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00004225 if (Context.needsTempDtorBranch()) {
4226 Context.setDecisionPoint(Succ, E);
4227 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004228 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004229
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004230 B = Block;
4231 }
4232 return B;
4233}
4234
Manuel Klimekb5616c92014-08-07 10:42:17 +00004235void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
4236 CFGBlock *FalseSucc) {
4237 if (!Context.TerminatorExpr) {
4238 // If no temporary was found, we do not need to insert a decision point.
4239 return;
4240 }
4241 assert(Context.TerminatorExpr);
4242 CFGBlock *Decision = createBlock(false);
4243 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00004244 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004245 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00004246 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00004247 Block = Decision;
4248}
4249
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004250CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00004251 AbstractConditionalOperator *E, bool BindToTemporary,
4252 TempDtorContext &Context) {
4253 VisitForTemporaryDtors(E->getCond(), false, Context);
4254 CFGBlock *ConditionBlock = Block;
4255 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00004256 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00004257 TryResult NegatedVal = ConditionVal;
4258 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00004259
Manuel Klimekdeb02622014-08-08 07:37:13 +00004260 TempDtorContext TrueContext(
4261 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004262 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004263 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004264
Manuel Klimekb5616c92014-08-07 10:42:17 +00004265 Block = ConditionBlock;
4266 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004267 TempDtorContext FalseContext(
4268 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00004269 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004270
Manuel Klimekb5616c92014-08-07 10:42:17 +00004271 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004272 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00004273 } else if (TrueContext.TerminatorExpr) {
4274 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00004275 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004276 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00004277 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00004278 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004279 return Block;
4280}
4281
Mike Stump31feda52009-07-17 01:31:16 +00004282/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
4283/// no successors or predecessors. If this is the first block created in the
4284/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004285CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00004286 bool first_block = begin() == end();
4287
4288 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004289 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00004290 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004291 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00004292
4293 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004294 if (first_block)
4295 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00004296
4297 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004298 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004299}
4300
David Blaikiee90195c2014-08-29 18:53:26 +00004301/// buildCFG - Constructs a CFG from an AST.
4302std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
4303 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00004304 CFGBuilder Builder(C, BO);
4305 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00004306}
4307
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004308const CXXDestructorDecl *
4309CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004310 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004311 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00004312 case CFGElement::NewAllocator:
Peter Szecsi999a25f2017-08-19 11:19:16 +00004313 case CFGElement::LoopExit:
Matthias Gehre351c2182017-07-12 07:04:19 +00004314 case CFGElement::LifetimeEnds:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004315 case CFGElement::Statement:
4316 case CFGElement::Constructor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004317 llvm_unreachable("getDestructorDecl should only be used with "
4318 "ImplicitDtors");
4319 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00004320 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004321 QualType ty = var->getType();
Devin Coughlin6eb1ca72016-08-02 21:07:23 +00004322
4323 // FIXME: See CFGBuilder::addLocalScopeForVarDecl.
4324 //
4325 // Lifetime-extending constructs are handled here. This works for a single
4326 // temporary in an initializer expression.
4327 if (ty->isReferenceType()) {
4328 if (const Expr *Init = var->getInit()) {
4329 ty = getReferenceInitTemporaryType(astContext, Init);
4330 }
4331 }
4332
Ted Kremeneke7d78882012-03-19 23:48:41 +00004333 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004334 ty = arrayType->getElementType();
4335 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004336 const RecordType *recordType = ty->getAs<RecordType>();
4337 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00004338 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004339 return classDecl->getDestructor();
4340 }
Jordan Rosed2f40792013-09-03 17:00:57 +00004341 case CFGElement::DeleteDtor: {
4342 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
4343 QualType DTy = DE->getDestroyedType();
4344 DTy = DTy.getNonReferenceType();
4345 const CXXRecordDecl *classDecl =
4346 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
4347 return classDecl->getDestructor();
4348 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004349 case CFGElement::TemporaryDtor: {
4350 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00004351 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004352 const CXXTemporary *temp = bindExpr->getTemporary();
4353 return temp->getDestructor();
4354 }
4355 case CFGElement::BaseDtor:
4356 case CFGElement::MemberDtor:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004357 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00004358 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004359 }
Ted Kremenek1676a042011-03-03 01:01:03 +00004360 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004361}
4362
Ted Kremenek8cfe2072011-03-03 01:21:32 +00004363bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00004364 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
4365 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00004366 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004367}
4368
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00004369//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004370// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00004371//===----------------------------------------------------------------------===//
4372
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004373CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004374 : ReachableBlock(IsReachable ? B : nullptr),
4375 UnreachableBlock(!IsReachable ? B : nullptr,
4376 B && IsReachable ? AB_Normal : AB_Unreachable) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004377
4378CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004379 : ReachableBlock(B),
4380 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
4381 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004382
4383void CFGBlock::addSuccessor(AdjacentBlock Succ,
4384 BumpVectorContext &C) {
4385 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004386 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004387
4388 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00004389 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004390
4391 Succs.push_back(Succ, C);
4392}
4393
Ted Kremenekb0371852010-09-09 00:06:04 +00004394bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00004395 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004396 if (F.IgnoreNullPredecessors && !From)
4397 return true;
4398
4399 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004400 // If the 'To' has no label or is labeled but the label isn't a
4401 // CaseStmt then filter this edge.
4402 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00004403 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00004404 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00004405 const Stmt *L = To->getLabel();
4406 if (!L || !isa<CaseStmt>(L))
4407 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00004408 }
4409 }
4410 }
4411
4412 return false;
4413}
4414
4415//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004416// CFG pretty printing
4417//===----------------------------------------------------------------------===//
4418
Ted Kremenek7e776b12007-08-22 18:22:34 +00004419namespace {
4420
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004421class StmtPrinterHelper : public PrinterHelper {
Eugene Zelenko38c70522017-12-07 21:55:09 +00004422 using StmtMapTy = llvm::DenseMap<const Stmt *, std::pair<unsigned, unsigned>>;
4423 using DeclMapTy = llvm::DenseMap<const Decl *, std::pair<unsigned, unsigned>>;
4424
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004425 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004426 DeclMapTy DeclMap;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004427 signed currentBlock = 0;
4428 unsigned currStmt = 0;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004429 const LangOptions &LangOpts;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004430
Eugene Zelenko38c70522017-12-07 21:55:09 +00004431public:
Chris Lattnerc61089a2009-06-30 01:26:17 +00004432 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004433 : LangOpts(LO) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004434 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4435 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004436 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004437 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004438 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4439 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004440 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004441 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004442
Ted Kremenek96a7a592011-03-01 03:15:10 +00004443 switch (stmt->getStmtClass()) {
4444 case Stmt::DeclStmtClass:
Artem Dergachev41ffb302018-02-08 22:58:15 +00004445 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4446 break;
Ted Kremenek96a7a592011-03-01 03:15:10 +00004447 case Stmt::IfStmtClass: {
4448 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4449 if (var)
4450 DeclMap[var] = P;
4451 break;
4452 }
4453 case Stmt::ForStmtClass: {
4454 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4455 if (var)
4456 DeclMap[var] = P;
4457 break;
4458 }
4459 case Stmt::WhileStmtClass: {
4460 const VarDecl *var =
4461 cast<WhileStmt>(stmt)->getConditionVariable();
4462 if (var)
4463 DeclMap[var] = P;
4464 break;
4465 }
4466 case Stmt::SwitchStmtClass: {
4467 const VarDecl *var =
4468 cast<SwitchStmt>(stmt)->getConditionVariable();
4469 if (var)
4470 DeclMap[var] = P;
4471 break;
4472 }
4473 case Stmt::CXXCatchStmtClass: {
4474 const VarDecl *var =
4475 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4476 if (var)
4477 DeclMap[var] = P;
4478 break;
4479 }
4480 default:
4481 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004482 }
4483 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004484 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004485 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004486 }
Mike Stump31feda52009-07-17 01:31:16 +00004487
Eugene Zelenko38c70522017-12-07 21:55:09 +00004488 ~StmtPrinterHelper() override = default;
Mike Stump31feda52009-07-17 01:31:16 +00004489
Chris Lattnerc61089a2009-06-30 01:26:17 +00004490 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004491 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004492 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004493
Craig Topperb45acb82014-03-14 06:02:07 +00004494 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004495 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004496
4497 if (I == StmtMap.end())
4498 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004499
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004500 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004501 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004502 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004503 }
Mike Stump31feda52009-07-17 01:31:16 +00004504
Ted Kremenek60983dc2010-01-19 20:52:05 +00004505 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004506 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004507 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004508
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004509 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004510 DeclMapTy::iterator I = DeclMap.find(D);
4511
4512 if (I == DeclMap.end())
4513 return false;
4514
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004515 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004516 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004517 return false;
4518 }
4519
4520 OS << "[B" << I->second.first << "." << I->second.second << "]";
4521 return true;
4522 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004523};
4524
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004525class CFGBlockTerminatorPrint
Eugene Zelenko38c70522017-12-07 21:55:09 +00004526 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004527 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004528 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004529 PrintingPolicy Policy;
Eugene Zelenko38c70522017-12-07 21:55:09 +00004530
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004531public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004532 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004533 const PrintingPolicy &Policy)
Eugene Zelenko38c70522017-12-07 21:55:09 +00004534 : OS(os), Helper(helper), Policy(Policy) {
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004535 this->Policy.IncludeNewlines = false;
4536 }
Mike Stump31feda52009-07-17 01:31:16 +00004537
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004538 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004539 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004540 if (Stmt *C = I->getCond())
4541 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004542 }
Mike Stump31feda52009-07-17 01:31:16 +00004543
Ted Kremenek9aae5132007-08-23 21:42:29 +00004544 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004545 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004546 Terminator->printPretty(OS, Helper, Policy);
4547 }
4548
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004549 void VisitDeclStmt(DeclStmt *DS) {
4550 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4551 OS << "static init " << VD->getName();
4552 }
4553
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004554 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004555 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004556 if (F->getInit())
4557 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004558 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004559 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004560 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004561 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004562 if (F->getInc())
4563 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004564 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004565 }
Mike Stump31feda52009-07-17 01:31:16 +00004566
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004567 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004568 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004569 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004570 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004571 }
Mike Stump31feda52009-07-17 01:31:16 +00004572
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004573 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004574 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004575 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004576 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004577 }
Mike Stump31feda52009-07-17 01:31:16 +00004578
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004579 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004580 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004581 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004582 }
Mike Stump31feda52009-07-17 01:31:16 +00004583
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004584 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004585 OS << "try ...";
4586 }
4587
Nico Weber699670e2017-08-23 15:33:16 +00004588 void VisitSEHTryStmt(SEHTryStmt *CS) {
4589 OS << "__try ...";
4590 }
4591
John McCallc07a0c72011-02-17 10:25:35 +00004592 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004593 if (Stmt *Cond = C->getCond())
4594 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004595 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004596 }
Mike Stump31feda52009-07-17 01:31:16 +00004597
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004598 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004599 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004600 if (Stmt *Cond = C->getCond())
4601 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004602 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004603 }
Mike Stump31feda52009-07-17 01:31:16 +00004604
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004605 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004606 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004607 if (Stmt *T = I->getTarget())
4608 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004609 }
Mike Stump31feda52009-07-17 01:31:16 +00004610
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004611 void VisitBinaryOperator(BinaryOperator* B) {
4612 if (!B->isLogicalOp()) {
4613 VisitExpr(B);
4614 return;
4615 }
Mike Stump31feda52009-07-17 01:31:16 +00004616
Richard Trieuddd01ce2014-06-09 22:53:25 +00004617 if (B->getLHS())
4618 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004619
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004620 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004621 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004622 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004623 return;
John McCalle3027922010-08-25 11:45:40 +00004624 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004625 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004626 return;
4627 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004628 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004629 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004630 }
Mike Stump31feda52009-07-17 01:31:16 +00004631
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004632 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004633 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004634 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004635
4636public:
4637 void print(CFGTerminator T) {
4638 if (T.isTemporaryDtorsBranch())
4639 OS << "(Temp Dtor) ";
4640 Visit(T.getStmt());
4641 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004642};
Eugene Zelenko38c70522017-12-07 21:55:09 +00004643
4644} // namespace
Chris Lattnerc61089a2009-06-30 01:26:17 +00004645
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004646static void print_initializer(raw_ostream &OS, StmtPrinterHelper &Helper,
4647 const CXXCtorInitializer *I) {
4648 if (I->isBaseInitializer())
4649 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
4650 else if (I->isDelegatingInitializer())
4651 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
4652 else
4653 OS << I->getAnyMember()->getName();
4654 OS << "(";
4655 if (Expr *IE = I->getInit())
4656 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
4657 OS << ")";
4658
4659 if (I->isBaseInitializer())
4660 OS << " (Base initializer)";
4661 else if (I->isDelegatingInitializer())
4662 OS << " (Delegating initializer)";
4663 else
4664 OS << " (Member initializer)";
4665}
4666
Aaron Ballmanff924b02013-11-18 20:11:50 +00004667static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004668 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004669 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4670 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004671 assert(S != nullptr && "Expecting non-null Stmt");
4672
Aaron Ballmanff924b02013-11-18 20:11:50 +00004673 // special printing for statement-expressions.
4674 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4675 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004676
Benjamin Kramer5733e352015-07-18 17:09:36 +00004677 auto Children = Sub->children();
4678 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004679 OS << "({ ... ; ";
4680 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4681 OS << " })\n";
4682 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004683 }
4684 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004685 // special printing for comma expressions.
4686 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4687 if (B->getOpcode() == BO_Comma) {
4688 OS << "... , ";
4689 Helper.handledStmt(B->getRHS(),OS);
4690 OS << '\n';
4691 return;
4692 }
4693 }
4694 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004695
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004696 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004697 OS << " (OperatorCall)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004698 } else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004699 OS << " (BindTemporary)";
Artem Dergachev41ffb302018-02-08 22:58:15 +00004700 } else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4701 OS << " (CXXConstructExpr, ";
4702 if (Optional<CFGConstructor> CE = E.getAs<CFGConstructor>()) {
4703 if (const Stmt *S = CE->getTriggerStmt())
4704 Helper.handledStmt((const_cast<Stmt *>(S)), OS);
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004705 else if (const CXXCtorInitializer *I = CE->getTriggerInit())
4706 print_initializer(OS, Helper, I);
Artem Dergachev41ffb302018-02-08 22:58:15 +00004707 else
4708 llvm_unreachable("Unexpected trigger kind!");
4709 OS << ", ";
4710 }
4711 OS << CCE->getType().getAsString() << ")";
4712 } else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
Ted Kremenek0ffba932011-12-21 19:32:38 +00004713 OS << " (" << CE->getStmtClassName() << ", "
4714 << CE->getCastKindName()
4715 << ", " << CE->getType().getAsString()
4716 << ")";
4717 }
Mike Stump31feda52009-07-17 01:31:16 +00004718
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004719 // Expressions need a newline.
4720 if (isa<Expr>(S))
4721 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004722 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
Artem Dergachev5a281bb2018-02-10 02:18:04 +00004723 print_initializer(OS, Helper, IE->getInitializer());
4724 OS << '\n';
David Blaikie00be69a2013-02-23 00:29:34 +00004725 } else if (Optional<CFGAutomaticObjDtor> DE =
4726 E.getAs<CFGAutomaticObjDtor>()) {
4727 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004728 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004729
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004730 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004731 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4732 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004733 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004734
4735 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4736 OS << " (Implicit destructor)\n";
Matthias Gehre351c2182017-07-12 07:04:19 +00004737 } else if (Optional<CFGLifetimeEnds> DE = E.getAs<CFGLifetimeEnds>()) {
4738 const VarDecl *VD = DE->getVarDecl();
4739 Helper.handleDecl(VD, OS);
4740
4741 OS << " (Lifetime ends)\n";
Peter Szecsi999a25f2017-08-19 11:19:16 +00004742 } else if (Optional<CFGLoopExit> LE = E.getAs<CFGLoopExit>()) {
4743 const Stmt *LoopStmt = LE->getLoopStmt();
4744 OS << LoopStmt->getStmtClassName() << " (LoopExit)\n";
Jordan Rosec9176072014-01-13 17:59:19 +00004745 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4746 OS << "CFGNewAllocator(";
4747 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4748 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4749 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004750 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4751 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4752 if (!RD)
4753 return;
4754 CXXDeleteExpr *DelExpr =
4755 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004756 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004757 OS << "->~" << RD->getName().str() << "()";
4758 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004759 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4760 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004761 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004762 OS << " (Base object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004763 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4764 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004765 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004766 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004767 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004768 OS << " (Member object destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004769 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4770 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004771 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004772 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004773 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004774 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004775}
Mike Stump31feda52009-07-17 01:31:16 +00004776
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004777static void print_block(raw_ostream &OS, const CFG* cfg,
4778 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004779 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004780 bool ShowColors) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004781 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004782
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004783 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004784 if (ShowColors)
4785 OS.changeColor(raw_ostream::YELLOW, true);
4786
4787 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004788
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004789 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004790 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004791 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004792 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004793 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004794 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004795 else if (B.hasNoReturnElement())
4796 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004797 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004798 OS << "]\n";
4799
4800 if (ShowColors)
4801 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004802
Ted Kremenek71eca012007-08-29 23:20:49 +00004803 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004804 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004805 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004806 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004807
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004808 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004809 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004810 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004811 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004812 if (C->getLHS())
4813 C->getLHS()->printPretty(OS, &Helper,
4814 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004815 if (C->getRHS()) {
4816 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004817 C->getRHS()->printPretty(OS, &Helper,
4818 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004819 }
Mike Stump92244b02010-01-19 22:00:14 +00004820 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004821 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004822 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004823 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004824 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004825 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004826 0);
4827 else
4828 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004829 OS << ")";
Nico Weber699670e2017-08-23 15:33:16 +00004830 } else if (SEHExceptStmt *ES = dyn_cast<SEHExceptStmt>(Label)) {
4831 OS << "__except (";
4832 ES->getFilterExpr()->printPretty(OS, &Helper,
4833 PrintingPolicy(Helper.getLangOpts()), 0);
4834 OS << ")";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004835 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004836 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004837
Ted Kremenek71eca012007-08-29 23:20:49 +00004838 OS << ":\n";
4839 }
Mike Stump31feda52009-07-17 01:31:16 +00004840
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004841 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004842 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004843
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004844 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4845 I != E ; ++I, ++j ) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004846 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004847 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004848 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004849
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004850 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004851
Aaron Ballmanff924b02013-11-18 20:11:50 +00004852 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004853
Ted Kremenek72be32a2011-12-22 23:33:52 +00004854 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004855 }
Mike Stump31feda52009-07-17 01:31:16 +00004856
Ted Kremenek71eca012007-08-29 23:20:49 +00004857 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004858 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004859 if (ShowColors)
4860 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004861
Ted Kremenek72be32a2011-12-22 23:33:52 +00004862 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004863
Aaron Ballmanff924b02013-11-18 20:11:50 +00004864 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004865
Aaron Ballmanff924b02013-11-18 20:11:50 +00004866 PrintingPolicy PP(Helper.getLangOpts());
4867 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004868 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004869 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004870
4871 if (ShowColors)
4872 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004873 }
Mike Stump31feda52009-07-17 01:31:16 +00004874
Ted Kremenek71eca012007-08-29 23:20:49 +00004875 if (print_edges) {
4876 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004877 if (!B.pred_empty()) {
4878 const raw_ostream::Colors Color = raw_ostream::BLUE;
4879 if (ShowColors)
4880 OS.changeColor(Color);
4881 OS << " Preds " ;
4882 if (ShowColors)
4883 OS.resetColor();
4884 OS << '(' << B.pred_size() << "):";
4885 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004886
Ted Kremenek72be32a2011-12-22 23:33:52 +00004887 if (ShowColors)
4888 OS.changeColor(Color);
4889
4890 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4891 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004892 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004893 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004894
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004895 CFGBlock *B = *I;
4896 bool Reachable = true;
4897 if (!B) {
4898 Reachable = false;
4899 B = I->getPossiblyUnreachableBlock();
4900 }
4901
4902 OS << " B" << B->getBlockID();
4903 if (!Reachable)
4904 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004905 }
4906
4907 if (ShowColors)
4908 OS.resetColor();
4909
4910 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004911 }
Mike Stump31feda52009-07-17 01:31:16 +00004912
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004913 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004914 if (!B.succ_empty()) {
4915 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4916 if (ShowColors)
4917 OS.changeColor(Color);
4918 OS << " Succs ";
4919 if (ShowColors)
4920 OS.resetColor();
4921 OS << '(' << B.succ_size() << "):";
4922 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004923
Ted Kremenek72be32a2011-12-22 23:33:52 +00004924 if (ShowColors)
4925 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004926
Ted Kremenek72be32a2011-12-22 23:33:52 +00004927 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4928 I != E; ++I, ++i) {
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004929 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004930 OS << "\n ";
4931
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004932 CFGBlock *B = *I;
4933
4934 bool Reachable = true;
4935 if (!B) {
4936 Reachable = false;
4937 B = I->getPossiblyUnreachableBlock();
4938 }
4939
4940 if (B) {
4941 OS << " B" << B->getBlockID();
4942 if (!Reachable)
4943 OS << "(Unreachable)";
4944 }
4945 else {
4946 OS << " NULL";
4947 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004948 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004949
Ted Kremenek72be32a2011-12-22 23:33:52 +00004950 if (ShowColors)
4951 OS.resetColor();
4952 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004953 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004954 }
Mike Stump31feda52009-07-17 01:31:16 +00004955}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004956
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004957/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004958void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4959 print(llvm::errs(), LO, ShowColors);
4960}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004961
4962/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004963void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004964 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004965
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004966 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004967 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004968
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004969 // Iterate through the CFGBlocks and print them one by one.
4970 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4971 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004972 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004973 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004974
Aaron Ballmanff924b02013-11-18 20:11:50 +00004975 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004976 }
Mike Stump31feda52009-07-17 01:31:16 +00004977
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004978 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004979 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004980 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004981 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004982}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004983
4984/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004985void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4986 bool ShowColors) const {
4987 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004988}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004989
Yaron Kerencdae9412016-01-29 19:38:18 +00004990LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00004991 dump(getParent(), LangOptions(), false);
4992}
4993
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004994/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4995/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004996void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004997 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004998 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004999 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00005000 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00005001}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005002
Ted Kremenek15647632008-01-30 23:02:42 +00005003/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005004void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00005005 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00005006 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00005007 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00005008}
5009
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005010Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00005011 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005012 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00005013 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005014
Craig Topper25542942014-05-20 04:30:07 +00005015 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00005016
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005017 switch (Terminator->getStmtClass()) {
5018 default:
5019 break;
Mike Stump31feda52009-07-17 01:31:16 +00005020
Jordan Rosecf10ea82013-06-06 21:53:45 +00005021 case Stmt::CXXForRangeStmtClass:
5022 E = cast<CXXForRangeStmt>(Terminator)->getCond();
5023 break;
5024
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005025 case Stmt::ForStmtClass:
5026 E = cast<ForStmt>(Terminator)->getCond();
5027 break;
Mike Stump31feda52009-07-17 01:31:16 +00005028
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005029 case Stmt::WhileStmtClass:
5030 E = cast<WhileStmt>(Terminator)->getCond();
5031 break;
Mike Stump31feda52009-07-17 01:31:16 +00005032
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005033 case Stmt::DoStmtClass:
5034 E = cast<DoStmt>(Terminator)->getCond();
5035 break;
Mike Stump31feda52009-07-17 01:31:16 +00005036
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005037 case Stmt::IfStmtClass:
5038 E = cast<IfStmt>(Terminator)->getCond();
5039 break;
Mike Stump31feda52009-07-17 01:31:16 +00005040
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005041 case Stmt::ChooseExprClass:
5042 E = cast<ChooseExpr>(Terminator)->getCond();
5043 break;
Mike Stump31feda52009-07-17 01:31:16 +00005044
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005045 case Stmt::IndirectGotoStmtClass:
5046 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
5047 break;
Mike Stump31feda52009-07-17 01:31:16 +00005048
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005049 case Stmt::SwitchStmtClass:
5050 E = cast<SwitchStmt>(Terminator)->getCond();
5051 break;
Mike Stump31feda52009-07-17 01:31:16 +00005052
John McCallc07a0c72011-02-17 10:25:35 +00005053 case Stmt::BinaryConditionalOperatorClass:
5054 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
5055 break;
5056
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005057 case Stmt::ConditionalOperatorClass:
5058 E = cast<ConditionalOperator>(Terminator)->getCond();
5059 break;
Mike Stump31feda52009-07-17 01:31:16 +00005060
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005061 case Stmt::BinaryOperatorClass: // '&&' and '||'
5062 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005063 break;
Mike Stump31feda52009-07-17 01:31:16 +00005064
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00005065 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00005066 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005067 }
Mike Stump31feda52009-07-17 01:31:16 +00005068
Ted Kremenekec3bbf42014-03-29 00:35:20 +00005069 if (!StripParens)
5070 return E;
5071
Craig Topper25542942014-05-20 04:30:07 +00005072 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00005073}
5074
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005075//===----------------------------------------------------------------------===//
5076// CFG Graphviz Visualization
5077//===----------------------------------------------------------------------===//
5078
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005079#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00005080static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005081#endif
5082
Chris Lattnerc61089a2009-06-30 01:26:17 +00005083void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005084#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00005085 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005086 GraphHelper = &H;
5087 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00005088 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00005089#endif
5090}
5091
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005092namespace llvm {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005093
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005094template<>
5095struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Eugene Zelenko38c70522017-12-07 21:55:09 +00005096 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
Tobias Grosser9fc223a2009-11-30 14:16:05 +00005097
Ted Kremenek5ef32db2011-08-12 23:37:29 +00005098 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005099#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005100 std::string OutSStr;
5101 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00005102 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00005103 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005104
5105 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
5106
5107 // Process string output to make it nicer...
5108 for (unsigned i = 0; i != OutStr.length(); ++i)
5109 if (OutStr[i] == '\n') { // Left justify
5110 OutStr[i] = '\\';
5111 OutStr.insert(OutStr.begin()+i+1, 'l');
5112 }
Mike Stump31feda52009-07-17 01:31:16 +00005113
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005114 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005115#else
Eugene Zelenko38c70522017-12-07 21:55:09 +00005116 return {};
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00005117#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00005118 }
5119};
Eugene Zelenko38c70522017-12-07 21:55:09 +00005120
5121} // namespace llvm