blob: d7a9bdb3d82cd47d970f1b530179596b214564a2 [file] [log] [blame]
Richard Smitha547eb22016-07-14 00:11:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
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"
Ted Kremenek1a241d12011-02-23 05:11:46 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/PrettyPrinter.h"
21#include "clang/AST/StmtVisitor.h"
Jordan Rose5374c072013-08-19 16:27:28 +000022#include "clang/Basic/Builtins.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000023#include "llvm/ADT/DenseMap.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000024#include <memory>
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "llvm/ADT/SmallPtrSet.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000026#include "llvm/Support/Allocator.h"
27#include "llvm/Support/Format.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000028#include "llvm/Support/GraphWriter.h"
29#include "llvm/Support/SaveAndRestore.h"
Ted Kremeneke5ccf9a2008-01-11 00:40:29 +000030
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +000031using namespace clang;
32
33namespace {
34
Ted Kremenek5ef32db2011-08-12 23:37:29 +000035static SourceLocation GetEndLoc(Decl *D) {
36 if (VarDecl *VD = dyn_cast<VarDecl>(D))
37 if (Expr *Ex = VD->getInit())
Ted Kremenek8889bb32008-08-06 23:20:50 +000038 return Ex->getSourceRange().getEnd();
Mike Stump31feda52009-07-17 01:31:16 +000039 return D->getLocation();
Ted Kremenek8889bb32008-08-06 23:20:50 +000040}
Ted Kremenekdc03bd02010-08-02 23:46:59 +000041
George Burgess IVced56e62015-10-01 18:47:52 +000042/// Helper for tryNormalizeBinaryOperator. Attempts to extract an IntegerLiteral
43/// or EnumConstantDecl from the given Expr. If it fails, returns nullptr.
44const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
45 E = E->IgnoreParens();
46 if (isa<IntegerLiteral>(E))
47 return E;
48 if (auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
49 return isa<EnumConstantDecl>(DR->getDecl()) ? DR : nullptr;
50 return nullptr;
51}
52
53/// Tries to interpret a binary operator into `Decl Op Expr` form, if Expr is
54/// an integer literal or an enum constant.
55///
56/// If this fails, at least one of the returned DeclRefExpr or Expr will be
57/// null.
58static std::tuple<const DeclRefExpr *, BinaryOperatorKind, const Expr *>
59tryNormalizeBinaryOperator(const BinaryOperator *B) {
60 BinaryOperatorKind Op = B->getOpcode();
61
62 const Expr *MaybeDecl = B->getLHS();
63 const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
64 // Expr looked like `0 == Foo` instead of `Foo == 0`
65 if (Constant == nullptr) {
66 // Flip the operator
67 if (Op == BO_GT)
68 Op = BO_LT;
69 else if (Op == BO_GE)
70 Op = BO_LE;
71 else if (Op == BO_LT)
72 Op = BO_GT;
73 else if (Op == BO_LE)
74 Op = BO_GE;
75
76 MaybeDecl = B->getRHS();
77 Constant = tryTransformToIntOrEnumConstant(B->getLHS());
78 }
79
80 auto *D = dyn_cast<DeclRefExpr>(MaybeDecl->IgnoreParenImpCasts());
81 return std::make_tuple(D, Op, Constant);
82}
83
84/// For an expression `x == Foo && x == Bar`, this determines whether the
85/// `Foo` and `Bar` are either of the same enumeration type, or both integer
86/// literals.
87///
88/// It's an error to pass this arguments that are not either IntegerLiterals
89/// or DeclRefExprs (that have decls of type EnumConstantDecl)
90static bool areExprTypesCompatible(const Expr *E1, const Expr *E2) {
91 // User intent isn't clear if they're mixing int literals with enum
92 // constants.
93 if (isa<IntegerLiteral>(E1) != isa<IntegerLiteral>(E2))
94 return false;
95
96 // Integer literal comparisons, regardless of literal type, are acceptable.
97 if (isa<IntegerLiteral>(E1))
98 return true;
99
100 // IntegerLiterals are handled above and only EnumConstantDecls are expected
101 // beyond this point
102 assert(isa<DeclRefExpr>(E1) && isa<DeclRefExpr>(E2));
103 auto *Decl1 = cast<DeclRefExpr>(E1)->getDecl();
104 auto *Decl2 = cast<DeclRefExpr>(E2)->getDecl();
105
106 assert(isa<EnumConstantDecl>(Decl1) && isa<EnumConstantDecl>(Decl2));
107 const DeclContext *DC1 = Decl1->getDeclContext();
108 const DeclContext *DC2 = Decl2->getDeclContext();
109
110 assert(isa<EnumDecl>(DC1) && isa<EnumDecl>(DC2));
111 return DC1 == DC2;
112}
113
Ted Kremenek7c58d352011-03-10 01:14:11 +0000114class CFGBuilder;
115
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000116/// The CFG builder uses a recursive algorithm to build the CFG. When
117/// we process an expression, sometimes we know that we must add the
118/// subexpressions as block-level expressions. For example:
119///
120/// exp1 || exp2
121///
122/// When processing the '||' expression, we know that exp1 and exp2
123/// need to be added as block-level expressions, even though they
124/// might not normally need to be. AddStmtChoice records this
125/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
126/// the builder has an option not to add a subexpression as a
127/// block-level expression.
128///
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000129class AddStmtChoice {
130public:
Ted Kremenek8219b822010-12-16 07:46:53 +0000131 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000132
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000133 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +0000134
Ted Kremenek7c58d352011-03-10 01:14:11 +0000135 bool alwaysAdd(CFGBuilder &builder,
136 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000137
138 /// Return a copy of this object, except with the 'always-add' bit
139 /// set as specified.
140 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +0000141 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000142 }
143
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000144private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +0000145 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000146};
Mike Stump31feda52009-07-17 01:31:16 +0000147
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000148/// LocalScope - Node in tree of local scopes created for C++ implicit
149/// destructor calls generation. It contains list of automatic variables
150/// declared in the scope and link to position in previous scope this scope
151/// began in.
152///
153/// The process of creating local scopes is as follows:
154/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
155/// - Before processing statements in scope (e.g. CompoundStmt) create
156/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
157/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000158/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000159/// at this VarDecl,
160/// - For every normal (without jump) end of scope add to CFGBlock destructors
161/// for objects in the current scope,
162/// - For every jump add to CFGBlock destructors for objects
163/// between CFGBuilder::ScopePos and local scope position saved for jump
164/// target. Thanks to C++ restrictions on goto jumps we can be sure that
165/// jump target position will be on the path to root from CFGBuilder::ScopePos
166/// (adding any variable that doesn't need constructor to be called to
167/// LocalScope can break this assumption),
168///
169class LocalScope {
170public:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000171 typedef BumpVector<VarDecl*> AutomaticVarsTy;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000172
173 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000174 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000175 class const_iterator {
176 const LocalScope* Scope;
177
178 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
179 /// Invalid iterator (with null Scope) has VarIter equal to 0.
180 unsigned VarIter;
181
182 public:
183 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
184 /// Incrementing invalid iterator is allowed and will result in invalid
185 /// iterator.
186 const_iterator()
Craig Topper25542942014-05-20 04:30:07 +0000187 : Scope(nullptr), VarIter(0) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000188
189 /// Create valid iterator. In case when S.Prev is an invalid iterator and
190 /// I is equal to 0, this will create invalid iterator.
191 const_iterator(const LocalScope& S, unsigned I)
192 : Scope(&S), VarIter(I) {
193 // Iterator to "end" of scope is not allowed. Handle it by going up
194 // in scopes tree possibly up to invalid iterator in the root.
195 if (VarIter == 0 && Scope)
196 *this = Scope->Prev;
197 }
198
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000199 VarDecl *const* operator->() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000200 assert (Scope && "Dereferencing invalid iterator is not allowed");
201 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
202 return &Scope->Vars[VarIter - 1];
203 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000204 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000205 return *this->operator->();
206 }
207
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000208 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209 if (!Scope)
210 return *this;
211
212 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
213 --VarIter;
214 if (VarIter == 0)
215 *this = Scope->Prev;
216 return *this;
217 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000218 const_iterator operator++(int) {
219 const_iterator P = *this;
220 ++*this;
221 return P;
222 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000223
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000224 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000225 return Scope == rhs.Scope && VarIter == rhs.VarIter;
226 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000227 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000228 return !(*this == rhs);
229 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000230
Aaron Ballman67347662015-02-15 22:00:28 +0000231 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000232 return *this != const_iterator();
233 }
234
235 int distance(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000236 };
237
238 friend class const_iterator;
239
240private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000241 BumpVectorContext ctx;
242
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000243 /// Automatic variables in order of declaration.
244 AutomaticVarsTy Vars;
245 /// Iterator to variable in previous scope that was declared just before
246 /// begin of this scope.
247 const_iterator Prev;
248
249public:
250 /// Constructs empty scope linked to previous scope in specified place.
David Blaikiec1334cc2015-08-13 22:12:21 +0000251 LocalScope(BumpVectorContext ctx, const_iterator P)
252 : ctx(std::move(ctx)), Vars(this->ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000253
254 /// Begin of scope in direction of CFG building (backwards).
255 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000256
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000257 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000258 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000259 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000260};
261
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000262/// distance - Calculates distance from this to L. L must be reachable from this
263/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
264/// number of scopes between this and L.
265int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
266 int D = 0;
267 const_iterator F = *this;
268 while (F.Scope != L.Scope) {
Ted Kremenek50aa2d42011-08-12 14:41:23 +0000269 assert (F != const_iterator()
270 && "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000271 D += F.VarIter;
272 F = F.Scope->Prev;
273 }
274 D += F.VarIter - L.VarIter;
275 return D;
276}
277
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000278/// Structure for specifying position in CFG during its build process. It
279/// consists of CFGBlock that specifies position in CFG and
280/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000281struct BlockScopePosPair {
Craig Topper25542942014-05-20 04:30:07 +0000282 BlockScopePosPair() : block(nullptr) {}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000283 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000284 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000285
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000286 CFGBlock *block;
287 LocalScope::const_iterator scopePosition;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000288};
289
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000290/// TryResult - a class representing a variant over the values
291/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
292/// and is used by the CFGBuilder to decide if a branch condition
293/// can be decided up front during CFG construction.
294class TryResult {
295 int X;
296public:
297 TryResult(bool b) : X(b ? 1 : 0) {}
298 TryResult() : X(-1) {}
299
300 bool isTrue() const { return X == 1; }
301 bool isFalse() const { return X == 0; }
302 bool isKnown() const { return X >= 0; }
303 void negate() {
304 assert(isKnown());
305 X ^= 0x1;
306 }
307};
308
Manuel Klimekdeb02622014-08-08 07:37:13 +0000309TryResult bothKnownTrue(TryResult R1, TryResult R2) {
310 if (!R1.isKnown() || !R2.isKnown())
311 return TryResult();
312 return TryResult(R1.isTrue() && R2.isTrue());
313}
314
Ted Kremenek8ae67872013-02-05 22:00:19 +0000315class reverse_children {
316 llvm::SmallVector<Stmt *, 12> childrenBuf;
317 ArrayRef<Stmt*> children;
318public:
319 reverse_children(Stmt *S);
320
321 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
322 iterator begin() const { return children.rbegin(); }
323 iterator end() const { return children.rend(); }
324};
325
326
327reverse_children::reverse_children(Stmt *S) {
328 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
329 children = CE->getRawSubExprs();
330 return;
331 }
332 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000333 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000334 case Stmt::InitListExprClass: {
335 InitListExpr *IE = cast<InitListExpr>(S);
336 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
337 IE->getNumInits());
338 return;
339 }
340 default:
341 break;
342 }
343
344 // Default case for all other statements.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000345 for (Stmt *SubStmt : S->children())
346 childrenBuf.push_back(SubStmt);
Ted Kremenek8ae67872013-02-05 22:00:19 +0000347
348 // This needs to be done *after* childrenBuf has been populated.
349 children = childrenBuf;
350}
351
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000352/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000353/// The builder is stateful: an instance of the builder should be used to only
354/// construct a single CFG.
355///
356/// Example usage:
357///
358/// CFGBuilder builder;
Jonathan Roelofsab046c52015-07-27 16:05:36 +0000359/// std::unique_ptr<CFG> cfg = builder.buildCFG(decl, stmt1);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000360///
Mike Stump31feda52009-07-17 01:31:16 +0000361/// CFG construction is done via a recursive walk of an AST. We actually parse
362/// the AST in reverse order so that the successor of a basic block is
363/// constructed prior to its predecessor. This allows us to nicely capture
364/// implicit fall-throughs without extra basic blocks.
Ted Kremenek1b8ac852007-08-21 22:06:14 +0000365///
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000366class CFGBuilder {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000367 typedef BlockScopePosPair JumpTarget;
368 typedef BlockScopePosPair JumpSource;
369
Mike Stump0d76d072009-07-20 23:24:15 +0000370 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000371 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000372
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000373 CFGBlock *Block;
374 CFGBlock *Succ;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000375 JumpTarget ContinueJumpTarget;
376 JumpTarget BreakJumpTarget;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000377 CFGBlock *SwitchTerminatedBlock;
378 CFGBlock *DefaultCaseBlock;
379 CFGBlock *TryTerminatedBlock;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000380
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000381 // Current position in local scope.
382 LocalScope::const_iterator ScopePos;
383
384 // LabelMap records the mapping from Label expressions to their jump targets.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000385 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000386 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000387
388 // A list of blocks that end with a "goto" that must be backpatched to their
389 // resolved targets upon completion of CFG construction.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000390 typedef std::vector<JumpSource> BackpatchBlocksTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000391 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000392
Ted Kremenekeda180e22007-08-28 19:26:49 +0000393 // A list of labels whose address has been taken (for indirect gotos).
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000394 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000395 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000396
Zhongxing Xud38fb842010-09-16 03:28:18 +0000397 bool badCFG;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000398 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000399
400 // State to track for building switch statements.
401 bool switchExclusivelyCovered;
Ted Kremenekbe528712011-03-04 01:03:41 +0000402 Expr::EvalResult *switchCond;
Ted Kremeneka099c592011-03-10 03:50:34 +0000403
404 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000405 const Stmt *lastLookup;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000406
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000407 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
408 // during construction of branches for chained logical operators.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000409 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
410 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000411
Mike Stump31feda52009-07-17 01:31:16 +0000412public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000413 explicit CFGBuilder(ASTContext *astContext,
414 const CFG::BuildOptions &buildOpts)
415 : Context(astContext), cfg(new CFG()), // crew a new CFG
Craig Topper25542942014-05-20 04:30:07 +0000416 Block(nullptr), Succ(nullptr),
417 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
418 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
419 switchExclusivelyCovered(false), switchCond(nullptr),
420 cachedEntry(nullptr), lastLookup(nullptr) {}
Mike Stump31feda52009-07-17 01:31:16 +0000421
Ted Kremenek9aae5132007-08-23 21:42:29 +0000422 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000423 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000424
Ted Kremeneka099c592011-03-10 03:50:34 +0000425 bool alwaysAdd(const Stmt *stmt);
426
Ted Kremenek93668002009-07-17 22:18:43 +0000427private:
428 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000429 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
430 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000431 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000432 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000433 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000434 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000435 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000436 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
437 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000438 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000439 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
440 AddStmtChoice asc);
441 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
442 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000443 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000444 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000445 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
446 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
447 AddStmtChoice asc);
448 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
449 AddStmtChoice asc);
450 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
451 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000452 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000453 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000454 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
455 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000456 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000457 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000458 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000459 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000460 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000461 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
462 CFGBlock *VisitLabelStmt(LabelStmt *L);
Devin Coughlinb6029b72015-11-25 22:35:37 +0000463 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000464 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000465 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000466 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
467 Stmt *Term,
468 CFGBlock *TrueBlock,
469 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000470 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000471 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
472 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
473 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
474 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000475 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000476 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000477 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000478 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000479 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000480 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000481 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
482 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000483 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000484 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000485
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000486 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
487 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000488 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000489 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000490
Manuel Klimekb5616c92014-08-07 10:42:17 +0000491 /// When creating the CFG for temporary destructors, we want to mirror the
492 /// branch structure of the corresponding constructor calls.
493 /// Thus, while visiting a statement for temporary destructors, we keep a
494 /// context to keep track of the following information:
495 /// - whether a subexpression is executed unconditionally
496 /// - if a subexpression is executed conditionally, the first
497 /// CXXBindTemporaryExpr we encounter in that subexpression (which
498 /// corresponds to the last temporary destructor we have to call for this
499 /// subexpression) and the CFG block at that point (which will become the
500 /// successor block when inserting the decision point).
501 ///
502 /// That way, we can build the branch structure for temporary destructors as
503 /// follows:
504 /// 1. If a subexpression is executed unconditionally, we add the temporary
505 /// destructor calls to the current block.
506 /// 2. If a subexpression is executed conditionally, when we encounter a
507 /// CXXBindTemporaryExpr:
508 /// a) If it is the first temporary destructor call in the subexpression,
509 /// we remember the CXXBindTemporaryExpr and the current block in the
510 /// TempDtorContext; we start a new block, and insert the temporary
511 /// destructor call.
512 /// b) Otherwise, add the temporary destructor call to the current block.
513 /// 3. When we finished visiting a conditionally executed subexpression,
514 /// and we found at least one temporary constructor during the visitation
515 /// (2.a has executed), we insert a decision block that uses the
516 /// CXXBindTemporaryExpr as terminator, and branches to the current block
517 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
518 /// branches to the stored successor.
519 struct TempDtorContext {
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000520 TempDtorContext()
521 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
522 TerminatorExpr(nullptr) {}
Manuel Klimekdeb02622014-08-08 07:37:13 +0000523
524 TempDtorContext(TryResult KnownExecuted)
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000525 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
526 TerminatorExpr(nullptr) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000527
528 /// Returns whether we need to start a new branch for a temporary destructor
Eric Christopher2c4555a2015-06-19 01:52:53 +0000529 /// call. This is the case when the temporary destructor is
Manuel Klimekb5616c92014-08-07 10:42:17 +0000530 /// conditionally executed, and it is the first one we encounter while
531 /// visiting a subexpression - other temporary destructors at the same level
532 /// will be added to the same block and are executed under the same
533 /// condition.
534 bool needsTempDtorBranch() const {
535 return IsConditional && !TerminatorExpr;
536 }
537
538 /// Remember the successor S of a temporary destructor decision branch for
539 /// the corresponding CXXBindTemporaryExpr E.
540 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
541 Succ = S;
542 TerminatorExpr = E;
543 }
544
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000545 const bool IsConditional;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000546 const TryResult KnownExecuted;
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000547 CFGBlock *Succ;
548 CXXBindTemporaryExpr *TerminatorExpr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000549 };
550
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000551 // Visitors to walk an AST and generate destructors of temporaries in
552 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000553 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
554 TempDtorContext &Context);
555 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
556 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
557 TempDtorContext &Context);
558 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
559 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
560 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
561 AbstractConditionalOperator *E, bool BindToTemporary,
562 TempDtorContext &Context);
563 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
564 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000565
Ted Kremenek6065ef62008-04-28 18:00:46 +0000566 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000567 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000568 badCFG = true;
569 return Block;
570 }
Mike Stump31feda52009-07-17 01:31:16 +0000571
Ted Kremenek93668002009-07-17 22:18:43 +0000572 void autoCreateBlock() { if (!Block) Block = createBlock(); }
573 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000574 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000575
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000576 CFGBlock *addStmt(Stmt *S) {
577 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000578 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000579 CFGBlock *addInitializer(CXXCtorInitializer *I);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000580 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000581 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000582 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000583
Marcin Swiderski5e415732010-09-30 23:05:00 +0000584 // Local scopes creation.
585 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
586
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000587 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000588 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
589 LocalScope* Scope = nullptr);
590 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000591
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000592 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000593
594 // Interface to CFGBlock - adding CFGElements.
Ted Kremenek37881932011-04-04 23:29:12 +0000595 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000596 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000597 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000598
Jordy Rose17347372011-06-10 08:49:37 +0000599 // All block-level expressions should have already been IgnoreParens()ed.
600 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000601 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000602 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000603 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000604 B->appendInitializer(I, cfg->getBumpVectorContext());
605 }
Jordan Rosec9176072014-01-13 17:59:19 +0000606 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
607 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
608 }
Marcin Swiderski20b88732010-10-05 05:37:00 +0000609 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
610 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
611 }
612 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
613 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
614 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000615 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
616 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
617 }
Chandler Carruthad747252011-09-13 06:09:01 +0000618 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
619 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
620 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000621
Jordan Rosed2f40792013-09-03 17:00:57 +0000622 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
623 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
624 }
625
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000626 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000627 LocalScope::const_iterator B, LocalScope::const_iterator E);
628
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000629 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
630 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
631 cfg->getBumpVectorContext());
632 }
633
634 /// Add a reachable successor to a block, with the alternate variant that is
635 /// unreachable.
636 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
637 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
638 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000639 }
Mike Stump11289f42009-09-09 15:08:12 +0000640
Richard Trieuf935b562014-04-05 05:17:01 +0000641 /// \brief Find a relational comparison with an expression evaluating to a
642 /// boolean and a constant other than 0 and 1.
643 /// e.g. if ((x < y) == 10)
644 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
645 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
646 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
647
648 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
649 const Expr *BoolExpr = RHSExpr;
650 bool IntFirst = true;
651 if (!IntLiteral) {
652 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
653 BoolExpr = LHSExpr;
654 IntFirst = false;
655 }
656
657 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
658 return TryResult();
659
660 llvm::APInt IntValue = IntLiteral->getValue();
661 if ((IntValue == 1) || (IntValue == 0))
662 return TryResult();
663
664 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
665 !IntValue.isNegative();
666
667 BinaryOperatorKind Bok = B->getOpcode();
668 if (Bok == BO_GT || Bok == BO_GE) {
669 // Always true for 10 > bool and bool > -1
670 // Always false for -1 > bool and bool > 10
671 return TryResult(IntFirst == IntLarger);
672 } else {
673 // Always true for -1 < bool and bool < 10
674 // Always false for 10 < bool and bool < -1
675 return TryResult(IntFirst != IntLarger);
676 }
677 }
678
Jordan Rose7afd71e2014-05-20 17:31:11 +0000679 /// Find an incorrect equality comparison. Either with an expression
680 /// evaluating to a boolean and a constant other than 0 and 1.
681 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
682 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000683 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
684 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
685 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
686
687 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
688 const Expr *BoolExpr = RHSExpr;
689
690 if (!IntLiteral) {
691 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
692 BoolExpr = LHSExpr;
693 }
694
Jordan Rose7afd71e2014-05-20 17:31:11 +0000695 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000696 return TryResult();
697
Jordan Rose7afd71e2014-05-20 17:31:11 +0000698 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
699 if (BitOp && (BitOp->getOpcode() == BO_And ||
700 BitOp->getOpcode() == BO_Or)) {
701 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
702 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
703
704 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
705
706 if (!IntLiteral2)
707 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
708
709 if (!IntLiteral2)
710 return TryResult();
711
712 llvm::APInt L1 = IntLiteral->getValue();
713 llvm::APInt L2 = IntLiteral2->getValue();
714 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
715 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
716 if (BuildOpts.Observer)
717 BuildOpts.Observer->compareBitwiseEquality(B,
718 B->getOpcode() != BO_EQ);
719 TryResult(B->getOpcode() != BO_EQ);
720 }
721 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
722 llvm::APInt IntValue = IntLiteral->getValue();
723 if ((IntValue == 1) || (IntValue == 0)) {
724 return TryResult();
725 }
726 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000727 }
728
Jordan Rose7afd71e2014-05-20 17:31:11 +0000729 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000730 }
731
732 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
733 const llvm::APSInt &Value1,
734 const llvm::APSInt &Value2) {
735 assert(Value1.isSigned() == Value2.isSigned());
736 switch (Relation) {
737 default:
738 return TryResult();
739 case BO_EQ:
740 return TryResult(Value1 == Value2);
741 case BO_NE:
742 return TryResult(Value1 != Value2);
743 case BO_LT:
744 return TryResult(Value1 < Value2);
745 case BO_LE:
746 return TryResult(Value1 <= Value2);
747 case BO_GT:
748 return TryResult(Value1 > Value2);
749 case BO_GE:
750 return TryResult(Value1 >= Value2);
751 }
752 }
753
754 /// \brief Find a pair of comparison expressions with or without parentheses
755 /// with a shared variable and constants and a logical operator between them
756 /// that always evaluates to either true or false.
757 /// e.g. if (x != 3 || x != 4)
758 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
759 assert(B->isLogicalOp());
760 const BinaryOperator *LHS =
761 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
762 const BinaryOperator *RHS =
763 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
764 if (!LHS || !RHS)
765 return TryResult();
766
767 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
768 return TryResult();
769
George Burgess IVced56e62015-10-01 18:47:52 +0000770 const DeclRefExpr *Decl1;
771 const Expr *Expr1;
772 BinaryOperatorKind BO1;
773 std::tie(Decl1, BO1, Expr1) = tryNormalizeBinaryOperator(LHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000774
George Burgess IVced56e62015-10-01 18:47:52 +0000775 if (!Decl1 || !Expr1)
Richard Trieuf935b562014-04-05 05:17:01 +0000776 return TryResult();
777
George Burgess IVced56e62015-10-01 18:47:52 +0000778 const DeclRefExpr *Decl2;
779 const Expr *Expr2;
780 BinaryOperatorKind BO2;
781 std::tie(Decl2, BO2, Expr2) = tryNormalizeBinaryOperator(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +0000782
George Burgess IVced56e62015-10-01 18:47:52 +0000783 if (!Decl2 || !Expr2)
Richard Trieuf935b562014-04-05 05:17:01 +0000784 return TryResult();
785
786 // Check that it is the same variable on both sides.
787 if (Decl1->getDecl() != Decl2->getDecl())
788 return TryResult();
789
George Burgess IVced56e62015-10-01 18:47:52 +0000790 // Make sure the user's intent is clear (e.g. they're comparing against two
791 // int literals, or two things from the same enum)
792 if (!areExprTypesCompatible(Expr1, Expr2))
793 return TryResult();
794
Richard Trieuf935b562014-04-05 05:17:01 +0000795 llvm::APSInt L1, L2;
796
George Burgess IVced56e62015-10-01 18:47:52 +0000797 if (!Expr1->EvaluateAsInt(L1, *Context) ||
798 !Expr2->EvaluateAsInt(L2, *Context))
Richard Trieuf935b562014-04-05 05:17:01 +0000799 return TryResult();
800
801 // Can't compare signed with unsigned or with different bit width.
802 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
803 return TryResult();
804
805 // Values that will be used to determine if result of logical
806 // operator is always true/false
807 const llvm::APSInt Values[] = {
808 // Value less than both Value1 and Value2
809 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
810 // L1
811 L1,
812 // Value between Value1 and Value2
813 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
814 L1.isUnsigned()),
815 // L2
816 L2,
817 // Value greater than both Value1 and Value2
818 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
819 };
820
821 // Check whether expression is always true/false by evaluating the following
822 // * variable x is less than the smallest literal.
823 // * variable x is equal to the smallest literal.
824 // * Variable x is between smallest and largest literal.
825 // * Variable x is equal to the largest literal.
826 // * Variable x is greater than largest literal.
827 bool AlwaysTrue = true, AlwaysFalse = true;
Benjamin Kramer2e018ef2016-05-27 13:36:58 +0000828 for (const llvm::APSInt &Value : Values) {
Richard Trieuf935b562014-04-05 05:17:01 +0000829 TryResult Res1, Res2;
830 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
831 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
832
833 if (!Res1.isKnown() || !Res2.isKnown())
834 return TryResult();
835
836 if (B->getOpcode() == BO_LAnd) {
837 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
838 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
839 } else {
840 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
841 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
842 }
843 }
844
845 if (AlwaysTrue || AlwaysFalse) {
846 if (BuildOpts.Observer)
847 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
848 return TryResult(AlwaysTrue);
849 }
850 return TryResult();
851 }
852
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000853 /// Try and evaluate an expression to an integer constant.
854 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
855 if (!BuildOpts.PruneTriviallyFalseEdges)
856 return false;
857 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000858 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000859 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000860 }
Mike Stump11289f42009-09-09 15:08:12 +0000861
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000862 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000863 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000864 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000865 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000866 S->isTypeDependent() || S->isValueDependent())
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000867 return TryResult();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000868
869 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
870 if (Bop->isLogicalOp()) {
871 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000872 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
873 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000874 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +0000875
876 // Retrieve result at first, or the map might be updated.
877 TryResult Result = evaluateAsBooleanConditionNoCache(S);
878 CachedBoolEvals[S] = Result; // update or insert
879 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000880 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000881 else {
882 switch (Bop->getOpcode()) {
883 default: break;
884 // For 'x & 0' and 'x * 0', we can determine that
885 // the value is always false.
886 case BO_Mul:
887 case BO_And: {
888 // If either operand is zero, we know the value
889 // must be false.
890 llvm::APSInt IntVal;
891 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000892 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000893 return TryResult(false);
894 }
895 }
896 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000897 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000898 return TryResult(false);
899 }
900 }
901 }
902 break;
903 }
904 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000905 }
906
907 return evaluateAsBooleanConditionNoCache(S);
908 }
909
910 /// \brief Evaluate as boolean \param E without using the cache.
911 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
912 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
913 if (Bop->isLogicalOp()) {
914 TryResult LHS = tryEvaluateBool(Bop->getLHS());
915 if (LHS.isKnown()) {
916 // We were able to evaluate the LHS, see if we can get away with not
917 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
918 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
919 return LHS.isTrue();
920
921 TryResult RHS = tryEvaluateBool(Bop->getRHS());
922 if (RHS.isKnown()) {
923 if (Bop->getOpcode() == BO_LOr)
924 return LHS.isTrue() || RHS.isTrue();
925 else
926 return LHS.isTrue() && RHS.isTrue();
927 }
928 } else {
929 TryResult RHS = tryEvaluateBool(Bop->getRHS());
930 if (RHS.isKnown()) {
931 // We can't evaluate the LHS; however, sometimes the result
932 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
933 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
934 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +0000935 } else {
936 TryResult BopRes = checkIncorrectLogicOperator(Bop);
937 if (BopRes.isKnown())
938 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000939 }
940 }
941
942 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000943 } else if (Bop->isEqualityOp()) {
944 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
945 if (BopRes.isKnown())
946 return BopRes.isTrue();
947 } else if (Bop->isRelationalOp()) {
948 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
949 if (BopRes.isKnown())
950 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000951 }
952 }
953
954 bool Result;
955 if (E->EvaluateAsBooleanCondition(Result, *Context))
956 return Result;
957
958 return TryResult();
Mike Stump773582d2009-07-23 23:25:26 +0000959 }
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000960
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000961};
Mike Stump31feda52009-07-17 01:31:16 +0000962
Ted Kremeneka099c592011-03-10 03:50:34 +0000963inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
964 const Stmt *stmt) const {
965 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
966}
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000967
Ted Kremeneka099c592011-03-10 03:50:34 +0000968bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000969 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
970
Ted Kremeneka099c592011-03-10 03:50:34 +0000971 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +0000972 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000973
974 if (lastLookup == stmt) {
975 if (cachedEntry) {
976 assert(cachedEntry->first == stmt);
977 return true;
978 }
Ted Kremenek8b46c002011-07-19 14:18:43 +0000979 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000980 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000981
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000982 lastLookup = stmt;
983
984 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +0000985 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
986
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000987 if (!fb) {
988 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +0000989 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +0000990 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000991 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000992
993 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000994 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +0000995 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +0000996 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000997 }
998
Ted Kremeneka099c592011-03-10 03:50:34 +0000999 cachedEntry = &*itr;
1000 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +00001001}
1002
Douglas Gregor4619e432008-12-05 23:32:09 +00001003// FIXME: Add support for dependent-sized array types in C++?
1004// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +00001005static const VariableArrayType *FindVA(const Type *t) {
1006 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
1007 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001008 if (vat->getSizeExpr())
1009 return vat;
Mike Stump31feda52009-07-17 01:31:16 +00001010
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001011 t = vt->getElementType().getTypePtr();
1012 }
Mike Stump31feda52009-07-17 01:31:16 +00001013
Craig Topper25542942014-05-20 04:30:07 +00001014 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +00001015}
Mike Stump31feda52009-07-17 01:31:16 +00001016
1017/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
1018/// arbitrary statement. Examples include a single expression or a function
1019/// body (compound statement). The ownership of the returned CFG is
1020/// transferred to the caller. If CFG construction fails, this method returns
1021/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +00001022std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +00001023 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +00001024 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +00001025 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001026
Mike Stump31feda52009-07-17 01:31:16 +00001027 // Create an empty block that will serve as the exit block for the CFG. Since
1028 // this is the first block added to the CFG, it will be implicitly registered
1029 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +00001030 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +00001031 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +00001032 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +00001033
Marcin Swiderski20b88732010-10-05 05:37:00 +00001034 if (BuildOpts.AddImplicitDtors)
1035 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
1036 addImplicitDtorsForDestructor(DD);
1037
Ted Kremenek9aae5132007-08-23 21:42:29 +00001038 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001039 CFGBlock *B = addStmt(Statement);
1040
1041 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001042 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001043
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001044 // For C++ constructor add initializers to CFG.
1045 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
Pete Cooper57d3f142015-07-30 17:22:52 +00001046 for (auto *I : llvm::reverse(CD->inits())) {
1047 B = addInitializer(I);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001048 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001049 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001050 }
1051 }
1052
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001053 if (B)
1054 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001055
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001056 // Backpatch the gotos whose label -> block mappings we didn't know when we
1057 // encountered them.
1058 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1059 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001060
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001061 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001062 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001063 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001064
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001065 // If there is no target for the goto, then we are looking at an
1066 // incomplete AST. Handle this by not registering a successor.
1067 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001068
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001069 JumpTarget JT = LI->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001070 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1071 JT.scopePosition);
1072 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001073 }
1074
1075 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001076 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001077 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1078 E = AddressTakenLabels.end(); I != E; ++I ) {
1079
1080 // Lookup the target block.
1081 LabelMapTy::iterator LI = LabelMap.find(*I);
1082
1083 // If there is no target block that contains label, then we are looking
1084 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001085 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001086
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001087 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001088 }
Mike Stump31feda52009-07-17 01:31:16 +00001089
Mike Stump31feda52009-07-17 01:31:16 +00001090 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001091 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001092
David Blaikiee90195c2014-08-29 18:53:26 +00001093 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001094}
Mike Stump31feda52009-07-17 01:31:16 +00001095
Ted Kremenek9aae5132007-08-23 21:42:29 +00001096/// createBlock - Used to lazily create blocks that are connected
1097/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001098CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1099 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001100 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001101 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001102 return B;
1103}
Mike Stump31feda52009-07-17 01:31:16 +00001104
Chandler Carrutha70991b2011-09-13 09:13:49 +00001105/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1106/// CFG. It is *not* connected to the current (global) successor, and instead
1107/// directly tied to the exit block in order to be reachable.
1108CFGBlock *CFGBuilder::createNoReturnBlock() {
1109 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001110 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001111 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001112 return B;
1113}
1114
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001115/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001116CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001117 if (!BuildOpts.AddInitializers)
1118 return Block;
1119
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001120 bool HasTemporaries = false;
1121
1122 // Destructors of temporaries in initialization expression should be called
1123 // after initialization finishes.
1124 Expr *Init = I->getInit();
1125 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001126 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001127
Jordan Rose6d671cc2012-09-05 22:55:23 +00001128 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001129 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001130 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001131 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1132 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001133 }
1134 }
1135
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001136 autoCreateBlock();
1137 appendInitializer(Block, I);
1138
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001139 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001140 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001141 // For expression with temporaries go directly to subexpression to omit
1142 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001143 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1144 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001145 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1146 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1147 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1148 // may cause the same Expr to appear more than once in the CFG. Doing it
1149 // here is safe because there's only one initializer per field.
1150 autoCreateBlock();
1151 appendStmt(Block, Default);
1152 if (Stmt *Child = Default->getExpr())
1153 if (CFGBlock *R = Visit(Child))
1154 Block = R;
1155 return Block;
1156 }
1157 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001158 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001159 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001160
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001161 return Block;
1162}
1163
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001164/// \brief Retrieve the type of the temporary object whose lifetime was
1165/// extended by a local reference with the given initializer.
1166static QualType getReferenceInitTemporaryType(ASTContext &Context,
1167 const Expr *Init) {
1168 while (true) {
1169 // Skip parentheses.
1170 Init = Init->IgnoreParens();
1171
1172 // Skip through cleanups.
1173 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1174 Init = EWC->getSubExpr();
1175 continue;
1176 }
1177
1178 // Skip through the temporary-materialization expression.
1179 if (const MaterializeTemporaryExpr *MTE
1180 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1181 Init = MTE->GetTemporaryExpr();
1182 continue;
1183 }
1184
1185 // Skip derived-to-base and no-op casts.
1186 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1187 if ((CE->getCastKind() == CK_DerivedToBase ||
1188 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1189 CE->getCastKind() == CK_NoOp) &&
1190 Init->getType()->isRecordType()) {
1191 Init = CE->getSubExpr();
1192 continue;
1193 }
1194 }
1195
1196 // Skip member accesses into rvalues.
1197 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1198 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1199 Init = ME->getBase();
1200 continue;
1201 }
1202 }
1203
1204 break;
1205 }
1206
1207 return Init->getType();
1208}
1209
Marcin Swiderski5e415732010-09-30 23:05:00 +00001210/// addAutomaticObjDtors - Add to current block automatic objects destructors
1211/// for objects in range of local scope positions. Use S as trigger statement
1212/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001213void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001214 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001215 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001216 return;
1217
Marcin Swiderski5e415732010-09-30 23:05:00 +00001218 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001219 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001220
Chandler Carruthad747252011-09-13 06:09:01 +00001221 // We need to append the destructors in reverse order, but any one of them
1222 // may be a no-return destructor which changes the CFG. As a result, buffer
1223 // this sequence up and replay them in reverse order when appending onto the
1224 // CFGBlock(s).
1225 SmallVector<VarDecl*, 10> Decls;
1226 Decls.reserve(B.distance(E));
1227 for (LocalScope::const_iterator I = B; I != E; ++I)
1228 Decls.push_back(*I);
1229
1230 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1231 E = Decls.rend();
1232 I != E; ++I) {
1233 // If this destructor is marked as a no-return destructor, we need to
1234 // create a new block for the destructor which does not have as a successor
1235 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001236 QualType Ty = (*I)->getType();
1237 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001238 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001239 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001240 Ty = Context->getBaseElementType(Ty);
1241
Richard Trieu95a192a2015-05-28 00:14:02 +00001242 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001243 Block = createNoReturnBlock();
1244 else
Chandler Carruthad747252011-09-13 06:09:01 +00001245 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001246
1247 appendAutomaticObjDtor(Block, *I, S);
1248 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001249}
1250
Marcin Swiderski20b88732010-10-05 05:37:00 +00001251/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1252/// base and member objects in destructor.
1253void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1254 assert (BuildOpts.AddImplicitDtors
1255 && "Can be called only when dtors should be added");
1256 const CXXRecordDecl *RD = DD->getParent();
1257
1258 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001259 for (const auto &VI : RD->vbases()) {
1260 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001261 if (!CD->hasTrivialDestructor()) {
1262 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001263 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001264 }
1265 }
1266
1267 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001268 for (const auto &BI : RD->bases()) {
1269 if (!BI.isVirtual()) {
1270 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001271 if (!CD->hasTrivialDestructor()) {
1272 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001273 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001274 }
1275 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001276 }
1277
1278 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001279 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001280 // Check for constant size array. Set type to array element type.
1281 QualType QT = FI->getType();
1282 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1283 if (AT->getSize() == 0)
1284 continue;
1285 QT = AT->getElementType();
1286 }
1287
1288 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001289 if (!CD->hasTrivialDestructor()) {
1290 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001291 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001292 }
1293 }
1294}
1295
Marcin Swiderski5e415732010-09-30 23:05:00 +00001296/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1297/// way return valid LocalScope object.
1298LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
David Blaikiec1334cc2015-08-13 22:12:21 +00001299 if (Scope)
1300 return Scope;
1301 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1302 return new (alloc.Allocate<LocalScope>())
1303 LocalScope(BumpVectorContext(alloc), ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001304}
1305
1306/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001307/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001308void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001309 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001310 return;
1311
Craig Topper25542942014-05-20 04:30:07 +00001312 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001313
1314 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001315 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001316 for (auto *BI : CS->body()) {
1317 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001318 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001319 Scope = addLocalScopeForDeclStmt(DS, Scope);
1320 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001321 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001322 }
1323
1324 // For any other statement scope will be implicit and as such will be
1325 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001326 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001327 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001328}
1329
1330/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1331/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001332LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001333 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001334 if (!BuildOpts.AddImplicitDtors)
1335 return Scope;
1336
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001337 for (auto *DI : DS->decls())
1338 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001339 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001340 return Scope;
1341}
1342
1343/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1344/// create add scope for automatic objects and temporary objects bound to
1345/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001346LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001347 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001348 if (!BuildOpts.AddImplicitDtors)
1349 return Scope;
1350
1351 // Check if variable is local.
1352 switch (VD->getStorageClass()) {
1353 case SC_None:
1354 case SC_Auto:
1355 case SC_Register:
1356 break;
1357 default: return Scope;
1358 }
1359
1360 // Check for const references bound to temporary. Set type to pointee.
1361 QualType QT = VD->getType();
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001362 if (QT.getTypePtr()->isReferenceType()) {
Richard Smith5a0ef782013-06-27 21:43:17 +00001363 // Attempt to determine whether this declaration lifetime-extends a
1364 // temporary.
1365 //
1366 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1367 // temporaries, and a single declaration can extend multiple temporaries.
1368 // We should look at the storage duration on each nested
1369 // MaterializeTemporaryExpr instead.
1370 const Expr *Init = VD->getInit();
1371 if (!Init)
1372 return Scope;
1373 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1374 Init = EWC->getSubExpr();
1375 if (!isa<MaterializeTemporaryExpr>(Init))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001376 return Scope;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001377
Richard Smith5a0ef782013-06-27 21:43:17 +00001378 // Lifetime-extending a temporary.
1379 QT = getReferenceInitTemporaryType(*Context, Init);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001380 }
1381
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001382 // Check for constant size array. Set type to array element type.
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001383 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001384 if (AT->getSize() == 0)
1385 return Scope;
1386 QT = AT->getElementType();
1387 }
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001388
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001389 // Check if type is a C++ class with non-trivial destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001390 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
David Blaikie0f2ae782012-01-24 04:51:48 +00001391 if (!CD->hasTrivialDestructor()) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001392 // Add the variable to scope
1393 Scope = createOrReuseLocalScope(Scope);
1394 Scope->addVar(VD);
1395 ScopePos = Scope->begin();
1396 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001397 return Scope;
1398}
1399
1400/// addLocalScopeAndDtors - For given statement add local scope for it and
1401/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001402void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001403 if (!BuildOpts.AddImplicitDtors)
1404 return;
1405
1406 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001407 addLocalScopeForStmt(S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001408 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1409}
1410
Marcin Swiderski321a7072010-09-30 22:54:37 +00001411/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1412/// variables with automatic storage duration to CFGBlock's elements vector.
1413/// Elements will be prepended to physical beginning of the vector which
1414/// happens to be logical end. Use blocks terminator as statement that specifies
1415/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001416/// FIXME: This mechanism for adding automatic destructors doesn't handle
1417/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001418void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001419 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Chandler Carruthad747252011-09-13 06:09:01 +00001420 BumpVectorContext &C = cfg->getBumpVectorContext();
1421 CFGBlock::iterator InsertPos
1422 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1423 for (LocalScope::const_iterator I = B; I != E; ++I)
1424 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1425 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001426}
1427
Ted Kremenek93668002009-07-17 22:18:43 +00001428/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001429/// blocks for ternary operators, &&, and ||. We also process "," and
1430/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001431CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001432 if (!S) {
1433 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001434 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001435 }
Jordy Rose17347372011-06-10 08:49:37 +00001436
1437 if (Expr *E = dyn_cast<Expr>(S))
1438 S = E->IgnoreParens();
1439
Ted Kremenek93668002009-07-17 22:18:43 +00001440 switch (S->getStmtClass()) {
1441 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001442 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001443
1444 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001445 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001446
John McCallc07a0c72011-02-17 10:25:35 +00001447 case Stmt::BinaryConditionalOperatorClass:
1448 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1449
Ted Kremenek93668002009-07-17 22:18:43 +00001450 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001451 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001452
Ted Kremenek93668002009-07-17 22:18:43 +00001453 case Stmt::BlockExprClass:
Devin Coughlinb6029b72015-11-25 22:35:37 +00001454 return VisitBlockExpr(cast<BlockExpr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001455
Ted Kremenek93668002009-07-17 22:18:43 +00001456 case Stmt::BreakStmtClass:
1457 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001458
Ted Kremenek93668002009-07-17 22:18:43 +00001459 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001460 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001461 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001462 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001463 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Ted Kremenek93668002009-07-17 22:18:43 +00001465 case Stmt::CaseStmtClass:
1466 return VisitCaseStmt(cast<CaseStmt>(S));
1467
1468 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001469 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001470
Ted Kremenek93668002009-07-17 22:18:43 +00001471 case Stmt::CompoundStmtClass:
1472 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001473
Ted Kremenek93668002009-07-17 22:18:43 +00001474 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001475 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001476
Ted Kremenek93668002009-07-17 22:18:43 +00001477 case Stmt::ContinueStmtClass:
1478 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001479
Ted Kremenekb27378c2010-01-19 20:40:33 +00001480 case Stmt::CXXCatchStmtClass:
1481 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1482
John McCall5d413782010-12-06 08:20:24 +00001483 case Stmt::ExprWithCleanupsClass:
1484 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001485
Jordan Rosee5d53932012-08-23 18:10:53 +00001486 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001487 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001488 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1489 // called function's declaration, not by the caller. If we simply add
1490 // this expression to the CFG, we could end up with the same Expr
1491 // appearing multiple times.
1492 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001493 //
1494 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1495 // expression to be used in the same function (through aggregate
1496 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001497 return VisitStmt(S, asc);
1498
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001499 case Stmt::CXXBindTemporaryExprClass:
1500 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1501
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001502 case Stmt::CXXConstructExprClass:
1503 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1504
Jordan Rosec9176072014-01-13 17:59:19 +00001505 case Stmt::CXXNewExprClass:
1506 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1507
Jordan Rosed2f40792013-09-03 17:00:57 +00001508 case Stmt::CXXDeleteExprClass:
1509 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1510
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001511 case Stmt::CXXFunctionalCastExprClass:
1512 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1513
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001514 case Stmt::CXXTemporaryObjectExprClass:
1515 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1516
Ted Kremenekb27378c2010-01-19 20:40:33 +00001517 case Stmt::CXXThrowExprClass:
1518 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001519
Ted Kremenekb27378c2010-01-19 20:40:33 +00001520 case Stmt::CXXTryStmtClass:
1521 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001522
Richard Smith02e85f32011-04-14 22:09:26 +00001523 case Stmt::CXXForRangeStmtClass:
1524 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1525
Ted Kremenek93668002009-07-17 22:18:43 +00001526 case Stmt::DeclStmtClass:
1527 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001528
Ted Kremenek93668002009-07-17 22:18:43 +00001529 case Stmt::DefaultStmtClass:
1530 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001531
Ted Kremenek93668002009-07-17 22:18:43 +00001532 case Stmt::DoStmtClass:
1533 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001534
Ted Kremenek93668002009-07-17 22:18:43 +00001535 case Stmt::ForStmtClass:
1536 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001537
Ted Kremenek93668002009-07-17 22:18:43 +00001538 case Stmt::GotoStmtClass:
1539 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001540
Ted Kremenek93668002009-07-17 22:18:43 +00001541 case Stmt::IfStmtClass:
1542 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001543
Ted Kremenek8219b822010-12-16 07:46:53 +00001544 case Stmt::ImplicitCastExprClass:
1545 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001546
Ted Kremenek93668002009-07-17 22:18:43 +00001547 case Stmt::IndirectGotoStmtClass:
1548 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001549
Ted Kremenek93668002009-07-17 22:18:43 +00001550 case Stmt::LabelStmtClass:
1551 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001552
Ted Kremenekda76a942012-04-12 20:34:52 +00001553 case Stmt::LambdaExprClass:
1554 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1555
Ted Kremenek5868ec62010-04-11 17:02:10 +00001556 case Stmt::MemberExprClass:
1557 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1558
Ted Kremenek04268232011-11-05 00:10:15 +00001559 case Stmt::NullStmtClass:
1560 return Block;
1561
Ted Kremenek93668002009-07-17 22:18:43 +00001562 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001563 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1564
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001565 case Stmt::ObjCAutoreleasePoolStmtClass:
1566 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1567
Ted Kremenek93668002009-07-17 22:18:43 +00001568 case Stmt::ObjCAtSynchronizedStmtClass:
1569 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001570
Ted Kremenek93668002009-07-17 22:18:43 +00001571 case Stmt::ObjCAtThrowStmtClass:
1572 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001573
Ted Kremenek93668002009-07-17 22:18:43 +00001574 case Stmt::ObjCAtTryStmtClass:
1575 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001576
Ted Kremenek93668002009-07-17 22:18:43 +00001577 case Stmt::ObjCForCollectionStmtClass:
1578 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001579
Ted Kremenek04268232011-11-05 00:10:15 +00001580 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001581 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001582
John McCallfe96e0b2011-11-06 09:01:30 +00001583 case Stmt::PseudoObjectExprClass:
1584 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1585
Ted Kremenek93668002009-07-17 22:18:43 +00001586 case Stmt::ReturnStmtClass:
1587 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001588
Peter Collingbournee190dee2011-03-11 19:24:49 +00001589 case Stmt::UnaryExprOrTypeTraitExprClass:
1590 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1591 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Ted Kremenek93668002009-07-17 22:18:43 +00001593 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001594 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001595
Ted Kremenek93668002009-07-17 22:18:43 +00001596 case Stmt::SwitchStmtClass:
1597 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001598
Zhanyong Wan6dace612010-11-22 08:45:56 +00001599 case Stmt::UnaryOperatorClass:
1600 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1601
Ted Kremenek93668002009-07-17 22:18:43 +00001602 case Stmt::WhileStmtClass:
1603 return VisitWhileStmt(cast<WhileStmt>(S));
1604 }
1605}
Mike Stump11289f42009-09-09 15:08:12 +00001606
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001607CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001608 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001609 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001610 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001611 }
Mike Stump11289f42009-09-09 15:08:12 +00001612
Ted Kremenek93668002009-07-17 22:18:43 +00001613 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001614}
Mike Stump31feda52009-07-17 01:31:16 +00001615
Ted Kremenek93668002009-07-17 22:18:43 +00001616/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001617CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1618 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001619
Ted Kremenek8ae67872013-02-05 22:00:19 +00001620 // Visit the children in their reverse order so that they appear in
1621 // left-to-right (natural) order in the CFG.
1622 reverse_children RChildren(S);
1623 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1624 I != E; ++I) {
1625 if (Stmt *Child = *I)
1626 if (CFGBlock *R = Visit(Child))
1627 B = R;
1628 }
1629 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001630}
Mike Stump11289f42009-09-09 15:08:12 +00001631
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001632CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1633 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001634 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001635
Ted Kremenek7c58d352011-03-10 01:14:11 +00001636 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001637 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001638 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001639 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001640
Ted Kremenek9aae5132007-08-23 21:42:29 +00001641 return Block;
1642}
Mike Stump11289f42009-09-09 15:08:12 +00001643
Zhanyong Wan6dace612010-11-22 08:45:56 +00001644CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001645 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001646 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001647 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001648 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001649 }
1650
Ted Kremenek8219b822010-12-16 07:46:53 +00001651 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001652}
1653
Ted Kremeneka16436f2012-07-14 05:04:06 +00001654CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1655 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1656 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Ted Kremeneka16436f2012-07-14 05:04:06 +00001658 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001659 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001660
Craig Topper25542942014-05-20 04:30:07 +00001661 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1662 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001663}
1664
1665std::pair<CFGBlock*, CFGBlock*>
1666CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1667 Stmt *Term,
1668 CFGBlock *TrueBlock,
1669 CFGBlock *FalseBlock) {
1670
1671 // Introspect the RHS. If it is a nested logical operation, we recursively
1672 // build the CFG using this function. Otherwise, resort to default
1673 // CFG construction behavior.
1674 Expr *RHS = B->getRHS()->IgnoreParens();
1675 CFGBlock *RHSBlock, *ExitBlock;
1676
1677 do {
1678 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1679 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001680 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001681 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1682 break;
1683 }
1684
1685 // The RHS is not a nested logical operation. Don't push the terminator
1686 // down further, but instead visit RHS and construct the respective
1687 // pieces of the CFG, and link up the RHSBlock with the terminator
1688 // we have been provided.
1689 ExitBlock = RHSBlock = createBlock(false);
1690
1691 if (!Term) {
1692 assert(TrueBlock == FalseBlock);
1693 addSuccessor(RHSBlock, TrueBlock);
1694 }
1695 else {
1696 RHSBlock->setTerminator(Term);
1697 TryResult KnownVal = tryEvaluateBool(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001698 if (!KnownVal.isKnown())
1699 KnownVal = tryEvaluateBool(B);
Ted Kremenek782f0032014-03-07 02:25:53 +00001700 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1701 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001702 }
1703
1704 Block = RHSBlock;
1705 RHSBlock = addStmt(RHS);
1706 }
1707 while (false);
1708
1709 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001710 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001711
1712 // Generate the blocks for evaluating the LHS.
1713 Expr *LHS = B->getLHS()->IgnoreParens();
1714
1715 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1716 if (B_LHS->isLogicalOp()) {
1717 if (B->getOpcode() == BO_LOr)
1718 FalseBlock = RHSBlock;
1719 else
1720 TrueBlock = RHSBlock;
1721
1722 // For the LHS, treat 'B' as the terminator that we want to sink
1723 // into the nested branch. The RHS always gets the top-most
1724 // terminator.
1725 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1726 }
1727
1728 // Create the block evaluating the LHS.
1729 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001730 CFGBlock *LHSBlock = createBlock(false);
1731 LHSBlock->setTerminator(B);
1732
Ted Kremeneka16436f2012-07-14 05:04:06 +00001733 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001734 CFGBlock *EntryLHSBlock = addStmt(LHS);
1735
1736 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001737 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001738
1739 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00001740 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001741
1742 // Now link the LHSBlock with RHSBlock.
1743 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00001744 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1745 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001746 } else {
1747 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00001748 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1749 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001750 }
1751
Ted Kremenekb50e7162012-07-14 05:04:10 +00001752 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001753}
1754
Ted Kremenekb50e7162012-07-14 05:04:10 +00001755
Ted Kremeneka16436f2012-07-14 05:04:06 +00001756CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1757 AddStmtChoice asc) {
1758 // && or ||
1759 if (B->isLogicalOp())
1760 return VisitLogicalOperator(B);
1761
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001762 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00001763 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001764 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00001765 addStmt(B->getRHS());
1766 return addStmt(B->getLHS());
1767 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001768
1769 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001770 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001771 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001772 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001773 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001774 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00001775 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001776 }
Mike Stump11289f42009-09-09 15:08:12 +00001777
Ted Kremenek7c58d352011-03-10 01:14:11 +00001778 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00001779 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001780 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00001781 }
1782
Zhongxing Xud95ccd52010-10-27 03:23:10 +00001783 CFGBlock *RBlock = Visit(B->getRHS());
1784 CFGBlock *LBlock = Visit(B->getLHS());
1785 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1786 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1787 // return RBlock. Otherwise we'll incorrectly return NULL.
1788 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00001789}
1790
Ted Kremeneke2499842012-04-12 20:03:44 +00001791CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001792 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00001793 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001794 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00001795 }
1796 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001797}
1798
Ted Kremenek93668002009-07-17 22:18:43 +00001799CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1800 // "break" is a control-flow statement. Thus we stop processing the current
1801 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001802 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001803 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001804
Ted Kremenek93668002009-07-17 22:18:43 +00001805 // Now create a new block that ends with the break statement.
1806 Block = createBlock(false);
1807 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00001808
Ted Kremenek93668002009-07-17 22:18:43 +00001809 // If there is no target for the break, then we are looking at an incomplete
1810 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001811 if (BreakJumpTarget.block) {
1812 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1813 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001814 } else
Ted Kremenek93668002009-07-17 22:18:43 +00001815 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00001816
1817
Ted Kremenek9aae5132007-08-23 21:42:29 +00001818 return Block;
1819}
Mike Stump11289f42009-09-09 15:08:12 +00001820
Sebastian Redl31ad7542011-03-13 17:09:40 +00001821static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00001822 QualType Ty = E->getType();
1823 if (Ty->isFunctionPointerType())
1824 Ty = Ty->getAs<PointerType>()->getPointeeType();
1825 else if (Ty->isBlockPointerType())
1826 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001827
Mike Stump04c68512010-01-21 15:20:48 +00001828 const FunctionType *FT = Ty->getAs<FunctionType>();
1829 if (FT) {
1830 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00001831 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00001832 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00001833 return false;
1834 }
1835 return true;
1836}
1837
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001838CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00001839 // Compute the callee type.
1840 QualType calleeType = C->getCallee()->getType();
1841 if (calleeType == Context->BoundMemberTy) {
1842 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1843
1844 // We should only get a null bound type if processing a dependent
1845 // CFG. Recover by assuming nothing.
1846 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00001847 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001848
John McCallc67067f2011-05-11 07:19:11 +00001849 // If this is a call to a no-return function, this stops the block here.
1850 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1851
Mike Stump04c68512010-01-21 15:20:48 +00001852 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00001853
1854 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001855 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00001856 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00001857 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00001858 }
1859
Jordan Rose5374c072013-08-19 16:27:28 +00001860 // If this is a call to a builtin function, it might not actually evaluate
1861 // its arguments. Don't add them to the CFG if this is the case.
1862 bool OmitArguments = false;
1863
Mike Stump92244b02010-01-19 22:00:14 +00001864 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00001865 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00001866 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00001867 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00001868 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00001869 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1870 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00001871 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001872
Sebastian Redl31ad7542011-03-13 17:09:40 +00001873 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00001874 AddEHEdge = false;
1875
Jordan Rose5374c072013-08-19 16:27:28 +00001876 if (OmitArguments) {
1877 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1878 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1879 autoCreateBlock();
1880 appendStmt(Block, C);
1881 return Visit(C->getCallee());
1882 }
1883
1884 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001885 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00001886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Mike Stump92244b02010-01-19 22:00:14 +00001888 if (Block) {
1889 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001890 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001891 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00001892 }
Mike Stump11289f42009-09-09 15:08:12 +00001893
Chandler Carrutha70991b2011-09-13 09:13:49 +00001894 if (NoReturn)
1895 Block = createNoReturnBlock();
1896 else
1897 Block = createBlock();
1898
Ted Kremenek2866bab2011-03-10 01:14:08 +00001899 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00001900
Mike Stump04c68512010-01-21 15:20:48 +00001901 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00001902 // Add exceptional edges.
1903 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001904 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00001905 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001906 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00001907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908
Mike Stump8c5d7992009-07-25 21:26:53 +00001909 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00001910}
Ted Kremenek9aae5132007-08-23 21:42:29 +00001911
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001912CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1913 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001914 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001915 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001916 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001917 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001918
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001919 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00001920 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001921 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001922 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001923 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001924 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001925
Ted Kremenek21822592009-07-17 18:20:32 +00001926 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001927 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001928 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001929 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001930 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001931
Ted Kremenek21822592009-07-17 18:20:32 +00001932 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00001933 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001934 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00001935 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1936 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00001937 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00001938 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00001939}
Mike Stump11289f42009-09-09 15:08:12 +00001940
1941
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001942CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Matthias Gehre09a134e2015-11-14 00:36:50 +00001943 LocalScope::const_iterator scopeBeginPos = ScopePos;
1944 if (BuildOpts.AddImplicitDtors) {
1945 addLocalScopeForStmt(C);
1946 }
1947 if (!C->body_empty() && !isa<ReturnStmt>(*C->body_rbegin())) {
Richard Smitha547eb22016-07-14 00:11:03 +00001948 // If the body ends with a ReturnStmt, the dtors will be added in
1949 // VisitReturnStmt.
Matthias Gehre09a134e2015-11-14 00:36:50 +00001950 addAutomaticObjDtors(ScopePos, scopeBeginPos, C);
1951 }
1952
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001953 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001954
1955 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1956 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00001957 // If we hit a segment of code just containing ';' (NullStmts), we can
1958 // get a null block back. In such cases, just use the LastBlock
1959 if (CFGBlock *newBlock = addStmt(*I))
1960 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001961
Ted Kremenekce499c22009-08-27 23:16:26 +00001962 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001963 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001964 }
Mike Stump92244b02010-01-19 22:00:14 +00001965
Ted Kremenek93668002009-07-17 22:18:43 +00001966 return LastBlock;
1967}
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCallc07a0c72011-02-17 10:25:35 +00001969CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001970 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00001971 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00001972 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00001973
Ted Kremenek51d40b02009-07-17 18:15:54 +00001974 // Create the confluence block that will "merge" the results of the ternary
1975 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001976 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001977 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001978 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001979 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001980
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001981 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00001982
Ted Kremenek51d40b02009-07-17 18:15:54 +00001983 // Create a block for the LHS expression if there is an LHS expression. A
1984 // GCC extension allows LHS to be NULL, causing the condition to be the
1985 // value that is returned instead.
1986 // e.g: x ?: y is shorthand for: x ? x : y;
1987 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001988 Block = nullptr;
1989 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00001990 const Expr *trueExpr = C->getTrueExpr();
1991 if (trueExpr != opaqueValue) {
1992 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001993 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001994 return nullptr;
1995 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00001996 }
Ted Kremenekd8138012011-02-24 03:09:15 +00001997 else
1998 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001999
Ted Kremenek51d40b02009-07-17 18:15:54 +00002000 // Create the block for the RHS expression.
2001 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002002 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002003 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002004 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Richard Smithf676e452012-07-24 21:02:14 +00002006 // If the condition is a logical '&&' or '||', build a more accurate CFG.
2007 if (BinaryOperator *Cond =
2008 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
2009 if (Cond->isLogicalOp())
2010 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
2011
Ted Kremenek51d40b02009-07-17 18:15:54 +00002012 // Create the block that will contain the condition.
2013 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00002014
Mike Stump773582d2009-07-23 23:25:26 +00002015 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002016 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00002017 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
2018 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00002019 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00002020 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00002021
Ted Kremenekd8138012011-02-24 03:09:15 +00002022 if (opaqueValue) {
2023 // Run the condition expression if it's not trivially expressed in
2024 // terms of the opaque value (or if there is no opaque value).
2025 if (condExpr != opaqueValue)
2026 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00002027
Ted Kremenekd8138012011-02-24 03:09:15 +00002028 // Before that, run the common subexpression if there was one.
2029 // At least one of this or the above will be run.
2030 return addStmt(BCO->getCommon());
2031 }
2032
2033 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00002034}
2035
Ted Kremenek93668002009-07-17 22:18:43 +00002036CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00002037 // Check if the Decl is for an __label__. If so, elide it from the
2038 // CFG entirely.
2039 if (isa<LabelDecl>(*DS->decl_begin()))
2040 return Block;
2041
Ted Kremenek3a601142011-05-24 20:41:31 +00002042 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002043 if (DS->isSingleDecl())
2044 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00002045
Craig Topper25542942014-05-20 04:30:07 +00002046 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002047
Jordan Rose8c6c8a92012-07-20 18:50:48 +00002048 // Build an individual DeclStmt for each decl.
2049 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
2050 E = DS->decl_rend();
2051 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00002052 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
2053 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
2054 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Mike Stump11289f42009-09-09 15:08:12 +00002055
Ted Kremenek93668002009-07-17 22:18:43 +00002056 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2057 // automatically freed with the CFG.
2058 DeclGroupRef DG(*I);
2059 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002060 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002061 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002062 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002063
Ted Kremenek93668002009-07-17 22:18:43 +00002064 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002065 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
2068 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002069}
Mike Stump11289f42009-09-09 15:08:12 +00002070
Ted Kremenek93668002009-07-17 22:18:43 +00002071/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002072/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002073CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002074 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002075 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002076
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002077 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002078 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2079 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002080 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002083 bool HasTemporaries = false;
2084
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002085 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002086 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002087
2088 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2089 // For static variables, we need to create a branch to track
2090 // whether or not they are initialized.
2091 if (Block) {
2092 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002093 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002094 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002095 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002096 }
2097 blockAfterStaticInit = Succ;
2098 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002099
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002100 // Destructors of temporaries in initialization expression should be called
2101 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002102 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002103 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002104 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002105
Jordan Rose6d671cc2012-09-05 22:55:23 +00002106 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002107 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002108 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002109 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2110 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002111 }
2112 }
2113
2114 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002115 appendStmt(Block, DS);
Ted Kremenek213d0532012-03-22 05:57:43 +00002116
2117 // Keep track of the last non-null block, as 'Block' can be nulled out
2118 // if the initializer expression is something like a 'while' in a
2119 // statement-expression.
2120 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002121
Ted Kremenek93668002009-07-17 22:18:43 +00002122 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002123 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002124 // For expression with temporaries go directly to subexpression to omit
2125 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002126 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2127 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2128 LastBlock = newBlock;
2129 }
2130 else {
2131 if (CFGBlock *newBlock = Visit(Init))
2132 LastBlock = newBlock;
2133 }
Ted Kremenek93668002009-07-17 22:18:43 +00002134 }
Mike Stump11289f42009-09-09 15:08:12 +00002135
Ted Kremenek93668002009-07-17 22:18:43 +00002136 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002137 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002138 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002139 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2140 LastBlock = newBlock;
2141 }
Mike Stump11289f42009-09-09 15:08:12 +00002142
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002143 // Remove variable from local scope.
2144 if (ScopePos && VD == *ScopePos)
2145 ++ScopePos;
2146
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002147 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002148 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002149 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002150 Block = createBlock(false);
2151 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002152 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002153 addSuccessor(Block, B);
2154 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002155 }
2156
2157 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002158}
2159
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002160CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002161 // We may see an if statement in the middle of a basic block, or it may be the
2162 // first statement we are processing. In either case, we create a new basic
2163 // block. First, we create the blocks for the then...else statements, and
2164 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002165 // middle of a block, we stop processing that block. That block is then the
2166 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002167
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002168 // Save local scope position because in case of condition variable ScopePos
2169 // won't be restored when traversing AST.
2170 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2171
Richard Smitha547eb22016-07-14 00:11:03 +00002172 // Create local scope for C++17 if init-stmt if one exists.
2173 if (Stmt *Init = I->getInit()) {
2174 LocalScope::const_iterator BeginScopePos = ScopePos;
2175 addLocalScopeForStmt(Init);
2176 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2177 }
2178
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002179 // Create local scope for possible condition variable.
2180 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002181 if (VarDecl *VD = I->getConditionVariable()) {
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002182 LocalScope::const_iterator BeginScopePos = ScopePos;
2183 addLocalScopeForVarDecl(VD);
2184 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2185 }
2186
Chris Lattner57540c52011-04-15 05:22:18 +00002187 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002188 // block.
2189 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002190 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002191 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002192 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002193 }
Mike Stump31feda52009-07-17 01:31:16 +00002194
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002195 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002196 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002197
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002198 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002199 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002200
Ted Kremenek9aae5132007-08-23 21:42:29 +00002201 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002202 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002203 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002204
2205 // If branch is not a compound statement create implicit scope
2206 // and add destructors.
2207 if (!isa<CompoundStmt>(Else))
2208 addLocalScopeAndDtors(Else);
2209
Ted Kremenek93668002009-07-17 22:18:43 +00002210 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002211
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002212 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2213 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002214 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002215 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002216 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002217 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002218 }
Mike Stump31feda52009-07-17 01:31:16 +00002219
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002220 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002221 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002222 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002223 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002224 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002225 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002226 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002227
2228 // If branch is not a compound statement create implicit scope
2229 // and add destructors.
2230 if (!isa<CompoundStmt>(Then))
2231 addLocalScopeAndDtors(Then);
2232
Ted Kremenek93668002009-07-17 22:18:43 +00002233 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002234
Ted Kremenek1b379512009-04-01 03:52:47 +00002235 if (!ThenBlock) {
2236 // We can reach here if the "then" body has all NullStmts.
2237 // Create an empty block so we can distinguish between true and false
2238 // branches in path-sensitive analyses.
2239 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002240 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002241 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002242 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002243 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002244 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002245 }
2246
Ted Kremenekb50e7162012-07-14 05:04:10 +00002247 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2248 // having these handle the actual control-flow jump. Note that
2249 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2250 // we resort to the old control-flow behavior. This special handling
2251 // removes infeasible paths from the control-flow graph by having the
2252 // control-flow transfer of '&&' or '||' go directly into the then/else
2253 // blocks directly.
2254 if (!I->getConditionVariable())
Richard Smithf676e452012-07-24 21:02:14 +00002255 if (BinaryOperator *Cond =
2256 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002257 if (Cond->isLogicalOp())
2258 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2259
Mike Stump31feda52009-07-17 01:31:16 +00002260 // Now create a new block containing the if statement.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002261 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002262
Ted Kremenek9aae5132007-08-23 21:42:29 +00002263 // Set the terminator of the new block to the If statement.
2264 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002265
Mike Stump773582d2009-07-23 23:25:26 +00002266 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002267 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002268
Ted Kremenekf3898612014-02-27 00:24:03 +00002269 // Add the successors. If we know that specific branches are
2270 // unreachable, inform addSuccessor() of that knowledge.
2271 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2272 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump31feda52009-07-17 01:31:16 +00002273
2274 // Add the condition as the last statement in the new block. This may create
2275 // new blocks as the condition may contain control-flow. Any newly created
2276 // blocks will be pointed to be "Block".
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002277 CFGBlock *LastBlock = addStmt(I->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002278
Richard Smitha547eb22016-07-14 00:11:03 +00002279 // If the IfStmt contains a condition variable, add it and its
Manuel Klimek75f34c12014-05-05 18:21:06 +00002280 // initializer to the CFG.
2281 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2282 autoCreateBlock();
2283 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002284 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002285
Richard Smitha547eb22016-07-14 00:11:03 +00002286 // Finally, if the IfStmt contains a C++17 init-stmt, add it to the CFG.
2287 if (Stmt *Init = I->getInit()) {
2288 autoCreateBlock();
2289 LastBlock = addStmt(Init);
2290 }
2291
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002292 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002293}
Mike Stump31feda52009-07-17 01:31:16 +00002294
2295
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002296CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002297 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002298 //
Mike Stump31feda52009-07-17 01:31:16 +00002299 // NOTE: If a "return" appears in the middle of a block, this means that the
2300 // code afterwards is DEAD (unreachable). We still keep a basic block
2301 // for that code; a simple "mark-and-sweep" from the entry block will be
2302 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002303
2304 // Create the new block.
2305 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002306
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002307 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002308
2309 // If the one of the destructors does not return, we already have the Exit
2310 // block as a successor.
2311 if (!Block->hasNoReturnElement())
2312 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002313
2314 // Add the return statement to the block. This may create new blocks if R
2315 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002316 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002317}
2318
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002319CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002320 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002321 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002322 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002323
Ted Kremenek93668002009-07-17 22:18:43 +00002324 if (!LabelBlock) // This can happen when the body is empty, i.e.
2325 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002326
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002327 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2328 "label already in map");
2329 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002330
2331 // Labels partition blocks, so this is the end of the basic block we were
2332 // processing (L is the block's label). Because this is label (and we have
2333 // already processed the substatement) there is no extra control-flow to worry
2334 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002335 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002336 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002337 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002338
2339 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002340 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002341
Ted Kremenek9aae5132007-08-23 21:42:29 +00002342 // This block is now the implicit successor of other blocks.
2343 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002344
Ted Kremenek9aae5132007-08-23 21:42:29 +00002345 return LabelBlock;
2346}
2347
Devin Coughlinb6029b72015-11-25 22:35:37 +00002348CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
2349 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2350 for (const BlockDecl::Capture &CI : E->getBlockDecl()->captures()) {
2351 if (Expr *CopyExpr = CI.getCopyExpr()) {
2352 CFGBlock *Tmp = Visit(CopyExpr);
2353 if (Tmp)
2354 LastBlock = Tmp;
2355 }
2356 }
2357 return LastBlock;
2358}
2359
Ted Kremenekda76a942012-04-12 20:34:52 +00002360CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2361 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2362 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2363 et = E->capture_init_end(); it != et; ++it) {
2364 if (Expr *Init = *it) {
2365 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002366 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002367 LastBlock = Tmp;
2368 }
2369 }
2370 return LastBlock;
2371}
2372
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002373CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002374 // Goto is a control-flow statement. Thus we stop processing the current
2375 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002376
Ted Kremenek9aae5132007-08-23 21:42:29 +00002377 Block = createBlock(false);
2378 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002379
2380 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002381 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002382
Ted Kremenek9aae5132007-08-23 21:42:29 +00002383 if (I == LabelMap.end())
2384 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002385 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2386 else {
2387 JumpTarget JT = I->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002388 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2389 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002390 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002391
Mike Stump31feda52009-07-17 01:31:16 +00002392 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002393}
2394
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002395CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002396 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002397
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002398 // Save local scope position because in case of condition variable ScopePos
2399 // won't be restored when traversing AST.
2400 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2401
2402 // Create local scope for init statement and possible condition variable.
2403 // Add destructor for init statement and condition variable.
2404 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002405 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002406 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002407 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2408
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002409 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002410 addLocalScopeForVarDecl(VD);
2411 LocalScope::const_iterator ContinueScopePos = ScopePos;
2412
2413 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2414
Mike Stump014b3ea2009-07-21 01:12:51 +00002415 // "for" is a control-flow statement. Thus we stop processing the current
2416 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002417 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002418 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002419 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002420 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002421 } else
2422 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002423
Ted Kremenek304a9532010-05-21 20:30:15 +00002424 // Save the current value for the break targets.
2425 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002426 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002427 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002428
Craig Topper25542942014-05-20 04:30:07 +00002429 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002430
Ted Kremenek9aae5132007-08-23 21:42:29 +00002431 // Now create the loop body.
2432 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002433 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002434
Ted Kremenekb50e7162012-07-14 05:04:10 +00002435 // Save the current values for Block, Succ, continue and break targets.
2436 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2437 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002438
Ted Kremenekb50e7162012-07-14 05:04:10 +00002439 // Create an empty block to represent the transition block for looping back
2440 // to the head of the loop. If we have increment code, it will
2441 // go in this block as well.
2442 Block = Succ = TransitionBlock = createBlock(false);
2443 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002444
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002445 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002446 // Generate increment code in its own basic block. This is the target of
2447 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002448 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002449 }
Mike Stump31feda52009-07-17 01:31:16 +00002450
Ted Kremenek902393b2009-04-28 00:51:56 +00002451 // Finish up the increment (or empty) block if it hasn't been already.
2452 if (Block) {
2453 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002454 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002455 return nullptr;
2456 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002457 }
Mike Stump31feda52009-07-17 01:31:16 +00002458
Ted Kremenekb50e7162012-07-14 05:04:10 +00002459 // The starting block for the loop increment is the block that should
2460 // represent the 'loop target' for looping back to the start of the loop.
2461 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2462 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002463
Ted Kremenekb50e7162012-07-14 05:04:10 +00002464 // Loop body should end with destructor of Condition variable (if any).
2465 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002466
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002467 // If body is not a compound statement create implicit scope
2468 // and add destructors.
2469 if (!isa<CompoundStmt>(F->getBody()))
2470 addLocalScopeAndDtors(F->getBody());
2471
Mike Stump31feda52009-07-17 01:31:16 +00002472 // Now populate the body block, and in the process create new blocks as we
2473 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002474 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002475
Ted Kremenekb50e7162012-07-14 05:04:10 +00002476 if (!BodyBlock) {
2477 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2478 // Use the continue jump target as the proxy for the body.
2479 BodyBlock = ContinueJumpTarget.block;
2480 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002481 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002482 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002483 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002484
2485 // Because of short-circuit evaluation, the condition of the loop can span
2486 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2487 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002488 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002489
Ted Kremenekb50e7162012-07-14 05:04:10 +00002490 do {
2491 Expr *C = F->getCond();
2492
2493 // Specially handle logical operators, which have a slightly
2494 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002495 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002496 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002497 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002498 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002499 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2500 break;
2501 }
2502
2503 // The default case when not handling logical operators.
2504 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2505 ExitConditionBlock->setTerminator(F);
2506
2507 // See if this is a known constant.
2508 TryResult KnownVal(true);
2509
2510 if (C) {
2511 // Now add the actual condition to the condition block.
2512 // Because the condition itself may contain control-flow, new blocks may
2513 // be created. Thus we update "Succ" after adding the condition.
2514 Block = ExitConditionBlock;
2515 EntryConditionBlock = addStmt(C);
2516
2517 // If this block contains a condition variable, add both the condition
2518 // variable and initializer to the CFG.
2519 if (VarDecl *VD = F->getConditionVariable()) {
2520 if (Expr *Init = VD->getInit()) {
2521 autoCreateBlock();
2522 appendStmt(Block, F->getConditionVariableDeclStmt());
2523 EntryConditionBlock = addStmt(Init);
2524 assert(Block == EntryConditionBlock);
2525 }
2526 }
2527
2528 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002529 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002530
2531 KnownVal = tryEvaluateBool(C);
2532 }
2533
2534 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002535 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002536 // Link up the condition block with the code that follows the loop. (the
2537 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002538 addSuccessor(ExitConditionBlock,
2539 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002540
2541 } while (false);
2542
2543 // Link up the loop-back block to the entry condition block.
2544 addSuccessor(TransitionBlock, EntryConditionBlock);
2545
2546 // The condition block is the implicit successor for any code above the loop.
2547 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002548
Ted Kremenek9aae5132007-08-23 21:42:29 +00002549 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002550 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002551 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002552 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002553 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002554 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002555
2556 // There is no loop initialization. We are thus basically a while loop.
2557 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002558 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002559 Succ = EntryConditionBlock;
2560 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002561}
2562
Ted Kremenek5868ec62010-04-11 17:02:10 +00002563CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002564 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002565 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002566 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002567 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002568 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002569}
2570
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002571CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002572 // Objective-C fast enumeration 'for' statements:
2573 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2574 //
2575 // for ( Type newVariable in collection_expression ) { statements }
2576 //
2577 // becomes:
2578 //
2579 // prologue:
2580 // 1. collection_expression
2581 // T. jump to loop_entry
2582 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002583 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002584 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2585 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2586 // TB:
2587 // statements
2588 // T. jump to loop_entry
2589 // FB:
2590 // what comes after
2591 //
2592 // and
2593 //
2594 // Type existingItem;
2595 // for ( existingItem in expression ) { statements }
2596 //
2597 // becomes:
2598 //
Mike Stump31feda52009-07-17 01:31:16 +00002599 // the same with newVariable replaced with existingItem; the binding works
2600 // the same except that for one ObjCForCollectionStmt::getElement() returns
2601 // a DeclStmt and the other returns a DeclRefExpr.
Ted Kremenek9d56e642008-11-11 17:10:00 +00002602 //
Mike Stump31feda52009-07-17 01:31:16 +00002603
Craig Topper25542942014-05-20 04:30:07 +00002604 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002605
Ted Kremenek9d56e642008-11-11 17:10:00 +00002606 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002607 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002608 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002609 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002610 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002611 } else
2612 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002613
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002614 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002615 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002616
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002617 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002618 ExitConditionBlock->setTerminator(S);
2619
2620 // The last statement in the block should be the ObjCForCollectionStmt, which
2621 // performs the actual binding to 'element' and determines if there are any
2622 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002623 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002624 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002625
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002626 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00002627 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00002628 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00002629 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2630 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00002631 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002632 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002633 return nullptr;
2634 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002635 }
Mike Stump31feda52009-07-17 01:31:16 +00002636
2637 // The condition block is the implicit successor for the loop body as well as
2638 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002639 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002640
Ted Kremenek9d56e642008-11-11 17:10:00 +00002641 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00002642 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002643 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00002644 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002645 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00002646 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002647
Anna Zaks56b49752013-06-22 00:23:20 +00002648 // Add an intermediate block between the BodyBlock and the
2649 // EntryConditionBlock to represent the "loop back" transition, for looping
2650 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00002651 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00002652 Succ = LoopBackBlock = createBlock();
2653 LoopBackBlock->setLoopTarget(S);
2654
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002655 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00002656 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002657
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002658 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002659
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002660 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00002661 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00002662 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002663 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002664 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002665 }
Mike Stump31feda52009-07-17 01:31:16 +00002666
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002667 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002668 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002669 }
Mike Stump31feda52009-07-17 01:31:16 +00002670
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002671 // Link up the condition block with the code that follows the loop.
2672 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002673 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002674
Ted Kremenek9d56e642008-11-11 17:10:00 +00002675 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002676 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00002677 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00002678}
2679
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002680CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2681 // Inline the body.
2682 return addStmt(S->getSubStmt());
2683 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2684}
2685
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002686CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00002687 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00002688
Ted Kremenek49805452009-05-02 01:49:13 +00002689 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00002690 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00002691
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002692 // The sync body starts its own basic block. This makes it a little easier
2693 // for diagnostic clients.
2694 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002695 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002696 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002697
Craig Topper25542942014-05-20 04:30:07 +00002698 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00002699 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002700 }
Mike Stump31feda52009-07-17 01:31:16 +00002701
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002702 // Add the @synchronized to the CFG.
2703 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002704 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002705
Ted Kremenek49805452009-05-02 01:49:13 +00002706 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00002707 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00002708}
Mike Stump31feda52009-07-17 01:31:16 +00002709
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002710CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002711 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00002712 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00002713}
Ted Kremenek9d56e642008-11-11 17:10:00 +00002714
John McCallfe96e0b2011-11-06 09:01:30 +00002715CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2716 autoCreateBlock();
2717
2718 // Add the PseudoObject as the last thing.
2719 appendStmt(Block, E);
2720
2721 CFGBlock *lastBlock = Block;
2722
2723 // Before that, evaluate all of the semantics in order. In
2724 // CFG-land, that means appending them in reverse order.
2725 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2726 Expr *Semantic = E->getSemanticExpr(--i);
2727
2728 // If the semantic is an opaque value, we're being asked to bind
2729 // it to its source expression.
2730 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2731 Semantic = OVE->getSourceExpr();
2732
2733 if (CFGBlock *B = Visit(Semantic))
2734 lastBlock = B;
2735 }
2736
2737 return lastBlock;
2738}
2739
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002740CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00002741 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002742
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002743 // Save local scope position because in case of condition variable ScopePos
2744 // won't be restored when traversing AST.
2745 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2746
2747 // Create local scope for possible condition variable.
2748 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002749 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002750 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002751 addLocalScopeForVarDecl(VD);
2752 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2753 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002754
Mike Stump014b3ea2009-07-21 01:12:51 +00002755 // "while" is a control-flow statement. Thus we stop processing the current
2756 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002757 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002758 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002759 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002760 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002761 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002762 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00002763 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00002764 }
Mike Stump31feda52009-07-17 01:31:16 +00002765
Craig Topper25542942014-05-20 04:30:07 +00002766 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002767
Ted Kremenek9aae5132007-08-23 21:42:29 +00002768 // Process the loop body.
2769 {
Ted Kremenek49936f72009-04-28 03:09:44 +00002770 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00002771
Ted Kremenekb50e7162012-07-14 05:04:10 +00002772 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002773 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2774 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00002775 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00002776
Mike Stump31feda52009-07-17 01:31:16 +00002777 // Create an empty block to represent the transition block for looping back
2778 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002779 Succ = TransitionBlock = createBlock(false);
2780 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002781 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002782
Ted Kremenek9aae5132007-08-23 21:42:29 +00002783 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002784 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002785
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002786 // Loop body should end with destructor of Condition variable (if any).
2787 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2788
2789 // If body is not a compound statement create implicit scope
2790 // and add destructors.
2791 if (!isa<CompoundStmt>(W->getBody()))
2792 addLocalScopeAndDtors(W->getBody());
2793
Ted Kremenek9aae5132007-08-23 21:42:29 +00002794 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002795 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002796
Ted Kremeneke9610502007-08-30 18:39:40 +00002797 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002798 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00002799 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002800 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002801 }
2802
2803 // Because of short-circuit evaluation, the condition of the loop can span
2804 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2805 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002806 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002807
2808 do {
2809 Expr *C = W->getCond();
2810
2811 // Specially handle logical operators, which have a slightly
2812 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002813 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002814 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002815 std::tie(EntryConditionBlock, ExitConditionBlock) =
2816 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002817 break;
2818 }
2819
2820 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00002821 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002822 ExitConditionBlock->setTerminator(W);
2823
2824 // Now add the actual condition to the condition block.
2825 // Because the condition itself may contain control-flow, new blocks may
2826 // be created. Thus we update "Succ" after adding the condition.
2827 Block = ExitConditionBlock;
2828 Block = EntryConditionBlock = addStmt(C);
2829
2830 // If this block contains a condition variable, add both the condition
2831 // variable and initializer to the CFG.
2832 if (VarDecl *VD = W->getConditionVariable()) {
2833 if (Expr *Init = VD->getInit()) {
2834 autoCreateBlock();
2835 appendStmt(Block, W->getConditionVariableDeclStmt());
2836 EntryConditionBlock = addStmt(Init);
2837 assert(Block == EntryConditionBlock);
2838 }
Ted Kremenek55957a82009-05-02 00:13:27 +00002839 }
Mike Stump31feda52009-07-17 01:31:16 +00002840
Ted Kremenekb50e7162012-07-14 05:04:10 +00002841 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002842 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002843
2844 // See if this is a known constant.
2845 const TryResult& KnownVal = tryEvaluateBool(C);
2846
Ted Kremenek30754282009-07-24 04:47:11 +00002847 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002848 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002849 // Link up the condition block with the code that follows the loop. (the
2850 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002851 addSuccessor(ExitConditionBlock,
2852 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002853
Ted Kremenekb50e7162012-07-14 05:04:10 +00002854 } while(false);
2855
2856 // Link up the loop-back block to the entry condition block.
2857 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00002858
2859 // There can be no more statements in the condition block since we loop back
2860 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002861 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002862
Ted Kremenek1ce53c42009-12-24 01:34:10 +00002863 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002864 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00002865 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002866}
Mike Stump11289f42009-09-09 15:08:12 +00002867
2868
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002869CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002870 // FIXME: For now we pretend that @catch and the code it contains does not
2871 // exit.
2872 return Block;
2873}
Mike Stump31feda52009-07-17 01:31:16 +00002874
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002875CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00002876 // FIXME: This isn't complete. We basically treat @throw like a return
2877 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00002878
Ted Kremenek0868eea2009-09-24 18:45:41 +00002879 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002880 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002881 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002882
Ted Kremenek93041ba2008-12-09 20:20:09 +00002883 // Create the new block.
2884 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002885
Ted Kremenek93041ba2008-12-09 20:20:09 +00002886 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002887 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002888
2889 // Add the statement to the block. This may create new blocks if S contains
2890 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002891 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00002892}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002893
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002894CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002895 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002896 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002897 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002898
2899 // Create the new block.
2900 Block = createBlock(false);
2901
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002902 if (TryTerminatedBlock)
2903 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002904 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002905 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002906 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002907 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002908
2909 // Add the statement to the block. This may create new blocks if S contains
2910 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002911 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002912}
2913
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002914CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00002915 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002916
Mike Stump8d50b6a2009-07-21 01:27:50 +00002917 // "do...while" is a control-flow statement. Thus we stop processing the
2918 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002919 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002920 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002921 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002922 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002923 } else
2924 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002925
2926 // Because of short-circuit evaluation, the condition of the loop can span
2927 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2928 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002929 CFGBlock *ExitConditionBlock = createBlock(false);
2930 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002931
Ted Kremenek81e14852007-08-27 19:46:09 +00002932 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002933 ExitConditionBlock->setTerminator(D);
2934
2935 // Now add the actual condition to the condition block. Because the condition
2936 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002937 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00002938 Block = ExitConditionBlock;
2939 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00002940 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002941 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002942 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002943 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002944 }
Mike Stump31feda52009-07-17 01:31:16 +00002945
Ted Kremeneka1523a32008-02-27 07:20:00 +00002946 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00002947 Succ = EntryConditionBlock;
2948
Mike Stump773582d2009-07-23 23:25:26 +00002949 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002950 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002951
Ted Kremenek9aae5132007-08-23 21:42:29 +00002952 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00002953 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002954 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002955 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002956
Ted Kremenek9aae5132007-08-23 21:42:29 +00002957 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002958 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2959 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2960 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002961
Ted Kremenek9aae5132007-08-23 21:42:29 +00002962 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002963 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002964
Ted Kremenek9aae5132007-08-23 21:42:29 +00002965 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002966 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002967
Ted Kremenek9aae5132007-08-23 21:42:29 +00002968 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00002969 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002970
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002971 // If body is not a compound statement create implicit scope
2972 // and add destructors.
2973 if (!isa<CompoundStmt>(D->getBody()))
2974 addLocalScopeAndDtors(D->getBody());
2975
Ted Kremenek9aae5132007-08-23 21:42:29 +00002976 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00002977 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002978
Ted Kremeneke9610502007-08-30 18:39:40 +00002979 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00002980 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00002981 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002982 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002983 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002984 }
Mike Stump31feda52009-07-17 01:31:16 +00002985
Ted Kremenek110974d2010-08-17 20:59:56 +00002986 if (!KnownVal.isFalse()) {
2987 // Add an intermediate block between the BodyBlock and the
2988 // ExitConditionBlock to represent the "loop back" transition. Create an
2989 // empty block to represent the transition block for looping back to the
2990 // head of the loop.
2991 // FIXME: Can we do this more efficiently without adding another block?
Craig Topper25542942014-05-20 04:30:07 +00002992 Block = nullptr;
Ted Kremenek110974d2010-08-17 20:59:56 +00002993 Succ = BodyBlock;
2994 CFGBlock *LoopBackBlock = createBlock();
2995 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00002996
Ted Kremenek110974d2010-08-17 20:59:56 +00002997 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002998 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00002999 }
3000 else
Craig Topper25542942014-05-20 04:30:07 +00003001 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003002 }
Mike Stump31feda52009-07-17 01:31:16 +00003003
Ted Kremenek30754282009-07-24 04:47:11 +00003004 // Link up the condition block with the code that follows the loop.
3005 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00003006 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003007
3008 // There can be no more statements in the body block(s) since we loop back to
3009 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00003010 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003011
Ted Kremenek9aae5132007-08-23 21:42:29 +00003012 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00003013 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003014 return BodyBlock;
3015}
3016
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003017CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00003018 // "continue" is a control-flow statement. Thus we stop processing the
3019 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003020 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003021 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003022
Ted Kremenek9aae5132007-08-23 21:42:29 +00003023 // Now create a new block that ends with the continue statement.
3024 Block = createBlock(false);
3025 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00003026
Ted Kremenek9aae5132007-08-23 21:42:29 +00003027 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00003028 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00003029 if (ContinueJumpTarget.block) {
3030 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
3031 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003032 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00003033 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00003034
Ted Kremenek9aae5132007-08-23 21:42:29 +00003035 return Block;
3036}
Mike Stump11289f42009-09-09 15:08:12 +00003037
Peter Collingbournee190dee2011-03-11 19:24:49 +00003038CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
3039 AddStmtChoice asc) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003040
Ted Kremenek7c58d352011-03-10 01:14:11 +00003041 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003042 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003043 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00003044 }
Mike Stump11289f42009-09-09 15:08:12 +00003045
Ted Kremenek93668002009-07-17 22:18:43 +00003046 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003047 CFGBlock *lastBlock = Block;
3048
Ted Kremenek93668002009-07-17 22:18:43 +00003049 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00003050 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00003051 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003052 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00003053 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00003054 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003055}
Mike Stump11289f42009-09-09 15:08:12 +00003056
Ted Kremenek93668002009-07-17 22:18:43 +00003057/// VisitStmtExpr - Utility method to handle (nested) statement
3058/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003059CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003060 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00003061 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00003062 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00003063 }
Ted Kremenek93668002009-07-17 22:18:43 +00003064 return VisitCompoundStmt(SE->getSubStmt());
3065}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003066
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003067CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00003068 // "switch" is a control-flow statement. Thus we stop processing the current
3069 // block.
Craig Topper25542942014-05-20 04:30:07 +00003070 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003071
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003072 // Save local scope position because in case of condition variable ScopePos
3073 // won't be restored when traversing AST.
3074 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3075
Richard Smitha547eb22016-07-14 00:11:03 +00003076 // Create local scope for C++17 switch init-stmt if one exists.
3077 if (Stmt *Init = Terminator->getInit()) {
3078 LocalScope::const_iterator BeginScopePos = ScopePos;
3079 addLocalScopeForStmt(Init);
3080 addAutomaticObjDtors(ScopePos, BeginScopePos, Terminator);
3081 }
3082
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003083 // Create local scope for possible condition variable.
3084 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003085 if (VarDecl *VD = Terminator->getConditionVariable()) {
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003086 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
3087 addLocalScopeForVarDecl(VD);
3088 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
3089 }
3090
Ted Kremenek9aae5132007-08-23 21:42:29 +00003091 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003092 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003093 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003094 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003095 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003096
3097 // Save the current "switch" context.
3098 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003099 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003100 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003101
Mike Stump31feda52009-07-17 01:31:16 +00003102 // Set the "default" case to be the block after the switch statement. If the
3103 // switch statement contains a "default:", this value will be overwritten with
3104 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003105 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003106
Ted Kremenek9aae5132007-08-23 21:42:29 +00003107 // Create a new block that will contain the switch statement.
3108 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003109
Ted Kremenek9aae5132007-08-23 21:42:29 +00003110 // Now process the switch body. The code after the switch is the implicit
3111 // successor.
3112 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003113 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003114
3115 // When visiting the body, the case statements should automatically get linked
3116 // up to the switch. We also don't keep a pointer to the body, since all
3117 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003118 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003119 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003120
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003121 // For pruning unreachable case statements, save the current state
3122 // for tracking the condition value.
3123 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3124 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003125
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003126 // Determine if the switch condition can be explicitly evaluated.
3127 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003128 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003129 bool b = tryEvaluate(Terminator->getCond(), result);
3130 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003131 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003132
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003133 // If body is not a compound statement create implicit scope
3134 // and add destructors.
3135 if (!isa<CompoundStmt>(Terminator->getBody()))
3136 addLocalScopeAndDtors(Terminator->getBody());
3137
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003138 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003139 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003140 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003141 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003142 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003143
Mike Stump31feda52009-07-17 01:31:16 +00003144 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003145 // following the switch body. Moreover, take into account if all the
3146 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003147 //
3148 // Note: We add a successor to a switch that is considered covered yet has no
3149 // case statements if the enumeration has no enumerators.
3150 bool SwitchAlwaysHasSuccessor = false;
3151 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3152 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3153 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003154 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3155 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003156
Ted Kremenek81e14852007-08-27 19:46:09 +00003157 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003158 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003159 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003160 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003161
Richard Smitha547eb22016-07-14 00:11:03 +00003162 // If the SwitchStmt contains a condition variable, add both the
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003163 // SwitchStmt and the condition variable initialization to the CFG.
3164 if (VarDecl *VD = Terminator->getConditionVariable()) {
3165 if (Expr *Init = VD->getInit()) {
3166 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003167 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003168 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003169 }
3170 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003171
Richard Smitha547eb22016-07-14 00:11:03 +00003172 // Finally, if the SwitchStmt contains a C++17 init-stmt, add it to the CFG.
3173 if (Stmt *Init = Terminator->getInit()) {
3174 autoCreateBlock();
3175 LastBlock = addStmt(Init);
3176 }
3177
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003178 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003179}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003180
3181static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003182 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003183 const CaseStmt *CS,
3184 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003185 if (!switchCond)
3186 return true;
3187
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003188 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003189
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003190 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003191 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003192 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003193 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003194 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003195
3196 if (condInt == lhsInt) {
3197 addCase = true;
3198 switchExclusivelyCovered = true;
3199 }
Devin Coughlineb538ab2015-09-22 20:31:19 +00003200 else if (condInt > lhsInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003201 if (const Expr *RHS = CS->getRHS()) {
3202 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003203 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
Devin Coughlineb538ab2015-09-22 20:31:19 +00003204 if (V2 >= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003205 addCase = true;
3206 switchExclusivelyCovered = true;
3207 }
3208 }
3209 }
3210 }
3211 else
3212 addCase = true;
3213 }
3214 return addCase;
3215}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003216
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003217CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003218 // CaseStmts are essentially labels, so they are the first statement in a
3219 // block.
Craig Topper25542942014-05-20 04:30:07 +00003220 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003221
Ted Kremenek60fa6572010-08-04 23:54:30 +00003222 if (Stmt *Sub = CS->getSubStmt()) {
3223 // For deeply nested chains of CaseStmts, instead of doing a recursion
3224 // (which can blow out the stack), manually unroll and create blocks
3225 // along the way.
3226 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003227 CFGBlock *currentBlock = createBlock(false);
3228 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003229
Ted Kremenek60fa6572010-08-04 23:54:30 +00003230 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003231 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003232 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003233 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003234
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003235 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003236 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003237 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003238 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003239
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003240 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003241 CS = cast<CaseStmt>(Sub);
3242 Sub = CS->getSubStmt();
3243 }
3244
3245 addStmt(Sub);
3246 }
Mike Stump11289f42009-09-09 15:08:12 +00003247
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003248 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003249 if (!CaseBlock)
3250 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003251
3252 // Cases statements partition blocks, so this is the top of the basic block we
3253 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003254 CaseBlock->setLabel(CS);
3255
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003256 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003257 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003258
3259 // Add this block to the list of successors for the block with the switch
3260 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003261 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003262 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003263 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003264 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003265
Ted Kremenek9aae5132007-08-23 21:42:29 +00003266 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003267 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003268
Ted Kremenek60fa6572010-08-04 23:54:30 +00003269 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003270 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003271 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003272 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003273 // This block is now the implicit successor of other blocks.
3274 Succ = CaseBlock;
3275 }
Mike Stump31feda52009-07-17 01:31:16 +00003276
Ted Kremenek60fa6572010-08-04 23:54:30 +00003277 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003278}
Mike Stump31feda52009-07-17 01:31:16 +00003279
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003280CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003281 if (Terminator->getSubStmt())
3282 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003283
Ted Kremenek654c78f2008-02-13 22:05:39 +00003284 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003285
3286 if (!DefaultCaseBlock)
3287 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003288
3289 // Default statements partition blocks, so this is the top of the basic block
3290 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003291 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003292
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003293 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003294 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003295
Mike Stump31feda52009-07-17 01:31:16 +00003296 // Unlike case statements, we don't add the default block to the successors
3297 // for the switch statement immediately. This is done when we finish
3298 // processing the switch statement. This allows for the default case
3299 // (including a fall-through to the code after the switch statement) to always
3300 // be the last successor of a switch-terminated block.
3301
Ted Kremenek654c78f2008-02-13 22:05:39 +00003302 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003303 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003304
Ted Kremenek654c78f2008-02-13 22:05:39 +00003305 // This block is now the implicit successor of other blocks.
3306 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003307
3308 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003309}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003310
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003311CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3312 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3313 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003314 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003315
3316 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003317 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003318 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003319 TrySuccessor = Block;
3320 } else TrySuccessor = Succ;
3321
Mike Stump0bdba6c2010-01-20 01:15:34 +00003322 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003323
3324 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003325 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003326 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003327 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003328
Mike Stump0bdba6c2010-01-20 01:15:34 +00003329 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003330 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3331 // The code after the try is the implicit successor.
3332 Succ = TrySuccessor;
3333 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003334 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003335 HasCatchAll = true;
3336 }
Craig Topper25542942014-05-20 04:30:07 +00003337 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003338 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003339 if (!CatchBlock)
3340 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003341 // Add this block to the list of successors for the block with the try
3342 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003343 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003344 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003345 if (!HasCatchAll) {
3346 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003347 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003348 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003349 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003350 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003351
3352 // The code after the try is the implicit successor.
3353 Succ = TrySuccessor;
3354
Mike Stump845384a2010-01-20 01:30:58 +00003355 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003356 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3357 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003358
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003359 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003360 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003361 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003362}
3363
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003364CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003365 // CXXCatchStmt are treated like labels, so they are the first statement in a
3366 // block.
3367
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003368 // Save local scope position because in case of exception variable ScopePos
3369 // won't be restored when traversing AST.
3370 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3371
3372 // Create local scope for possible exception variable.
3373 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003374 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003375 LocalScope::const_iterator BeginScopePos = ScopePos;
3376 addLocalScopeForVarDecl(VD);
3377 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3378 }
3379
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003380 if (CS->getHandlerBlock())
3381 addStmt(CS->getHandlerBlock());
3382
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003383 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003384 if (!CatchBlock)
3385 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003386
3387 // CXXCatchStmt is more than just a label. They have semantic meaning
3388 // as well, as they implicitly "initialize" the catch variable. Add
3389 // it to the CFG as a CFGElement so that the control-flow of these
3390 // semantics gets captured.
3391 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003392
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003393 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3394 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003395 CatchBlock->setLabel(CS);
3396
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003397 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003398 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003399 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003400
3401 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003402 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003403
3404 return CatchBlock;
3405}
3406
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003407CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003408 // C++0x for-range statements are specified as [stmt.ranged]:
3409 //
3410 // {
3411 // auto && __range = range-init;
3412 // for ( auto __begin = begin-expr,
3413 // __end = end-expr;
3414 // __begin != __end;
3415 // ++__begin ) {
3416 // for-range-declaration = *__begin;
3417 // statement
3418 // }
3419 // }
3420
3421 // Save local scope position before the addition of the implicit variables.
3422 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3423
3424 // Create local scopes and destructors for range, begin and end variables.
3425 if (Stmt *Range = S->getRangeStmt())
3426 addLocalScopeForStmt(Range);
Richard Smith01694c32016-03-20 10:33:40 +00003427 if (Stmt *Begin = S->getBeginStmt())
3428 addLocalScopeForStmt(Begin);
3429 if (Stmt *End = S->getEndStmt())
3430 addLocalScopeForStmt(End);
Richard Smith02e85f32011-04-14 22:09:26 +00003431 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3432
3433 LocalScope::const_iterator ContinueScopePos = ScopePos;
3434
3435 // "for" is a control-flow statement. Thus we stop processing the current
3436 // block.
Craig Topper25542942014-05-20 04:30:07 +00003437 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003438 if (Block) {
3439 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003440 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003441 LoopSuccessor = Block;
3442 } else
3443 LoopSuccessor = Succ;
3444
3445 // Save the current value for the break targets.
3446 // All breaks should go to the code following the loop.
3447 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3448 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3449
3450 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003451 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003452 ConditionBlock->setTerminator(S);
3453
3454 // Now add the actual condition to the condition block.
3455 if (Expr *C = S->getCond()) {
3456 Block = ConditionBlock;
3457 CFGBlock *BeginConditionBlock = addStmt(C);
3458 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003459 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003460 assert(BeginConditionBlock == ConditionBlock &&
3461 "condition block in for-range was unexpectedly complex");
3462 (void)BeginConditionBlock;
3463 }
3464
3465 // The condition block is the implicit successor for the loop body as well as
3466 // any code above the loop.
3467 Succ = ConditionBlock;
3468
3469 // See if this is a known constant.
3470 TryResult KnownVal(true);
3471
3472 if (S->getCond())
3473 KnownVal = tryEvaluateBool(S->getCond());
3474
3475 // Now create the loop body.
3476 {
3477 assert(S->getBody());
3478
3479 // Save the current values for Block, Succ, and continue targets.
3480 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3481 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3482
3483 // Generate increment code in its own basic block. This is the target of
3484 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003485 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003486 Succ = addStmt(S->getInc());
Alexander Kornienkoff2046a2016-07-08 10:50:51 +00003487 if (badCFG)
3488 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003489 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3490
3491 // The starting block for the loop increment is the block that should
3492 // represent the 'loop target' for looping back to the start of the loop.
3493 ContinueJumpTarget.block->setLoopTarget(S);
3494
3495 // Finish up the increment block and prepare to start the loop body.
3496 assert(Block);
3497 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003498 return nullptr;
3499 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003500
3501 // Add implicit scope and dtors for loop variable.
3502 addLocalScopeAndDtors(S->getLoopVarStmt());
3503
3504 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003505 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003506 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003507 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003508 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003509 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003510 return nullptr;
3511
Richard Smith02e85f32011-04-14 22:09:26 +00003512 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003513 addSuccessor(ConditionBlock,
3514 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003515 }
3516
3517 // Link up the condition block with the code that follows the loop (the
3518 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003519 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003520
3521 // Add the initialization statements.
3522 Block = createBlock();
Richard Smith01694c32016-03-20 10:33:40 +00003523 addStmt(S->getBeginStmt());
3524 addStmt(S->getEndStmt());
Richard Smith0c502d22011-04-18 15:49:25 +00003525 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003526}
3527
John McCall5d413782010-12-06 08:20:24 +00003528CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003529 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003530 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003531 // If adding implicit destructors visit the full expression for adding
3532 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003533 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003534 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003535
3536 // Full expression has to be added as CFGStmt so it will be sequenced
3537 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003538 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003539 }
3540 return Visit(E->getSubExpr(), asc);
3541}
3542
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003543CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3544 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003545 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003546 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003547 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003548
3549 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003550 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003551 }
3552 return Visit(E->getSubExpr(), asc);
3553}
3554
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003555CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3556 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003557 autoCreateBlock();
Zhongxing Xuf0cb43f2012-01-11 02:39:07 +00003558 appendStmt(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003559
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003560 return VisitChildren(C);
3561}
3562
Jordan Rosec9176072014-01-13 17:59:19 +00003563CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3564 AddStmtChoice asc) {
3565
3566 autoCreateBlock();
3567 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003568
Jordan Rosec9176072014-01-13 17:59:19 +00003569 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003570 Block = Visit(NE->getInitializer());
Jordan Rosec9176072014-01-13 17:59:19 +00003571 if (BuildOpts.AddCXXNewAllocator)
3572 appendNewAllocator(Block, NE);
3573 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003574 Block = Visit(NE->getArraySize());
Jordan Rosec9176072014-01-13 17:59:19 +00003575 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3576 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003577 Block = Visit(*I);
Jordan Rosec9176072014-01-13 17:59:19 +00003578 return Block;
3579}
Jordan Rosed2f40792013-09-03 17:00:57 +00003580
3581CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3582 AddStmtChoice asc) {
3583 autoCreateBlock();
3584 appendStmt(Block, DE);
3585 QualType DTy = DE->getDestroyedType();
3586 DTy = DTy.getNonReferenceType();
3587 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3588 if (RD) {
Matt Beaumont-Gay093f2402013-09-09 21:07:58 +00003589 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
Jordan Rosed2f40792013-09-03 17:00:57 +00003590 appendDeleteDtor(Block, RD, DE);
3591 }
3592
3593 return VisitChildren(DE);
3594}
3595
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003596CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3597 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003598 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003599 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003600 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003601 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003602 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003603 }
3604 return Visit(E->getSubExpr(), asc);
3605}
3606
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003607CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3608 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003609 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003610 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003611 return VisitChildren(C);
3612}
3613
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003614CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3615 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003616 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003617 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003618 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003619 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003620 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003621}
3622
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003623CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00003624 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003625 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003626
Ted Kremenekeda180e22007-08-28 19:26:49 +00003627 if (!IBlock) {
3628 IBlock = createBlock(false);
3629 cfg->setIndirectGotoBlock(IBlock);
3630 }
Mike Stump31feda52009-07-17 01:31:16 +00003631
Ted Kremenekeda180e22007-08-28 19:26:49 +00003632 // IndirectGoto is a control-flow statement. Thus we stop processing the
3633 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003634 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003635 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003636
Ted Kremenekeda180e22007-08-28 19:26:49 +00003637 Block = createBlock(false);
3638 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003639 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00003640 return addStmt(I->getTarget());
3641}
3642
Manuel Klimekb5616c92014-08-07 10:42:17 +00003643CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3644 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003645 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3646
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003647tryAgain:
3648 if (!E) {
3649 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00003650 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003651 }
3652 switch (E->getStmtClass()) {
3653 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003654 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003655
3656 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003657 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3658 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003659
3660 case Stmt::CXXBindTemporaryExprClass:
3661 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003662 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003663
John McCallc07a0c72011-02-17 10:25:35 +00003664 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003665 case Stmt::ConditionalOperatorClass:
3666 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003667 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003668
3669 case Stmt::ImplicitCastExprClass:
3670 // For implicit cast we want BindToTemporary to be passed further.
3671 E = cast<CastExpr>(E)->getSubExpr();
3672 goto tryAgain;
3673
Manuel Klimekb0042c42014-07-30 08:34:42 +00003674 case Stmt::CXXFunctionalCastExprClass:
3675 // For functional cast we want BindToTemporary to be passed further.
3676 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3677 goto tryAgain;
3678
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003679 case Stmt::ParenExprClass:
3680 E = cast<ParenExpr>(E)->getSubExpr();
3681 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00003682
Manuel Klimekb0042c42014-07-30 08:34:42 +00003683 case Stmt::MaterializeTemporaryExprClass: {
3684 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3685 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3686 SmallVector<const Expr *, 2> CommaLHSs;
3687 SmallVector<SubobjectAdjustment, 2> Adjustments;
3688 // Find the expression whose lifetime needs to be extended.
3689 E = const_cast<Expr *>(
3690 cast<MaterializeTemporaryExpr>(E)
3691 ->GetTemporaryExpr()
3692 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3693 // Visit the skipped comma operator left-hand sides for other temporaries.
3694 for (const Expr *CommaLHS : CommaLHSs) {
3695 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00003696 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00003697 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003698 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00003699 }
Richard Smith4137af22014-07-27 05:12:49 +00003700
3701 case Stmt::BlockExprClass:
3702 // Don't recurse into blocks; their subexpressions don't get evaluated
3703 // here.
3704 return Block;
3705
3706 case Stmt::LambdaExprClass: {
3707 // For lambda expressions, only recurse into the capture initializers,
3708 // and not the body.
3709 auto *LE = cast<LambdaExpr>(E);
3710 CFGBlock *B = Block;
3711 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003712 if (CFGBlock *R = VisitForTemporaryDtors(
3713 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00003714 B = R;
3715 }
3716 return B;
3717 }
3718
3719 case Stmt::CXXDefaultArgExprClass:
3720 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3721 goto tryAgain;
3722
3723 case Stmt::CXXDefaultInitExprClass:
3724 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3725 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003726 }
3727}
3728
Manuel Klimekb5616c92014-08-07 10:42:17 +00003729CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3730 TempDtorContext &Context) {
3731 if (isa<LambdaExpr>(E)) {
3732 // Do not visit the children of lambdas; they have their own CFGs.
3733 return Block;
3734 }
3735
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003736 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00003737 // order that they will appear in the CFG. Because the CFG is built
3738 // bottom-up, this means we visit them in their natural order, which
3739 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003740 CFGBlock *B = Block;
Benjamin Kramer642f1732015-07-02 21:03:14 +00003741 for (Stmt *Child : E->children())
3742 if (Child)
Manuel Klimekb5616c92014-08-07 10:42:17 +00003743 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00003744 B = R;
Benjamin Kramer642f1732015-07-02 21:03:14 +00003745
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003746 return B;
3747}
3748
Manuel Klimekb5616c92014-08-07 10:42:17 +00003749CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3750 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003751 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003752 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00003753 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3754 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3755 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00003756
Manuel Klimekedf925b92014-08-07 18:44:19 +00003757 // We do not know at CFG-construction time whether the right-hand-side was
3758 // executed, thus we add a branch node that depends on the temporary
3759 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003760 TempDtorContext RHSContext(
3761 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00003762 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00003763 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00003764
Manuel Klimekb5616c92014-08-07 10:42:17 +00003765 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003766 }
3767
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003768 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003769 // For assignment operator (=) LHS expression is visited
3770 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003771 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3772 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003773 return LHSBlock ? LHSBlock : RHSBlock;
3774 }
3775
3776 // For any other binary operator RHS expression is visited before
3777 // LHS expression (order of children). For destructors visit them in reverse
3778 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003779 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3780 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003781 return RHSBlock ? RHSBlock : LHSBlock;
3782}
3783
3784CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003785 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003786 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003787 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00003788 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003789 // If lifetime of temporary is not prolonged (by assigning to constant
3790 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00003791
Chandler Carruthad747252011-09-13 06:09:01 +00003792 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003793
Richard Trieu95a192a2015-05-28 00:14:02 +00003794 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003795 // If the destructor is marked as a no-return destructor, we need to
3796 // create a new block for the destructor which does not have as a
3797 // successor anything built thus far. Control won't flow out of this
3798 // block.
3799 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00003800 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003801 } else if (Context.needsTempDtorBranch()) {
3802 // If we need to introduce a branch, we add a new block that we will hook
3803 // up to a decision block later.
3804 if (B) Succ = B;
3805 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003806 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00003807 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003808 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00003809 if (Context.needsTempDtorBranch()) {
3810 Context.setDecisionPoint(Succ, E);
3811 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003812 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003813
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003814 B = Block;
3815 }
3816 return B;
3817}
3818
Manuel Klimekb5616c92014-08-07 10:42:17 +00003819void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3820 CFGBlock *FalseSucc) {
3821 if (!Context.TerminatorExpr) {
3822 // If no temporary was found, we do not need to insert a decision point.
3823 return;
3824 }
3825 assert(Context.TerminatorExpr);
3826 CFGBlock *Decision = createBlock(false);
3827 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00003828 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003829 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00003830 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00003831 Block = Decision;
3832}
3833
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003834CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003835 AbstractConditionalOperator *E, bool BindToTemporary,
3836 TempDtorContext &Context) {
3837 VisitForTemporaryDtors(E->getCond(), false, Context);
3838 CFGBlock *ConditionBlock = Block;
3839 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00003840 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003841 TryResult NegatedVal = ConditionVal;
3842 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00003843
Manuel Klimekdeb02622014-08-08 07:37:13 +00003844 TempDtorContext TrueContext(
3845 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003846 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003847 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003848
Manuel Klimekb5616c92014-08-07 10:42:17 +00003849 Block = ConditionBlock;
3850 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003851 TempDtorContext FalseContext(
3852 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003853 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003854
Manuel Klimekb5616c92014-08-07 10:42:17 +00003855 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003856 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003857 } else if (TrueContext.TerminatorExpr) {
3858 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003859 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003860 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003861 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003862 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003863 return Block;
3864}
3865
Ted Kremenek04cca642007-08-23 21:26:19 +00003866} // end anonymous namespace
Ted Kremenek889073f2007-08-23 16:51:22 +00003867
Mike Stump31feda52009-07-17 01:31:16 +00003868/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3869/// no successors or predecessors. If this is the first block created in the
3870/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003871CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00003872 bool first_block = begin() == end();
3873
3874 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003875 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00003876 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003877 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00003878
3879 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003880 if (first_block)
3881 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00003882
3883 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003884 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00003885}
3886
David Blaikiee90195c2014-08-29 18:53:26 +00003887/// buildCFG - Constructs a CFG from an AST.
3888std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3889 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00003890 CFGBuilder Builder(C, BO);
3891 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00003892}
3893
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003894const CXXDestructorDecl *
3895CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003896 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003897 case CFGElement::Statement:
3898 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00003899 case CFGElement::NewAllocator:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003900 llvm_unreachable("getDestructorDecl should only be used with "
3901 "ImplicitDtors");
3902 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00003903 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003904 QualType ty = var->getType();
Ted Kremenek1676a042011-03-03 01:01:03 +00003905 ty = ty.getNonReferenceType();
Ted Kremeneke7d78882012-03-19 23:48:41 +00003906 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003907 ty = arrayType->getElementType();
3908 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003909 const RecordType *recordType = ty->getAs<RecordType>();
3910 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00003911 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003912 return classDecl->getDestructor();
3913 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003914 case CFGElement::DeleteDtor: {
3915 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3916 QualType DTy = DE->getDestroyedType();
3917 DTy = DTy.getNonReferenceType();
3918 const CXXRecordDecl *classDecl =
3919 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3920 return classDecl->getDestructor();
3921 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003922 case CFGElement::TemporaryDtor: {
3923 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00003924 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003925 const CXXTemporary *temp = bindExpr->getTemporary();
3926 return temp->getDestructor();
3927 }
3928 case CFGElement::BaseDtor:
3929 case CFGElement::MemberDtor:
3930
3931 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00003932 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003933 }
Ted Kremenek1676a042011-03-03 01:01:03 +00003934 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003935}
3936
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003937bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00003938 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3939 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003940 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00003941}
3942
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00003943//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003944// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00003945//===----------------------------------------------------------------------===//
3946
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003947CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Craig Topper25542942014-05-20 04:30:07 +00003948 : ReachableBlock(IsReachable ? B : nullptr),
3949 UnreachableBlock(!IsReachable ? B : nullptr,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003950 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3951
3952CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3953 : ReachableBlock(B),
Craig Topper25542942014-05-20 04:30:07 +00003954 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003955 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3956
3957void CFGBlock::addSuccessor(AdjacentBlock Succ,
3958 BumpVectorContext &C) {
3959 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003960 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003961
3962 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003963 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003964
3965 Succs.push_back(Succ, C);
3966}
3967
Ted Kremenekb0371852010-09-09 00:06:04 +00003968bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00003969 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003970
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003971 if (F.IgnoreNullPredecessors && !From)
3972 return true;
3973
3974 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003975 // If the 'To' has no label or is labeled but the label isn't a
3976 // CaseStmt then filter this edge.
3977 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00003978 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003979 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00003980 const Stmt *L = To->getLabel();
3981 if (!L || !isa<CaseStmt>(L))
3982 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00003983 }
3984 }
3985 }
3986
3987 return false;
3988}
3989
3990//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00003991// CFG pretty printing
3992//===----------------------------------------------------------------------===//
3993
Ted Kremenek7e776b12007-08-22 18:22:34 +00003994namespace {
3995
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003996class StmtPrinterHelper : public PrinterHelper {
Ted Kremenek96a7a592011-03-01 03:15:10 +00003997 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3998 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003999 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004000 DeclMapTy DeclMap;
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004001 signed currentBlock;
Ted Kremenekd94854a2012-08-22 06:26:15 +00004002 unsigned currStmt;
Chris Lattnerc61089a2009-06-30 01:26:17 +00004003 const LangOptions &LangOpts;
Ted Kremenek9aae5132007-08-23 21:42:29 +00004004public:
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004005
Chris Lattnerc61089a2009-06-30 01:26:17 +00004006 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Ted Kremenekd94854a2012-08-22 06:26:15 +00004007 : currentBlock(0), currStmt(0), LangOpts(LO)
Ted Kremenek96a7a592011-03-01 03:15:10 +00004008 {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004009 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
4010 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004011 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004012 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00004013 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
4014 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004015 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00004016 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004017
Ted Kremenek96a7a592011-03-01 03:15:10 +00004018 switch (stmt->getStmtClass()) {
4019 case Stmt::DeclStmtClass:
4020 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
4021 break;
4022 case Stmt::IfStmtClass: {
4023 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
4024 if (var)
4025 DeclMap[var] = P;
4026 break;
4027 }
4028 case Stmt::ForStmtClass: {
4029 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
4030 if (var)
4031 DeclMap[var] = P;
4032 break;
4033 }
4034 case Stmt::WhileStmtClass: {
4035 const VarDecl *var =
4036 cast<WhileStmt>(stmt)->getConditionVariable();
4037 if (var)
4038 DeclMap[var] = P;
4039 break;
4040 }
4041 case Stmt::SwitchStmtClass: {
4042 const VarDecl *var =
4043 cast<SwitchStmt>(stmt)->getConditionVariable();
4044 if (var)
4045 DeclMap[var] = P;
4046 break;
4047 }
4048 case Stmt::CXXCatchStmtClass: {
4049 const VarDecl *var =
4050 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
4051 if (var)
4052 DeclMap[var] = P;
4053 break;
4054 }
4055 default:
4056 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004057 }
4058 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004059 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00004060 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004061 }
Mike Stump31feda52009-07-17 01:31:16 +00004062
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00004063 ~StmtPrinterHelper() override {}
Mike Stump31feda52009-07-17 01:31:16 +00004064
Chris Lattnerc61089a2009-06-30 01:26:17 +00004065 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004066 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00004067 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00004068
Craig Topperb45acb82014-03-14 06:02:07 +00004069 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004070 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004071
4072 if (I == StmtMap.end())
4073 return false;
Mike Stump31feda52009-07-17 01:31:16 +00004074
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004075 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004076 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004077 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004078 }
Mike Stump31feda52009-07-17 01:31:16 +00004079
Ted Kremenek60983dc2010-01-19 20:52:05 +00004080 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004081 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004082 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004083
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004084 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004085 DeclMapTy::iterator I = DeclMap.find(D);
4086
4087 if (I == DeclMap.end())
4088 return false;
4089
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00004090 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00004091 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004092 return false;
4093 }
4094
4095 OS << "[B" << I->second.first << "." << I->second.second << "]";
4096 return true;
4097 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004098};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004099} // end anonymous namespace
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004100
Chris Lattnerc61089a2009-06-30 01:26:17 +00004101
4102namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004103class CFGBlockTerminatorPrint
Ted Kremenek83ebcef2008-01-08 18:15:10 +00004104 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Mike Stump31feda52009-07-17 01:31:16 +00004105
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004106 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004107 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004108 PrintingPolicy Policy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004109public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004110 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004111 const PrintingPolicy &Policy)
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004112 : OS(os), Helper(helper), Policy(Policy) {
4113 this->Policy.IncludeNewlines = false;
4114 }
Mike Stump31feda52009-07-17 01:31:16 +00004115
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004116 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004117 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004118 if (Stmt *C = I->getCond())
4119 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004120 }
Mike Stump31feda52009-07-17 01:31:16 +00004121
Ted Kremenek9aae5132007-08-23 21:42:29 +00004122 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004123 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004124 Terminator->printPretty(OS, Helper, Policy);
4125 }
4126
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004127 void VisitDeclStmt(DeclStmt *DS) {
4128 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4129 OS << "static init " << VD->getName();
4130 }
4131
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004132 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004133 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004134 if (F->getInit())
4135 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004136 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004137 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004138 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004139 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004140 if (F->getInc())
4141 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004142 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004143 }
Mike Stump31feda52009-07-17 01:31:16 +00004144
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004145 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004146 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004147 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004148 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004149 }
Mike Stump31feda52009-07-17 01:31:16 +00004150
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004151 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004152 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004153 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004154 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004155 }
Mike Stump31feda52009-07-17 01:31:16 +00004156
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004157 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004158 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004159 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004160 }
Mike Stump31feda52009-07-17 01:31:16 +00004161
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004162 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004163 OS << "try ...";
4164 }
4165
John McCallc07a0c72011-02-17 10:25:35 +00004166 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004167 if (Stmt *Cond = C->getCond())
4168 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004169 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004170 }
Mike Stump31feda52009-07-17 01:31:16 +00004171
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004172 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004173 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004174 if (Stmt *Cond = C->getCond())
4175 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004176 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004177 }
Mike Stump31feda52009-07-17 01:31:16 +00004178
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004179 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004180 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004181 if (Stmt *T = I->getTarget())
4182 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004183 }
Mike Stump31feda52009-07-17 01:31:16 +00004184
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004185 void VisitBinaryOperator(BinaryOperator* B) {
4186 if (!B->isLogicalOp()) {
4187 VisitExpr(B);
4188 return;
4189 }
Mike Stump31feda52009-07-17 01:31:16 +00004190
Richard Trieuddd01ce2014-06-09 22:53:25 +00004191 if (B->getLHS())
4192 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004193
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004194 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004195 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004196 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004197 return;
John McCalle3027922010-08-25 11:45:40 +00004198 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004199 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004200 return;
4201 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004202 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004203 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004204 }
Mike Stump31feda52009-07-17 01:31:16 +00004205
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004206 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004207 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004208 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004209
4210public:
4211 void print(CFGTerminator T) {
4212 if (T.isTemporaryDtorsBranch())
4213 OS << "(Temp Dtor) ";
4214 Visit(T.getStmt());
4215 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004216};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004217} // end anonymous namespace
4218
Aaron Ballmanff924b02013-11-18 20:11:50 +00004219static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004220 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004221 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4222 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004223 assert(S != nullptr && "Expecting non-null Stmt");
4224
Aaron Ballmanff924b02013-11-18 20:11:50 +00004225 // special printing for statement-expressions.
4226 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4227 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004228
Benjamin Kramer5733e352015-07-18 17:09:36 +00004229 auto Children = Sub->children();
4230 if (Children.begin() != Children.end()) {
Aaron Ballmanff924b02013-11-18 20:11:50 +00004231 OS << "({ ... ; ";
4232 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4233 OS << " })\n";
4234 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004235 }
4236 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004237 // special printing for comma expressions.
4238 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4239 if (B->getOpcode() == BO_Comma) {
4240 OS << "... , ";
4241 Helper.handledStmt(B->getRHS(),OS);
4242 OS << '\n';
4243 return;
4244 }
4245 }
4246 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004247
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004248 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004249 OS << " (OperatorCall)";
Ted Kremenek0ffba932011-12-21 19:32:38 +00004250 }
4251 else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004252 OS << " (BindTemporary)";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004253 }
Ted Kremenek1a7648b2011-12-21 19:39:59 +00004254 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4255 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4256 }
Ted Kremenek0ffba932011-12-21 19:32:38 +00004257 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4258 OS << " (" << CE->getStmtClassName() << ", "
4259 << CE->getCastKindName()
4260 << ", " << CE->getType().getAsString()
4261 << ")";
4262 }
Mike Stump31feda52009-07-17 01:31:16 +00004263
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004264 // Expressions need a newline.
4265 if (isa<Expr>(S))
4266 OS << '\n';
Ted Kremenek0f5d8bc2010-08-31 18:47:37 +00004267
David Blaikie00be69a2013-02-23 00:29:34 +00004268 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4269 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004270 if (I->isBaseInitializer())
4271 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004272 else if (I->isDelegatingInitializer())
4273 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004274 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004275
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004276 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004277 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004278 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004279 OS << ")";
4280
4281 if (I->isBaseInitializer())
4282 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004283 else if (I->isDelegatingInitializer())
4284 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004285 else OS << " (Member initializer)\n";
4286
David Blaikie00be69a2013-02-23 00:29:34 +00004287 } else if (Optional<CFGAutomaticObjDtor> DE =
4288 E.getAs<CFGAutomaticObjDtor>()) {
4289 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004290 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004291
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004292 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004293 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4294 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004295 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004296
4297 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4298 OS << " (Implicit destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004299
Jordan Rosec9176072014-01-13 17:59:19 +00004300 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4301 OS << "CFGNewAllocator(";
4302 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4303 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4304 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004305 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4306 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4307 if (!RD)
4308 return;
4309 CXXDeleteExpr *DelExpr =
4310 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004311 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004312 OS << "->~" << RD->getName().str() << "()";
4313 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004314 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4315 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004316 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004317 OS << " (Base object destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004318
David Blaikie00be69a2013-02-23 00:29:34 +00004319 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4320 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004321 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004322 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004323 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004324 OS << " (Member object destructor)\n";
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004325
David Blaikie00be69a2013-02-23 00:29:34 +00004326 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4327 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004328 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004329 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004330 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004331 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004332}
Mike Stump31feda52009-07-17 01:31:16 +00004333
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004334static void print_block(raw_ostream &OS, const CFG* cfg,
4335 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004336 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004337 bool ShowColors) {
Mike Stump31feda52009-07-17 01:31:16 +00004338
Aaron Ballmanff924b02013-11-18 20:11:50 +00004339 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004340
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004341 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004342 if (ShowColors)
4343 OS.changeColor(raw_ostream::YELLOW, true);
4344
4345 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004346
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004347 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004348 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004349 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004350 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004351 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004352 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004353 else if (B.hasNoReturnElement())
4354 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004355 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004356 OS << "]\n";
4357
4358 if (ShowColors)
4359 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004360
Ted Kremenek71eca012007-08-29 23:20:49 +00004361 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004362 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004363
4364 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004365 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004366
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004367 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004368 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004369 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004370 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004371 if (C->getLHS())
4372 C->getLHS()->printPretty(OS, &Helper,
4373 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004374 if (C->getRHS()) {
4375 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004376 C->getRHS()->printPretty(OS, &Helper,
4377 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004378 }
Mike Stump92244b02010-01-19 22:00:14 +00004379 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004380 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004381 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004382 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004383 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004384 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004385 0);
4386 else
4387 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004388 OS << ")";
4389
4390 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004391 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004392
Ted Kremenek71eca012007-08-29 23:20:49 +00004393 OS << ":\n";
4394 }
Mike Stump31feda52009-07-17 01:31:16 +00004395
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004396 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004397 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004398
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004399 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4400 I != E ; ++I, ++j ) {
Mike Stump31feda52009-07-17 01:31:16 +00004401
Ted Kremenek71eca012007-08-29 23:20:49 +00004402 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004403 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004404 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004405
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004406 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004407
Aaron Ballmanff924b02013-11-18 20:11:50 +00004408 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004409
Ted Kremenek72be32a2011-12-22 23:33:52 +00004410 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004411 }
Mike Stump31feda52009-07-17 01:31:16 +00004412
Ted Kremenek71eca012007-08-29 23:20:49 +00004413 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004414 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004415 if (ShowColors)
4416 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004417
Ted Kremenek72be32a2011-12-22 23:33:52 +00004418 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004419
Aaron Ballmanff924b02013-11-18 20:11:50 +00004420 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004421
Aaron Ballmanff924b02013-11-18 20:11:50 +00004422 PrintingPolicy PP(Helper.getLangOpts());
4423 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004424 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004425 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004426
4427 if (ShowColors)
4428 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004429 }
Mike Stump31feda52009-07-17 01:31:16 +00004430
Ted Kremenek71eca012007-08-29 23:20:49 +00004431 if (print_edges) {
4432 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004433 if (!B.pred_empty()) {
4434 const raw_ostream::Colors Color = raw_ostream::BLUE;
4435 if (ShowColors)
4436 OS.changeColor(Color);
4437 OS << " Preds " ;
4438 if (ShowColors)
4439 OS.resetColor();
4440 OS << '(' << B.pred_size() << "):";
4441 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004442
Ted Kremenek72be32a2011-12-22 23:33:52 +00004443 if (ShowColors)
4444 OS.changeColor(Color);
4445
4446 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4447 I != E; ++I, ++i) {
Mike Stump31feda52009-07-17 01:31:16 +00004448
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004449 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004450 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004451
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004452 CFGBlock *B = *I;
4453 bool Reachable = true;
4454 if (!B) {
4455 Reachable = false;
4456 B = I->getPossiblyUnreachableBlock();
4457 }
4458
4459 OS << " B" << B->getBlockID();
4460 if (!Reachable)
4461 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004462 }
4463
4464 if (ShowColors)
4465 OS.resetColor();
4466
4467 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004468 }
Mike Stump31feda52009-07-17 01:31:16 +00004469
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004470 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004471 if (!B.succ_empty()) {
4472 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4473 if (ShowColors)
4474 OS.changeColor(Color);
4475 OS << " Succs ";
4476 if (ShowColors)
4477 OS.resetColor();
4478 OS << '(' << B.succ_size() << "):";
4479 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004480
Ted Kremenek72be32a2011-12-22 23:33:52 +00004481 if (ShowColors)
4482 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004483
Ted Kremenek72be32a2011-12-22 23:33:52 +00004484 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4485 I != E; ++I, ++i) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004486
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004487 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004488 OS << "\n ";
4489
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004490 CFGBlock *B = *I;
4491
4492 bool Reachable = true;
4493 if (!B) {
4494 Reachable = false;
4495 B = I->getPossiblyUnreachableBlock();
4496 }
4497
4498 if (B) {
4499 OS << " B" << B->getBlockID();
4500 if (!Reachable)
4501 OS << "(Unreachable)";
4502 }
4503 else {
4504 OS << " NULL";
4505 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004506 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004507
Ted Kremenek72be32a2011-12-22 23:33:52 +00004508 if (ShowColors)
4509 OS.resetColor();
4510 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004511 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004512 }
Mike Stump31feda52009-07-17 01:31:16 +00004513}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004514
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004515
4516/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004517void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4518 print(llvm::errs(), LO, ShowColors);
4519}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004520
4521/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004522void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004523 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004524
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004525 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004526 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004527
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004528 // Iterate through the CFGBlocks and print them one by one.
4529 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4530 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004531 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004532 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004533
Aaron Ballmanff924b02013-11-18 20:11:50 +00004534 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004535 }
Mike Stump31feda52009-07-17 01:31:16 +00004536
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004537 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004538 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004539 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004540 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004541}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004542
4543/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004544void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4545 bool ShowColors) const {
4546 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004547}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004548
Yaron Kerencdae9412016-01-29 19:38:18 +00004549LLVM_DUMP_METHOD void CFGBlock::dump() const {
Anna Zaksa6fea132014-06-13 23:47:38 +00004550 dump(getParent(), LangOptions(), false);
4551}
4552
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004553/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4554/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004555void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004556 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004557 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004558 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004559 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004560}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004561
Ted Kremenek15647632008-01-30 23:02:42 +00004562/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004563void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004564 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004565 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004566 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004567}
4568
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004569Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004570 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004571 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004572 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004573
Craig Topper25542942014-05-20 04:30:07 +00004574 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004575
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004576 switch (Terminator->getStmtClass()) {
4577 default:
4578 break;
Mike Stump31feda52009-07-17 01:31:16 +00004579
Jordan Rosecf10ea82013-06-06 21:53:45 +00004580 case Stmt::CXXForRangeStmtClass:
4581 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4582 break;
4583
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004584 case Stmt::ForStmtClass:
4585 E = cast<ForStmt>(Terminator)->getCond();
4586 break;
Mike Stump31feda52009-07-17 01:31:16 +00004587
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004588 case Stmt::WhileStmtClass:
4589 E = cast<WhileStmt>(Terminator)->getCond();
4590 break;
Mike Stump31feda52009-07-17 01:31:16 +00004591
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004592 case Stmt::DoStmtClass:
4593 E = cast<DoStmt>(Terminator)->getCond();
4594 break;
Mike Stump31feda52009-07-17 01:31:16 +00004595
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004596 case Stmt::IfStmtClass:
4597 E = cast<IfStmt>(Terminator)->getCond();
4598 break;
Mike Stump31feda52009-07-17 01:31:16 +00004599
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004600 case Stmt::ChooseExprClass:
4601 E = cast<ChooseExpr>(Terminator)->getCond();
4602 break;
Mike Stump31feda52009-07-17 01:31:16 +00004603
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004604 case Stmt::IndirectGotoStmtClass:
4605 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4606 break;
Mike Stump31feda52009-07-17 01:31:16 +00004607
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004608 case Stmt::SwitchStmtClass:
4609 E = cast<SwitchStmt>(Terminator)->getCond();
4610 break;
Mike Stump31feda52009-07-17 01:31:16 +00004611
John McCallc07a0c72011-02-17 10:25:35 +00004612 case Stmt::BinaryConditionalOperatorClass:
4613 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4614 break;
4615
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004616 case Stmt::ConditionalOperatorClass:
4617 E = cast<ConditionalOperator>(Terminator)->getCond();
4618 break;
Mike Stump31feda52009-07-17 01:31:16 +00004619
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004620 case Stmt::BinaryOperatorClass: // '&&' and '||'
4621 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004622 break;
Mike Stump31feda52009-07-17 01:31:16 +00004623
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004624 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00004625 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004626 }
Mike Stump31feda52009-07-17 01:31:16 +00004627
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004628 if (!StripParens)
4629 return E;
4630
Craig Topper25542942014-05-20 04:30:07 +00004631 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004632}
4633
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004634//===----------------------------------------------------------------------===//
4635// CFG Graphviz Visualization
4636//===----------------------------------------------------------------------===//
4637
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004638
4639#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00004640static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004641#endif
4642
Chris Lattnerc61089a2009-06-30 01:26:17 +00004643void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004644#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00004645 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004646 GraphHelper = &H;
4647 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00004648 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004649#endif
4650}
4651
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004652namespace llvm {
4653template<>
4654struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Tobias Grosser9fc223a2009-11-30 14:16:05 +00004655
4656 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4657
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004658 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004659
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004660#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004661 std::string OutSStr;
4662 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004663 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004664 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004665
4666 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4667
4668 // Process string output to make it nicer...
4669 for (unsigned i = 0; i != OutStr.length(); ++i)
4670 if (OutStr[i] == '\n') { // Left justify
4671 OutStr[i] = '\\';
4672 OutStr.insert(OutStr.begin()+i+1, 'l');
4673 }
Mike Stump31feda52009-07-17 01:31:16 +00004674
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004675 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004676#else
4677 return "";
4678#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004679 }
4680};
4681} // end namespace llvm