blob: b2fdd27879853e2b999702eb37c48922de4dac45 [file] [log] [blame]
Ted Kremenek6f400242012-07-14 05:04:01 +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
Ted Kremenek7c58d352011-03-10 01:14:11 +000042class CFGBuilder;
43
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000044/// The CFG builder uses a recursive algorithm to build the CFG. When
45/// we process an expression, sometimes we know that we must add the
46/// subexpressions as block-level expressions. For example:
47///
48/// exp1 || exp2
49///
50/// When processing the '||' expression, we know that exp1 and exp2
51/// need to be added as block-level expressions, even though they
52/// might not normally need to be. AddStmtChoice records this
53/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then
54/// the builder has an option not to add a subexpression as a
55/// block-level expression.
56///
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000057class AddStmtChoice {
58public:
Ted Kremenek8219b822010-12-16 07:46:53 +000059 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 };
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +000060
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000061 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {}
Ted Kremenek5d2bb1b2010-03-02 21:43:54 +000062
Ted Kremenek7c58d352011-03-10 01:14:11 +000063 bool alwaysAdd(CFGBuilder &builder,
64 const Stmt *stmt) const;
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000065
66 /// Return a copy of this object, except with the 'always-add' bit
67 /// set as specified.
68 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const {
Ted Kremenek7c58d352011-03-10 01:14:11 +000069 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000070 }
71
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000072private:
Zhanyong Wanb5d11c12010-11-24 03:28:53 +000073 Kind kind;
Ted Kremenek4cad5fc2009-12-16 03:18:58 +000074};
Mike Stump31feda52009-07-17 01:31:16 +000075
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +000076/// LocalScope - Node in tree of local scopes created for C++ implicit
77/// destructor calls generation. It contains list of automatic variables
78/// declared in the scope and link to position in previous scope this scope
79/// began in.
80///
81/// The process of creating local scopes is as follows:
82/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null),
83/// - Before processing statements in scope (e.g. CompoundStmt) create
84/// LocalScope object using CFGBuilder::ScopePos as link to previous scope
85/// and set CFGBuilder::ScopePos to the end of new scope,
Marcin Swiderskie9862ce2010-09-30 22:42:32 +000086/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +000087/// at this VarDecl,
88/// - For every normal (without jump) end of scope add to CFGBlock destructors
89/// for objects in the current scope,
90/// - For every jump add to CFGBlock destructors for objects
91/// between CFGBuilder::ScopePos and local scope position saved for jump
92/// target. Thanks to C++ restrictions on goto jumps we can be sure that
93/// jump target position will be on the path to root from CFGBuilder::ScopePos
94/// (adding any variable that doesn't need constructor to be called to
95/// LocalScope can break this assumption),
96///
97class LocalScope {
98public:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +000099 typedef BumpVector<VarDecl*> AutomaticVarsTy;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000100
101 /// const_iterator - Iterates local scope backwards and jumps to previous
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000102 /// scope on reaching the beginning of currently iterated scope.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000103 class const_iterator {
104 const LocalScope* Scope;
105
106 /// VarIter is guaranteed to be greater then 0 for every valid iterator.
107 /// Invalid iterator (with null Scope) has VarIter equal to 0.
108 unsigned VarIter;
109
110 public:
111 /// Create invalid iterator. Dereferencing invalid iterator is not allowed.
112 /// Incrementing invalid iterator is allowed and will result in invalid
113 /// iterator.
114 const_iterator()
Craig Topper25542942014-05-20 04:30:07 +0000115 : Scope(nullptr), VarIter(0) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000116
117 /// Create valid iterator. In case when S.Prev is an invalid iterator and
118 /// I is equal to 0, this will create invalid iterator.
119 const_iterator(const LocalScope& S, unsigned I)
120 : Scope(&S), VarIter(I) {
121 // Iterator to "end" of scope is not allowed. Handle it by going up
122 // in scopes tree possibly up to invalid iterator in the root.
123 if (VarIter == 0 && Scope)
124 *this = Scope->Prev;
125 }
126
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000127 VarDecl *const* operator->() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000128 assert (Scope && "Dereferencing invalid iterator is not allowed");
129 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
130 return &Scope->Vars[VarIter - 1];
131 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000132 VarDecl *operator*() const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000133 return *this->operator->();
134 }
135
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000136 const_iterator &operator++() {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000137 if (!Scope)
138 return *this;
139
140 assert (VarIter != 0 && "Iterator has invalid value of VarIter member");
141 --VarIter;
142 if (VarIter == 0)
143 *this = Scope->Prev;
144 return *this;
145 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000146 const_iterator operator++(int) {
147 const_iterator P = *this;
148 ++*this;
149 return P;
150 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000151
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000152 bool operator==(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000153 return Scope == rhs.Scope && VarIter == rhs.VarIter;
154 }
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000155 bool operator!=(const const_iterator &rhs) const {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000156 return !(*this == rhs);
157 }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000158
Aaron Ballman67347662015-02-15 22:00:28 +0000159 explicit operator bool() const {
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000160 return *this != const_iterator();
161 }
162
163 int distance(const_iterator L);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000164 };
165
166 friend class const_iterator;
167
168private:
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000169 BumpVectorContext ctx;
170
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000171 /// Automatic variables in order of declaration.
172 AutomaticVarsTy Vars;
173 /// Iterator to variable in previous scope that was declared just before
174 /// begin of this scope.
175 const_iterator Prev;
176
177public:
178 /// Constructs empty scope linked to previous scope in specified place.
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000179 LocalScope(BumpVectorContext &ctx, const_iterator P)
180 : ctx(ctx), Vars(ctx, 4), Prev(P) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000181
182 /// Begin of scope in direction of CFG building (backwards).
183 const_iterator begin() const { return const_iterator(*this, Vars.size()); }
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000184
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000185 void addVar(VarDecl *VD) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +0000186 Vars.push_back(VD, ctx);
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000187 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000188};
189
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000190/// distance - Calculates distance from this to L. L must be reachable from this
191/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t.
192/// number of scopes between this and L.
193int LocalScope::const_iterator::distance(LocalScope::const_iterator L) {
194 int D = 0;
195 const_iterator F = *this;
196 while (F.Scope != L.Scope) {
Ted Kremenek50aa2d42011-08-12 14:41:23 +0000197 assert (F != const_iterator()
198 && "L iterator is not reachable from F iterator.");
Marcin Swiderskie9862ce2010-09-30 22:42:32 +0000199 D += F.VarIter;
200 F = F.Scope->Prev;
201 }
202 D += F.VarIter - L.VarIter;
203 return D;
204}
205
Jonathan Roelofs99bdd982015-05-19 18:51:56 +0000206/// Structure for specifying position in CFG during its build process. It
207/// consists of CFGBlock that specifies position in CFG and
208/// LocalScope::const_iterator that specifies position in LocalScope graph.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000209struct BlockScopePosPair {
Craig Topper25542942014-05-20 04:30:07 +0000210 BlockScopePosPair() : block(nullptr) {}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000211 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos)
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000212 : block(b), scopePosition(scopePos) {}
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000213
Ted Kremenekef81e9e2011-01-07 19:37:16 +0000214 CFGBlock *block;
215 LocalScope::const_iterator scopePosition;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000216};
217
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000218/// TryResult - a class representing a variant over the values
219/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool,
220/// and is used by the CFGBuilder to decide if a branch condition
221/// can be decided up front during CFG construction.
222class TryResult {
223 int X;
224public:
225 TryResult(bool b) : X(b ? 1 : 0) {}
226 TryResult() : X(-1) {}
227
228 bool isTrue() const { return X == 1; }
229 bool isFalse() const { return X == 0; }
230 bool isKnown() const { return X >= 0; }
231 void negate() {
232 assert(isKnown());
233 X ^= 0x1;
234 }
235};
236
Manuel Klimekdeb02622014-08-08 07:37:13 +0000237TryResult bothKnownTrue(TryResult R1, TryResult R2) {
238 if (!R1.isKnown() || !R2.isKnown())
239 return TryResult();
240 return TryResult(R1.isTrue() && R2.isTrue());
241}
242
Ted Kremenek8ae67872013-02-05 22:00:19 +0000243class reverse_children {
244 llvm::SmallVector<Stmt *, 12> childrenBuf;
245 ArrayRef<Stmt*> children;
246public:
247 reverse_children(Stmt *S);
248
249 typedef ArrayRef<Stmt*>::reverse_iterator iterator;
250 iterator begin() const { return children.rbegin(); }
251 iterator end() const { return children.rend(); }
252};
253
254
255reverse_children::reverse_children(Stmt *S) {
256 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
257 children = CE->getRawSubExprs();
258 return;
259 }
260 switch (S->getStmtClass()) {
Ted Kremenek7d86b9c2013-02-05 22:03:14 +0000261 // Note: Fill in this switch with more cases we want to optimize.
Ted Kremenek8ae67872013-02-05 22:00:19 +0000262 case Stmt::InitListExprClass: {
263 InitListExpr *IE = cast<InitListExpr>(S);
264 children = llvm::makeArrayRef(reinterpret_cast<Stmt**>(IE->getInits()),
265 IE->getNumInits());
266 return;
267 }
268 default:
269 break;
270 }
271
272 // Default case for all other statements.
273 for (Stmt::child_range I = S->children(); I; ++I) {
274 childrenBuf.push_back(*I);
275 }
276
277 // This needs to be done *after* childrenBuf has been populated.
278 children = childrenBuf;
279}
280
Ted Kremenekbe9b33b2008-08-04 22:51:42 +0000281/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000282/// The builder is stateful: an instance of the builder should be used to only
283/// construct a single CFG.
284///
285/// Example usage:
286///
287/// CFGBuilder builder;
288/// CFG* cfg = builder.BuildAST(stmt1);
289///
Mike Stump31feda52009-07-17 01:31:16 +0000290/// CFG construction is done via a recursive walk of an AST. We actually parse
291/// the AST in reverse order so that the successor of a basic block is
292/// constructed prior to its predecessor. This allows us to nicely capture
293/// implicit fall-throughs without extra basic blocks.
Ted Kremenek1b8ac852007-08-21 22:06:14 +0000294///
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000295class CFGBuilder {
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000296 typedef BlockScopePosPair JumpTarget;
297 typedef BlockScopePosPair JumpSource;
298
Mike Stump0d76d072009-07-20 23:24:15 +0000299 ASTContext *Context;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000300 std::unique_ptr<CFG> cfg;
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000301
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000302 CFGBlock *Block;
303 CFGBlock *Succ;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000304 JumpTarget ContinueJumpTarget;
305 JumpTarget BreakJumpTarget;
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000306 CFGBlock *SwitchTerminatedBlock;
307 CFGBlock *DefaultCaseBlock;
308 CFGBlock *TryTerminatedBlock;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000309
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000310 // Current position in local scope.
311 LocalScope::const_iterator ScopePos;
312
313 // LabelMap records the mapping from Label expressions to their jump targets.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000314 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000315 LabelMapTy LabelMap;
Mike Stump31feda52009-07-17 01:31:16 +0000316
317 // A list of blocks that end with a "goto" that must be backpatched to their
318 // resolved targets upon completion of CFG construction.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +0000319 typedef std::vector<JumpSource> BackpatchBlocksTy;
Ted Kremenek8a632182007-08-21 23:26:17 +0000320 BackpatchBlocksTy BackpatchBlocks;
Mike Stump31feda52009-07-17 01:31:16 +0000321
Ted Kremenekeda180e22007-08-28 19:26:49 +0000322 // A list of labels whose address has been taken (for indirect gotos).
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000323 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy;
Ted Kremenekeda180e22007-08-28 19:26:49 +0000324 LabelSetTy AddressTakenLabels;
Mike Stump31feda52009-07-17 01:31:16 +0000325
Zhongxing Xud38fb842010-09-16 03:28:18 +0000326 bool badCFG;
Ted Kremenekf9d82902011-03-10 01:14:05 +0000327 const CFG::BuildOptions &BuildOpts;
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000328
329 // State to track for building switch statements.
330 bool switchExclusivelyCovered;
Ted Kremenekbe528712011-03-04 01:03:41 +0000331 Expr::EvalResult *switchCond;
Ted Kremeneka099c592011-03-10 03:50:34 +0000332
333 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000334 const Stmt *lastLookup;
Zhongxing Xud38fb842010-09-16 03:28:18 +0000335
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000336 // Caches boolean evaluations of expressions to avoid multiple re-evaluations
337 // during construction of branches for chained logical operators.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000338 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy;
339 CachedBoolEvalsTy CachedBoolEvals;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000340
Mike Stump31feda52009-07-17 01:31:16 +0000341public:
Ted Kremenekf9d82902011-03-10 01:14:05 +0000342 explicit CFGBuilder(ASTContext *astContext,
343 const CFG::BuildOptions &buildOpts)
344 : Context(astContext), cfg(new CFG()), // crew a new CFG
Craig Topper25542942014-05-20 04:30:07 +0000345 Block(nullptr), Succ(nullptr),
346 SwitchTerminatedBlock(nullptr), DefaultCaseBlock(nullptr),
347 TryTerminatedBlock(nullptr), badCFG(false), BuildOpts(buildOpts),
348 switchExclusivelyCovered(false), switchCond(nullptr),
349 cachedEntry(nullptr), lastLookup(nullptr) {}
Mike Stump31feda52009-07-17 01:31:16 +0000350
Ted Kremenek9aae5132007-08-23 21:42:29 +0000351 // buildCFG - Used by external clients to construct the CFG.
David Blaikiee90195c2014-08-29 18:53:26 +0000352 std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *Statement);
Mike Stump31feda52009-07-17 01:31:16 +0000353
Ted Kremeneka099c592011-03-10 03:50:34 +0000354 bool alwaysAdd(const Stmt *stmt);
355
Ted Kremenek93668002009-07-17 22:18:43 +0000356private:
357 // Visitors to walk an AST and construct the CFG.
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000358 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
359 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000360 CFGBlock *VisitBreakStmt(BreakStmt *B);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000361 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000362 CFGBlock *VisitCaseStmt(CaseStmt *C);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000363 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000364 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
John McCallc07a0c72011-02-17 10:25:35 +0000365 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C,
366 AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000367 CFGBlock *VisitContinueStmt(ContinueStmt *C);
Ted Kremenek6f400242012-07-14 05:04:01 +0000368 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
369 AddStmtChoice asc);
370 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
371 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc);
Jordan Rosec9176072014-01-13 17:59:19 +0000372 CFGBlock *VisitCXXNewExpr(CXXNewExpr *DE, AddStmtChoice asc);
Jordan Rosed2f40792013-09-03 17:00:57 +0000373 CFGBlock *VisitCXXDeleteExpr(CXXDeleteExpr *DE, AddStmtChoice asc);
Ted Kremenek6f400242012-07-14 05:04:01 +0000374 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S);
375 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
376 AddStmtChoice asc);
377 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
378 AddStmtChoice asc);
379 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
380 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000381 CFGBlock *VisitDeclStmt(DeclStmt *DS);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000382 CFGBlock *VisitDeclSubExpr(DeclStmt *DS);
Ted Kremenek21822592009-07-17 18:20:32 +0000383 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
384 CFGBlock *VisitDoStmt(DoStmt *D);
Ted Kremenek6f400242012-07-14 05:04:01 +0000385 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, AddStmtChoice asc);
Ted Kremenek21822592009-07-17 18:20:32 +0000386 CFGBlock *VisitForStmt(ForStmt *F);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000387 CFGBlock *VisitGotoStmt(GotoStmt *G);
Ted Kremenek93668002009-07-17 22:18:43 +0000388 CFGBlock *VisitIfStmt(IfStmt *I);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +0000389 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000390 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
391 CFGBlock *VisitLabelStmt(LabelStmt *L);
Ted Kremenek6f400242012-07-14 05:04:01 +0000392 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc);
Ted Kremeneka16436f2012-07-14 05:04:06 +0000393 CFGBlock *VisitLogicalOperator(BinaryOperator *B);
Ted Kremenekb50e7162012-07-14 05:04:10 +0000394 std::pair<CFGBlock *, CFGBlock *> VisitLogicalOperator(BinaryOperator *B,
395 Stmt *Term,
396 CFGBlock *TrueBlock,
397 CFGBlock *FalseBlock);
Ted Kremenek5868ec62010-04-11 17:02:10 +0000398 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000399 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
400 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
401 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
402 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000403 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Ted Kremenek93668002009-07-17 22:18:43 +0000404 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
John McCallfe96e0b2011-11-06 09:01:30 +0000405 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E);
Ted Kremenek6f400242012-07-14 05:04:01 +0000406 CFGBlock *VisitReturnStmt(ReturnStmt *R);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000407 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000408 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek6f400242012-07-14 05:04:01 +0000409 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
410 AddStmtChoice asc);
Zhanyong Wan6dace612010-11-22 08:45:56 +0000411 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc);
Ted Kremenek93668002009-07-17 22:18:43 +0000412 CFGBlock *VisitWhileStmt(WhileStmt *W);
Mike Stump48871a22009-07-17 01:04:31 +0000413
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000414 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
415 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000416 CFGBlock *VisitChildren(Stmt *S);
Ted Kremeneke2499842012-04-12 20:03:44 +0000417 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc);
Mike Stump48871a22009-07-17 01:04:31 +0000418
Manuel Klimekb5616c92014-08-07 10:42:17 +0000419 /// When creating the CFG for temporary destructors, we want to mirror the
420 /// branch structure of the corresponding constructor calls.
421 /// Thus, while visiting a statement for temporary destructors, we keep a
422 /// context to keep track of the following information:
423 /// - whether a subexpression is executed unconditionally
424 /// - if a subexpression is executed conditionally, the first
425 /// CXXBindTemporaryExpr we encounter in that subexpression (which
426 /// corresponds to the last temporary destructor we have to call for this
427 /// subexpression) and the CFG block at that point (which will become the
428 /// successor block when inserting the decision point).
429 ///
430 /// That way, we can build the branch structure for temporary destructors as
431 /// follows:
432 /// 1. If a subexpression is executed unconditionally, we add the temporary
433 /// destructor calls to the current block.
434 /// 2. If a subexpression is executed conditionally, when we encounter a
435 /// CXXBindTemporaryExpr:
436 /// a) If it is the first temporary destructor call in the subexpression,
437 /// we remember the CXXBindTemporaryExpr and the current block in the
438 /// TempDtorContext; we start a new block, and insert the temporary
439 /// destructor call.
440 /// b) Otherwise, add the temporary destructor call to the current block.
441 /// 3. When we finished visiting a conditionally executed subexpression,
442 /// and we found at least one temporary constructor during the visitation
443 /// (2.a has executed), we insert a decision block that uses the
444 /// CXXBindTemporaryExpr as terminator, and branches to the current block
445 /// if the CXXBindTemporaryExpr was marked executed, and otherwise
446 /// branches to the stored successor.
447 struct TempDtorContext {
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000448 TempDtorContext()
449 : IsConditional(false), KnownExecuted(true), Succ(nullptr),
450 TerminatorExpr(nullptr) {}
Manuel Klimekdeb02622014-08-08 07:37:13 +0000451
452 TempDtorContext(TryResult KnownExecuted)
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000453 : IsConditional(true), KnownExecuted(KnownExecuted), Succ(nullptr),
454 TerminatorExpr(nullptr) {}
Manuel Klimekb5616c92014-08-07 10:42:17 +0000455
456 /// Returns whether we need to start a new branch for a temporary destructor
457 /// call. This is the case when the the temporary destructor is
458 /// conditionally executed, and it is the first one we encounter while
459 /// visiting a subexpression - other temporary destructors at the same level
460 /// will be added to the same block and are executed under the same
461 /// condition.
462 bool needsTempDtorBranch() const {
463 return IsConditional && !TerminatorExpr;
464 }
465
466 /// Remember the successor S of a temporary destructor decision branch for
467 /// the corresponding CXXBindTemporaryExpr E.
468 void setDecisionPoint(CFGBlock *S, CXXBindTemporaryExpr *E) {
469 Succ = S;
470 TerminatorExpr = E;
471 }
472
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000473 const bool IsConditional;
Manuel Klimekdeb02622014-08-08 07:37:13 +0000474 const TryResult KnownExecuted;
NAKAMURA Takumi6b0fe342014-08-08 09:51:07 +0000475 CFGBlock *Succ;
476 CXXBindTemporaryExpr *TerminatorExpr;
Manuel Klimekb5616c92014-08-07 10:42:17 +0000477 };
478
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000479 // Visitors to walk an AST and generate destructors of temporaries in
480 // full expression.
Manuel Klimekb5616c92014-08-07 10:42:17 +0000481 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
482 TempDtorContext &Context);
483 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E, TempDtorContext &Context);
484 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E,
485 TempDtorContext &Context);
486 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(
487 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context);
488 CFGBlock *VisitConditionalOperatorForTemporaryDtors(
489 AbstractConditionalOperator *E, bool BindToTemporary,
490 TempDtorContext &Context);
491 void InsertTempDtorDecisionBlock(const TempDtorContext &Context,
492 CFGBlock *FalseSucc = nullptr);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000493
Ted Kremenek6065ef62008-04-28 18:00:46 +0000494 // NYS == Not Yet Supported
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000495 CFGBlock *NYS() {
Ted Kremenekb64d1832008-03-13 03:04:22 +0000496 badCFG = true;
497 return Block;
498 }
Mike Stump31feda52009-07-17 01:31:16 +0000499
Ted Kremenek93668002009-07-17 22:18:43 +0000500 void autoCreateBlock() { if (!Block) Block = createBlock(); }
501 CFGBlock *createBlock(bool add_successor = true);
Chandler Carrutha70991b2011-09-13 09:13:49 +0000502 CFGBlock *createNoReturnBlock();
Zhongxing Xu33dfc072010-09-06 07:32:31 +0000503
Zhongxing Xuea9fcff2010-06-03 06:43:23 +0000504 CFGBlock *addStmt(Stmt *S) {
505 return Visit(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek4cad5fc2009-12-16 03:18:58 +0000506 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000507 CFGBlock *addInitializer(CXXCtorInitializer *I);
Zhongxing Xu6d372f72010-10-01 03:22:39 +0000508 void addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000509 LocalScope::const_iterator E, Stmt *S);
Marcin Swiderski20b88732010-10-05 05:37:00 +0000510 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD);
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000511
Marcin Swiderski5e415732010-09-30 23:05:00 +0000512 // Local scopes creation.
513 LocalScope* createOrReuseLocalScope(LocalScope* Scope);
514
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000515 void addLocalScopeForStmt(Stmt *S);
Craig Topper25542942014-05-20 04:30:07 +0000516 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS,
517 LocalScope* Scope = nullptr);
518 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = nullptr);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000519
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000520 void addLocalScopeAndDtors(Stmt *S);
Marcin Swiderski5e415732010-09-30 23:05:00 +0000521
522 // Interface to CFGBlock - adding CFGElements.
Ted Kremenek37881932011-04-04 23:29:12 +0000523 void appendStmt(CFGBlock *B, const Stmt *S) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000524 if (alwaysAdd(S) && cachedEntry)
Ted Kremeneka099c592011-03-10 03:50:34 +0000525 cachedEntry->second = B;
Ted Kremeneka099c592011-03-10 03:50:34 +0000526
Jordy Rose17347372011-06-10 08:49:37 +0000527 // All block-level expressions should have already been IgnoreParens()ed.
528 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S);
Ted Kremenek37881932011-04-04 23:29:12 +0000529 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000530 }
Alexis Hunt1d792652011-01-08 20:30:50 +0000531 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000532 B->appendInitializer(I, cfg->getBumpVectorContext());
533 }
Jordan Rosec9176072014-01-13 17:59:19 +0000534 void appendNewAllocator(CFGBlock *B, CXXNewExpr *NE) {
535 B->appendNewAllocator(NE, cfg->getBumpVectorContext());
536 }
Marcin Swiderski20b88732010-10-05 05:37:00 +0000537 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) {
538 B->appendBaseDtor(BS, cfg->getBumpVectorContext());
539 }
540 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) {
541 B->appendMemberDtor(FD, cfg->getBumpVectorContext());
542 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +0000543 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) {
544 B->appendTemporaryDtor(E, cfg->getBumpVectorContext());
545 }
Chandler Carruthad747252011-09-13 06:09:01 +0000546 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) {
547 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext());
548 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +0000549
Jordan Rosed2f40792013-09-03 17:00:57 +0000550 void appendDeleteDtor(CFGBlock *B, CXXRecordDecl *RD, CXXDeleteExpr *DE) {
551 B->appendDeleteDtor(RD, DE, cfg->getBumpVectorContext());
552 }
553
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000554 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +0000555 LocalScope::const_iterator B, LocalScope::const_iterator E);
556
Ted Kremenek4b6fee62014-02-27 00:24:00 +0000557 void addSuccessor(CFGBlock *B, CFGBlock *S, bool IsReachable = true) {
558 B->addSuccessor(CFGBlock::AdjacentBlock(S, IsReachable),
559 cfg->getBumpVectorContext());
560 }
561
562 /// Add a reachable successor to a block, with the alternate variant that is
563 /// unreachable.
564 void addSuccessor(CFGBlock *B, CFGBlock *ReachableBlock, CFGBlock *AltBlock) {
565 B->addSuccessor(CFGBlock::AdjacentBlock(ReachableBlock, AltBlock),
566 cfg->getBumpVectorContext());
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000567 }
Mike Stump11289f42009-09-09 15:08:12 +0000568
Richard Trieuf935b562014-04-05 05:17:01 +0000569 /// \brief Find a relational comparison with an expression evaluating to a
570 /// boolean and a constant other than 0 and 1.
571 /// e.g. if ((x < y) == 10)
572 TryResult checkIncorrectRelationalOperator(const BinaryOperator *B) {
573 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
574 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
575
576 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
577 const Expr *BoolExpr = RHSExpr;
578 bool IntFirst = true;
579 if (!IntLiteral) {
580 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
581 BoolExpr = LHSExpr;
582 IntFirst = false;
583 }
584
585 if (!IntLiteral || !BoolExpr->isKnownToHaveBooleanValue())
586 return TryResult();
587
588 llvm::APInt IntValue = IntLiteral->getValue();
589 if ((IntValue == 1) || (IntValue == 0))
590 return TryResult();
591
592 bool IntLarger = IntLiteral->getType()->isUnsignedIntegerType() ||
593 !IntValue.isNegative();
594
595 BinaryOperatorKind Bok = B->getOpcode();
596 if (Bok == BO_GT || Bok == BO_GE) {
597 // Always true for 10 > bool and bool > -1
598 // Always false for -1 > bool and bool > 10
599 return TryResult(IntFirst == IntLarger);
600 } else {
601 // Always true for -1 < bool and bool < 10
602 // Always false for 10 < bool and bool < -1
603 return TryResult(IntFirst != IntLarger);
604 }
605 }
606
Jordan Rose7afd71e2014-05-20 17:31:11 +0000607 /// Find an incorrect equality comparison. Either with an expression
608 /// evaluating to a boolean and a constant other than 0 and 1.
609 /// e.g. if (!x == 10) or a bitwise and/or operation that always evaluates to
610 /// true/false e.q. (x & 8) == 4.
Richard Trieuf935b562014-04-05 05:17:01 +0000611 TryResult checkIncorrectEqualityOperator(const BinaryOperator *B) {
612 const Expr *LHSExpr = B->getLHS()->IgnoreParens();
613 const Expr *RHSExpr = B->getRHS()->IgnoreParens();
614
615 const IntegerLiteral *IntLiteral = dyn_cast<IntegerLiteral>(LHSExpr);
616 const Expr *BoolExpr = RHSExpr;
617
618 if (!IntLiteral) {
619 IntLiteral = dyn_cast<IntegerLiteral>(RHSExpr);
620 BoolExpr = LHSExpr;
621 }
622
Jordan Rose7afd71e2014-05-20 17:31:11 +0000623 if (!IntLiteral)
Richard Trieuf935b562014-04-05 05:17:01 +0000624 return TryResult();
625
Jordan Rose7afd71e2014-05-20 17:31:11 +0000626 const BinaryOperator *BitOp = dyn_cast<BinaryOperator>(BoolExpr);
627 if (BitOp && (BitOp->getOpcode() == BO_And ||
628 BitOp->getOpcode() == BO_Or)) {
629 const Expr *LHSExpr2 = BitOp->getLHS()->IgnoreParens();
630 const Expr *RHSExpr2 = BitOp->getRHS()->IgnoreParens();
631
632 const IntegerLiteral *IntLiteral2 = dyn_cast<IntegerLiteral>(LHSExpr2);
633
634 if (!IntLiteral2)
635 IntLiteral2 = dyn_cast<IntegerLiteral>(RHSExpr2);
636
637 if (!IntLiteral2)
638 return TryResult();
639
640 llvm::APInt L1 = IntLiteral->getValue();
641 llvm::APInt L2 = IntLiteral2->getValue();
642 if ((BitOp->getOpcode() == BO_And && (L2 & L1) != L1) ||
643 (BitOp->getOpcode() == BO_Or && (L2 | L1) != L1)) {
644 if (BuildOpts.Observer)
645 BuildOpts.Observer->compareBitwiseEquality(B,
646 B->getOpcode() != BO_EQ);
647 TryResult(B->getOpcode() != BO_EQ);
648 }
649 } else if (BoolExpr->isKnownToHaveBooleanValue()) {
650 llvm::APInt IntValue = IntLiteral->getValue();
651 if ((IntValue == 1) || (IntValue == 0)) {
652 return TryResult();
653 }
654 return TryResult(B->getOpcode() != BO_EQ);
Richard Trieuf935b562014-04-05 05:17:01 +0000655 }
656
Jordan Rose7afd71e2014-05-20 17:31:11 +0000657 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000658 }
659
660 TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
661 const llvm::APSInt &Value1,
662 const llvm::APSInt &Value2) {
663 assert(Value1.isSigned() == Value2.isSigned());
664 switch (Relation) {
665 default:
666 return TryResult();
667 case BO_EQ:
668 return TryResult(Value1 == Value2);
669 case BO_NE:
670 return TryResult(Value1 != Value2);
671 case BO_LT:
672 return TryResult(Value1 < Value2);
673 case BO_LE:
674 return TryResult(Value1 <= Value2);
675 case BO_GT:
676 return TryResult(Value1 > Value2);
677 case BO_GE:
678 return TryResult(Value1 >= Value2);
679 }
680 }
681
682 /// \brief Find a pair of comparison expressions with or without parentheses
683 /// with a shared variable and constants and a logical operator between them
684 /// that always evaluates to either true or false.
685 /// e.g. if (x != 3 || x != 4)
686 TryResult checkIncorrectLogicOperator(const BinaryOperator *B) {
687 assert(B->isLogicalOp());
688 const BinaryOperator *LHS =
689 dyn_cast<BinaryOperator>(B->getLHS()->IgnoreParens());
690 const BinaryOperator *RHS =
691 dyn_cast<BinaryOperator>(B->getRHS()->IgnoreParens());
692 if (!LHS || !RHS)
693 return TryResult();
694
695 if (!LHS->isComparisonOp() || !RHS->isComparisonOp())
696 return TryResult();
697
698 BinaryOperatorKind BO1 = LHS->getOpcode();
699 const DeclRefExpr *Decl1 =
700 dyn_cast<DeclRefExpr>(LHS->getLHS()->IgnoreParenImpCasts());
701 const IntegerLiteral *Literal1 =
702 dyn_cast<IntegerLiteral>(LHS->getRHS()->IgnoreParens());
703 if (!Decl1 && !Literal1) {
704 if (BO1 == BO_GT)
705 BO1 = BO_LT;
706 else if (BO1 == BO_GE)
707 BO1 = BO_LE;
708 else if (BO1 == BO_LT)
709 BO1 = BO_GT;
710 else if (BO1 == BO_LE)
711 BO1 = BO_GE;
712 Decl1 = dyn_cast<DeclRefExpr>(LHS->getRHS()->IgnoreParenImpCasts());
713 Literal1 = dyn_cast<IntegerLiteral>(LHS->getLHS()->IgnoreParens());
714 }
715
716 if (!Decl1 || !Literal1)
717 return TryResult();
718
719 BinaryOperatorKind BO2 = RHS->getOpcode();
720 const DeclRefExpr *Decl2 =
721 dyn_cast<DeclRefExpr>(RHS->getLHS()->IgnoreParenImpCasts());
722 const IntegerLiteral *Literal2 =
723 dyn_cast<IntegerLiteral>(RHS->getRHS()->IgnoreParens());
724 if (!Decl2 && !Literal2) {
725 if (BO2 == BO_GT)
726 BO2 = BO_LT;
727 else if (BO2 == BO_GE)
728 BO2 = BO_LE;
729 else if (BO2 == BO_LT)
730 BO2 = BO_GT;
731 else if (BO2 == BO_LE)
732 BO2 = BO_GE;
733 Decl2 = dyn_cast<DeclRefExpr>(RHS->getRHS()->IgnoreParenImpCasts());
734 Literal2 = dyn_cast<IntegerLiteral>(RHS->getLHS()->IgnoreParens());
735 }
736
737 if (!Decl2 || !Literal2)
738 return TryResult();
739
740 // Check that it is the same variable on both sides.
741 if (Decl1->getDecl() != Decl2->getDecl())
742 return TryResult();
743
744 llvm::APSInt L1, L2;
745
746 if (!Literal1->EvaluateAsInt(L1, *Context) ||
747 !Literal2->EvaluateAsInt(L2, *Context))
748 return TryResult();
749
750 // Can't compare signed with unsigned or with different bit width.
751 if (L1.isSigned() != L2.isSigned() || L1.getBitWidth() != L2.getBitWidth())
752 return TryResult();
753
754 // Values that will be used to determine if result of logical
755 // operator is always true/false
756 const llvm::APSInt Values[] = {
757 // Value less than both Value1 and Value2
758 llvm::APSInt::getMinValue(L1.getBitWidth(), L1.isUnsigned()),
759 // L1
760 L1,
761 // Value between Value1 and Value2
762 ((L1 < L2) ? L1 : L2) + llvm::APSInt(llvm::APInt(L1.getBitWidth(), 1),
763 L1.isUnsigned()),
764 // L2
765 L2,
766 // Value greater than both Value1 and Value2
767 llvm::APSInt::getMaxValue(L1.getBitWidth(), L1.isUnsigned()),
768 };
769
770 // Check whether expression is always true/false by evaluating the following
771 // * variable x is less than the smallest literal.
772 // * variable x is equal to the smallest literal.
773 // * Variable x is between smallest and largest literal.
774 // * Variable x is equal to the largest literal.
775 // * Variable x is greater than largest literal.
776 bool AlwaysTrue = true, AlwaysFalse = true;
777 for (unsigned int ValueIndex = 0;
778 ValueIndex < sizeof(Values) / sizeof(Values[0]);
779 ++ValueIndex) {
780 llvm::APSInt Value = Values[ValueIndex];
781 TryResult Res1, Res2;
782 Res1 = analyzeLogicOperatorCondition(BO1, Value, L1);
783 Res2 = analyzeLogicOperatorCondition(BO2, Value, L2);
784
785 if (!Res1.isKnown() || !Res2.isKnown())
786 return TryResult();
787
788 if (B->getOpcode() == BO_LAnd) {
789 AlwaysTrue &= (Res1.isTrue() && Res2.isTrue());
790 AlwaysFalse &= !(Res1.isTrue() && Res2.isTrue());
791 } else {
792 AlwaysTrue &= (Res1.isTrue() || Res2.isTrue());
793 AlwaysFalse &= !(Res1.isTrue() || Res2.isTrue());
794 }
795 }
796
797 if (AlwaysTrue || AlwaysFalse) {
798 if (BuildOpts.Observer)
799 BuildOpts.Observer->compareAlwaysTrue(B, AlwaysTrue);
800 return TryResult(AlwaysTrue);
801 }
802 return TryResult();
803 }
804
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000805 /// Try and evaluate an expression to an integer constant.
806 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) {
807 if (!BuildOpts.PruneTriviallyFalseEdges)
808 return false;
809 return !S->isTypeDependent() &&
Ted Kremenek352a7082011-04-04 20:30:58 +0000810 !S->isValueDependent() &&
Richard Smith7b553f12011-10-29 00:50:52 +0000811 S->EvaluateAsRValue(outResult, *Context);
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000812 }
Mike Stump11289f42009-09-09 15:08:12 +0000813
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000814 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
Mike Stump773582d2009-07-23 23:25:26 +0000815 /// if we can evaluate to a known value, otherwise return -1.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +0000816 TryResult tryEvaluateBool(Expr *S) {
Richard Smithfaa32a92011-10-14 20:22:00 +0000817 if (!BuildOpts.PruneTriviallyFalseEdges ||
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000818 S->isTypeDependent() || S->isValueDependent())
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000819 return TryResult();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000820
821 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) {
822 if (Bop->isLogicalOp()) {
823 // Check the cache first.
NAKAMURA Takumie9ca55e2012-03-25 06:30:37 +0000824 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S);
825 if (I != CachedBoolEvals.end())
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000826 return I->second; // already in map;
NAKAMURA Takumif0434b02012-03-25 06:30:32 +0000827
828 // Retrieve result at first, or the map might be updated.
829 TryResult Result = evaluateAsBooleanConditionNoCache(S);
830 CachedBoolEvals[S] = Result; // update or insert
831 return Result;
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000832 }
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000833 else {
834 switch (Bop->getOpcode()) {
835 default: break;
836 // For 'x & 0' and 'x * 0', we can determine that
837 // the value is always false.
838 case BO_Mul:
839 case BO_And: {
840 // If either operand is zero, we know the value
841 // must be false.
842 llvm::APSInt IntVal;
843 if (Bop->getLHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000844 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000845 return TryResult(false);
846 }
847 }
848 if (Bop->getRHS()->EvaluateAsInt(IntVal, *Context)) {
David Blaikie7a3cbb22015-03-09 02:02:07 +0000849 if (!IntVal.getBoolValue()) {
Ted Kremenek64fea5f2012-08-24 07:42:09 +0000850 return TryResult(false);
851 }
852 }
853 }
854 break;
855 }
856 }
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000857 }
858
859 return evaluateAsBooleanConditionNoCache(S);
860 }
861
862 /// \brief Evaluate as boolean \param E without using the cache.
863 TryResult evaluateAsBooleanConditionNoCache(Expr *E) {
864 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) {
865 if (Bop->isLogicalOp()) {
866 TryResult LHS = tryEvaluateBool(Bop->getLHS());
867 if (LHS.isKnown()) {
868 // We were able to evaluate the LHS, see if we can get away with not
869 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
870 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr))
871 return LHS.isTrue();
872
873 TryResult RHS = tryEvaluateBool(Bop->getRHS());
874 if (RHS.isKnown()) {
875 if (Bop->getOpcode() == BO_LOr)
876 return LHS.isTrue() || RHS.isTrue();
877 else
878 return LHS.isTrue() && RHS.isTrue();
879 }
880 } else {
881 TryResult RHS = tryEvaluateBool(Bop->getRHS());
882 if (RHS.isKnown()) {
883 // We can't evaluate the LHS; however, sometimes the result
884 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
885 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr))
886 return RHS.isTrue();
Richard Trieuf935b562014-04-05 05:17:01 +0000887 } else {
888 TryResult BopRes = checkIncorrectLogicOperator(Bop);
889 if (BopRes.isKnown())
890 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000891 }
892 }
893
894 return TryResult();
Richard Trieuf935b562014-04-05 05:17:01 +0000895 } else if (Bop->isEqualityOp()) {
896 TryResult BopRes = checkIncorrectEqualityOperator(Bop);
897 if (BopRes.isKnown())
898 return BopRes.isTrue();
899 } else if (Bop->isRelationalOp()) {
900 TryResult BopRes = checkIncorrectRelationalOperator(Bop);
901 if (BopRes.isKnown())
902 return BopRes.isTrue();
Argyrios Kyrtzidis5f172a32012-03-23 00:59:17 +0000903 }
904 }
905
906 bool Result;
907 if (E->EvaluateAsBooleanCondition(Result, *Context))
908 return Result;
909
910 return TryResult();
Mike Stump773582d2009-07-23 23:25:26 +0000911 }
Ted Kremenekeff9a7f2011-03-01 23:12:55 +0000912
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +0000913};
Mike Stump31feda52009-07-17 01:31:16 +0000914
Ted Kremeneka099c592011-03-10 03:50:34 +0000915inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder,
916 const Stmt *stmt) const {
917 return builder.alwaysAdd(stmt) || kind == AlwaysAdd;
918}
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000919
Ted Kremeneka099c592011-03-10 03:50:34 +0000920bool CFGBuilder::alwaysAdd(const Stmt *stmt) {
Ted Kremenek8b46c002011-07-19 14:18:43 +0000921 bool shouldAdd = BuildOpts.alwaysAdd(stmt);
922
Ted Kremeneka099c592011-03-10 03:50:34 +0000923 if (!BuildOpts.forcedBlkExprs)
Ted Kremenek8b46c002011-07-19 14:18:43 +0000924 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000925
926 if (lastLookup == stmt) {
927 if (cachedEntry) {
928 assert(cachedEntry->first == stmt);
929 return true;
930 }
Ted Kremenek8b46c002011-07-19 14:18:43 +0000931 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000932 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000933
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000934 lastLookup = stmt;
935
936 // Perform the lookup!
Ted Kremeneka099c592011-03-10 03:50:34 +0000937 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs;
938
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000939 if (!fb) {
940 // No need to update 'cachedEntry', since it will always be null.
Craig Topper25542942014-05-20 04:30:07 +0000941 assert(!cachedEntry);
Ted Kremenek8b46c002011-07-19 14:18:43 +0000942 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000943 }
Ted Kremeneka099c592011-03-10 03:50:34 +0000944
945 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt);
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000946 if (itr == fb->end()) {
Craig Topper25542942014-05-20 04:30:07 +0000947 cachedEntry = nullptr;
Ted Kremenek8b46c002011-07-19 14:18:43 +0000948 return shouldAdd;
Ted Kremenekdcc4c382011-03-23 21:33:21 +0000949 }
950
Ted Kremeneka099c592011-03-10 03:50:34 +0000951 cachedEntry = &*itr;
952 return true;
Ted Kremenek7c58d352011-03-10 01:14:11 +0000953}
954
Douglas Gregor4619e432008-12-05 23:32:09 +0000955// FIXME: Add support for dependent-sized array types in C++?
956// Does it even make sense to build a CFG for an uninstantiated template?
John McCall424cec92011-01-19 06:33:43 +0000957static const VariableArrayType *FindVA(const Type *t) {
958 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) {
959 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt))
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000960 if (vat->getSizeExpr())
961 return vat;
Mike Stump31feda52009-07-17 01:31:16 +0000962
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000963 t = vt->getElementType().getTypePtr();
964 }
Mike Stump31feda52009-07-17 01:31:16 +0000965
Craig Topper25542942014-05-20 04:30:07 +0000966 return nullptr;
Ted Kremenekd86d39c2008-09-26 22:58:57 +0000967}
Mike Stump31feda52009-07-17 01:31:16 +0000968
969/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
970/// arbitrary statement. Examples include a single expression or a function
971/// body (compound statement). The ownership of the returned CFG is
972/// transferred to the caller. If CFG construction fails, this method returns
973/// NULL.
David Blaikiee90195c2014-08-29 18:53:26 +0000974std::unique_ptr<CFG> CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) {
Ted Kremenek8aed4902009-10-20 23:46:25 +0000975 assert(cfg.get());
Ted Kremenek93668002009-07-17 22:18:43 +0000976 if (!Statement)
Craig Topper25542942014-05-20 04:30:07 +0000977 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +0000978
Mike Stump31feda52009-07-17 01:31:16 +0000979 // Create an empty block that will serve as the exit block for the CFG. Since
980 // this is the first block added to the CFG, it will be implicitly registered
981 // as the exit block.
Ted Kremenek81e14852007-08-27 19:46:09 +0000982 Succ = createBlock();
Ted Kremenek289ae4f2009-10-12 20:55:07 +0000983 assert(Succ == &cfg->getExit());
Craig Topper25542942014-05-20 04:30:07 +0000984 Block = nullptr; // the EXIT block is empty. Create all other blocks lazily.
Mike Stump31feda52009-07-17 01:31:16 +0000985
Marcin Swiderski20b88732010-10-05 05:37:00 +0000986 if (BuildOpts.AddImplicitDtors)
987 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D))
988 addImplicitDtorsForDestructor(DD);
989
Ted Kremenek9aae5132007-08-23 21:42:29 +0000990 // Visit the statements and create the CFG.
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000991 CFGBlock *B = addStmt(Statement);
992
993 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +0000994 return nullptr;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +0000995
Marcin Swiderski87b1bb62010-10-04 03:38:22 +0000996 // For C++ constructor add initializers to CFG.
997 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
998 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(),
999 E = CD->init_rend(); I != E; ++I) {
1000 B = addInitializer(*I);
1001 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001002 return nullptr;
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001003 }
1004 }
1005
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001006 if (B)
1007 Succ = B;
Mike Stump6bf1c082010-01-21 02:21:40 +00001008
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001009 // Backpatch the gotos whose label -> block mappings we didn't know when we
1010 // encountered them.
1011 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
1012 E = BackpatchBlocks.end(); I != E; ++I ) {
Mike Stump31feda52009-07-17 01:31:16 +00001013
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001014 CFGBlock *B = I->block;
Rafael Espindola210de572013-03-27 15:37:54 +00001015 const GotoStmt *G = cast<GotoStmt>(B->getTerminator());
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001016 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00001017
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001018 // If there is no target for the goto, then we are looking at an
1019 // incomplete AST. Handle this by not registering a successor.
1020 if (LI == LabelMap.end()) continue;
Ted Kremenek9aae5132007-08-23 21:42:29 +00001021
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001022 JumpTarget JT = LI->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001023 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition,
1024 JT.scopePosition);
1025 addSuccessor(B, JT.block);
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001026 }
1027
1028 // Add successors to the Indirect Goto Dispatch block (if we have one).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001029 if (CFGBlock *B = cfg->getIndirectGotoBlock())
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001030 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
1031 E = AddressTakenLabels.end(); I != E; ++I ) {
1032
1033 // Lookup the target block.
1034 LabelMapTy::iterator LI = LabelMap.find(*I);
1035
1036 // If there is no target block that contains label, then we are looking
1037 // at an incomplete AST. Handle this by not registering a successor.
Ted Kremenek9aae5132007-08-23 21:42:29 +00001038 if (LI == LabelMap.end()) continue;
Zhongxing Xub1e10aa2010-09-06 07:04:06 +00001039
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001040 addSuccessor(B, LI->second.block);
Ted Kremenekeda180e22007-08-28 19:26:49 +00001041 }
Mike Stump31feda52009-07-17 01:31:16 +00001042
Mike Stump31feda52009-07-17 01:31:16 +00001043 // Create an empty entry block that has no predecessors.
Ted Kremenek5c50fd12007-09-26 21:23:31 +00001044 cfg->setEntry(createBlock());
Mike Stump31feda52009-07-17 01:31:16 +00001045
David Blaikiee90195c2014-08-29 18:53:26 +00001046 return std::move(cfg);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001047}
Mike Stump31feda52009-07-17 01:31:16 +00001048
Ted Kremenek9aae5132007-08-23 21:42:29 +00001049/// createBlock - Used to lazily create blocks that are connected
1050/// to the current (global) succcessor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001051CFGBlock *CFGBuilder::createBlock(bool add_successor) {
1052 CFGBlock *B = cfg->createBlock();
Ted Kremenek93668002009-07-17 22:18:43 +00001053 if (add_successor && Succ)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001054 addSuccessor(B, Succ);
Ted Kremenek9aae5132007-08-23 21:42:29 +00001055 return B;
1056}
Mike Stump31feda52009-07-17 01:31:16 +00001057
Chandler Carrutha70991b2011-09-13 09:13:49 +00001058/// createNoReturnBlock - Used to create a block is a 'noreturn' point in the
1059/// CFG. It is *not* connected to the current (global) successor, and instead
1060/// directly tied to the exit block in order to be reachable.
1061CFGBlock *CFGBuilder::createNoReturnBlock() {
1062 CFGBlock *B = createBlock(false);
Chandler Carruth75d78232011-09-13 09:53:55 +00001063 B->setHasNoReturnElement();
Ted Kremenekf3539192014-02-27 00:24:05 +00001064 addSuccessor(B, &cfg->getExit(), Succ);
Chandler Carrutha70991b2011-09-13 09:13:49 +00001065 return B;
1066}
1067
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001068/// addInitializer - Add C++ base or member initializer element to CFG.
Alexis Hunt1d792652011-01-08 20:30:50 +00001069CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) {
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001070 if (!BuildOpts.AddInitializers)
1071 return Block;
1072
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001073 bool HasTemporaries = false;
1074
1075 // Destructors of temporaries in initialization expression should be called
1076 // after initialization finishes.
1077 Expr *Init = I->getInit();
1078 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00001079 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001080
Jordan Rose6d671cc2012-09-05 22:55:23 +00001081 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001082 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00001083 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00001084 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
1085 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001086 }
1087 }
1088
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001089 autoCreateBlock();
1090 appendInitializer(Block, I);
1091
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001092 if (Init) {
Ted Kremenek8219b822010-12-16 07:46:53 +00001093 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001094 // For expression with temporaries go directly to subexpression to omit
1095 // generating destructors for the second time.
Ted Kremenek8219b822010-12-16 07:46:53 +00001096 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr());
1097 }
Enrico Pertosofaed8012015-06-03 10:12:40 +00001098 if (BuildOpts.AddCXXDefaultInitExprInCtors) {
1099 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(Init)) {
1100 // In general, appending the expression wrapped by a CXXDefaultInitExpr
1101 // may cause the same Expr to appear more than once in the CFG. Doing it
1102 // here is safe because there's only one initializer per field.
1103 autoCreateBlock();
1104 appendStmt(Block, Default);
1105 if (Stmt *Child = Default->getExpr())
1106 if (CFGBlock *R = Visit(Child))
1107 Block = R;
1108 return Block;
1109 }
1110 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001111 return Visit(Init);
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001112 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001113
Marcin Swiderski87b1bb62010-10-04 03:38:22 +00001114 return Block;
1115}
1116
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001117/// \brief Retrieve the type of the temporary object whose lifetime was
1118/// extended by a local reference with the given initializer.
1119static QualType getReferenceInitTemporaryType(ASTContext &Context,
1120 const Expr *Init) {
1121 while (true) {
1122 // Skip parentheses.
1123 Init = Init->IgnoreParens();
1124
1125 // Skip through cleanups.
1126 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) {
1127 Init = EWC->getSubExpr();
1128 continue;
1129 }
1130
1131 // Skip through the temporary-materialization expression.
1132 if (const MaterializeTemporaryExpr *MTE
1133 = dyn_cast<MaterializeTemporaryExpr>(Init)) {
1134 Init = MTE->GetTemporaryExpr();
1135 continue;
1136 }
1137
1138 // Skip derived-to-base and no-op casts.
1139 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) {
1140 if ((CE->getCastKind() == CK_DerivedToBase ||
1141 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1142 CE->getCastKind() == CK_NoOp) &&
1143 Init->getType()->isRecordType()) {
1144 Init = CE->getSubExpr();
1145 continue;
1146 }
1147 }
1148
1149 // Skip member accesses into rvalues.
1150 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) {
1151 if (!ME->isArrow() && ME->getBase()->isRValue()) {
1152 Init = ME->getBase();
1153 continue;
1154 }
1155 }
1156
1157 break;
1158 }
1159
1160 return Init->getType();
1161}
1162
Marcin Swiderski5e415732010-09-30 23:05:00 +00001163/// addAutomaticObjDtors - Add to current block automatic objects destructors
1164/// for objects in range of local scope positions. Use S as trigger statement
1165/// for destructors.
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001166void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B,
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001167 LocalScope::const_iterator E, Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001168 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001169 return;
1170
Marcin Swiderski5e415732010-09-30 23:05:00 +00001171 if (B == E)
Zhongxing Xu6d372f72010-10-01 03:22:39 +00001172 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001173
Chandler Carruthad747252011-09-13 06:09:01 +00001174 // We need to append the destructors in reverse order, but any one of them
1175 // may be a no-return destructor which changes the CFG. As a result, buffer
1176 // this sequence up and replay them in reverse order when appending onto the
1177 // CFGBlock(s).
1178 SmallVector<VarDecl*, 10> Decls;
1179 Decls.reserve(B.distance(E));
1180 for (LocalScope::const_iterator I = B; I != E; ++I)
1181 Decls.push_back(*I);
1182
1183 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(),
1184 E = Decls.rend();
1185 I != E; ++I) {
1186 // If this destructor is marked as a no-return destructor, we need to
1187 // create a new block for the destructor which does not have as a successor
1188 // anything built thus far: control won't flow out of this block.
Ted Kremenek3d617732012-07-18 04:57:57 +00001189 QualType Ty = (*I)->getType();
1190 if (Ty->isReferenceType()) {
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001191 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit());
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001192 }
Ted Kremenek3d617732012-07-18 04:57:57 +00001193 Ty = Context->getBaseElementType(Ty);
1194
Richard Trieu95a192a2015-05-28 00:14:02 +00001195 if (Ty->getAsCXXRecordDecl()->isAnyDestructorNoReturn())
Chandler Carrutha70991b2011-09-13 09:13:49 +00001196 Block = createNoReturnBlock();
1197 else
Chandler Carruthad747252011-09-13 06:09:01 +00001198 autoCreateBlock();
Chandler Carruthad747252011-09-13 06:09:01 +00001199
1200 appendAutomaticObjDtor(Block, *I, S);
1201 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001202}
1203
Marcin Swiderski20b88732010-10-05 05:37:00 +00001204/// addImplicitDtorsForDestructor - Add implicit destructors generated for
1205/// base and member objects in destructor.
1206void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) {
1207 assert (BuildOpts.AddImplicitDtors
1208 && "Can be called only when dtors should be added");
1209 const CXXRecordDecl *RD = DD->getParent();
1210
1211 // At the end destroy virtual base objects.
Aaron Ballman445a9392014-03-13 16:15:17 +00001212 for (const auto &VI : RD->vbases()) {
1213 const CXXRecordDecl *CD = VI.getType()->getAsCXXRecordDecl();
Marcin Swiderski20b88732010-10-05 05:37:00 +00001214 if (!CD->hasTrivialDestructor()) {
1215 autoCreateBlock();
Aaron Ballman445a9392014-03-13 16:15:17 +00001216 appendBaseDtor(Block, &VI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001217 }
1218 }
1219
1220 // Before virtual bases destroy direct base objects.
Aaron Ballman574705e2014-03-13 15:41:46 +00001221 for (const auto &BI : RD->bases()) {
1222 if (!BI.isVirtual()) {
1223 const CXXRecordDecl *CD = BI.getType()->getAsCXXRecordDecl();
David Blaikie0f2ae782012-01-24 04:51:48 +00001224 if (!CD->hasTrivialDestructor()) {
1225 autoCreateBlock();
Aaron Ballman574705e2014-03-13 15:41:46 +00001226 appendBaseDtor(Block, &BI);
David Blaikie0f2ae782012-01-24 04:51:48 +00001227 }
1228 }
Marcin Swiderski20b88732010-10-05 05:37:00 +00001229 }
1230
1231 // First destroy member objects.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001232 for (auto *FI : RD->fields()) {
Marcin Swiderski01769902010-10-25 07:05:54 +00001233 // Check for constant size array. Set type to array element type.
1234 QualType QT = FI->getType();
1235 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
1236 if (AT->getSize() == 0)
1237 continue;
1238 QT = AT->getElementType();
1239 }
1240
1241 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
Marcin Swiderski20b88732010-10-05 05:37:00 +00001242 if (!CD->hasTrivialDestructor()) {
1243 autoCreateBlock();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001244 appendMemberDtor(Block, FI);
Marcin Swiderski20b88732010-10-05 05:37:00 +00001245 }
1246 }
1247}
1248
Marcin Swiderski5e415732010-09-30 23:05:00 +00001249/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either
1250/// way return valid LocalScope object.
1251LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) {
1252 if (!Scope) {
Ted Kremenekc7bfdcd2011-02-15 02:47:45 +00001253 llvm::BumpPtrAllocator &alloc = cfg->getAllocator();
1254 Scope = alloc.Allocate<LocalScope>();
1255 BumpVectorContext ctx(alloc);
1256 new (Scope) LocalScope(ctx, ScopePos);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001257 }
1258 return Scope;
1259}
1260
1261/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement
Zhongxing Xu81714f22010-10-01 03:00:16 +00001262/// that should create implicit scope (e.g. if/else substatements).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001263void CFGBuilder::addLocalScopeForStmt(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001264 if (!BuildOpts.AddImplicitDtors)
Zhongxing Xu81714f22010-10-01 03:00:16 +00001265 return;
1266
Craig Topper25542942014-05-20 04:30:07 +00001267 LocalScope *Scope = nullptr;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001268
1269 // For compound statement we will be creating explicit scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001270 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) {
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001271 for (auto *BI : CS->body()) {
1272 Stmt *SI = BI->stripLabelLikeStatements();
Chris Lattnerc8e630e2011-02-17 07:39:24 +00001273 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001274 Scope = addLocalScopeForDeclStmt(DS, Scope);
1275 }
Zhongxing Xu81714f22010-10-01 03:00:16 +00001276 return;
Marcin Swiderski5e415732010-09-30 23:05:00 +00001277 }
1278
1279 // For any other statement scope will be implicit and as such will be
1280 // interesting only for DeclStmt.
Chandler Carrutha626d642011-09-10 00:02:34 +00001281 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements()))
Zhongxing Xu307701e2010-10-01 03:09:09 +00001282 addLocalScopeForDeclStmt(DS);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001283}
1284
1285/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will
1286/// reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001287LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001288 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001289 if (!BuildOpts.AddImplicitDtors)
1290 return Scope;
1291
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001292 for (auto *DI : DS->decls())
1293 if (VarDecl *VD = dyn_cast<VarDecl>(DI))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001294 Scope = addLocalScopeForVarDecl(VD, Scope);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001295 return Scope;
1296}
1297
1298/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will
1299/// create add scope for automatic objects and temporary objects bound to
1300/// const reference. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001301LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD,
Zhongxing Xu307701e2010-10-01 03:09:09 +00001302 LocalScope* Scope) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001303 if (!BuildOpts.AddImplicitDtors)
1304 return Scope;
1305
1306 // Check if variable is local.
1307 switch (VD->getStorageClass()) {
1308 case SC_None:
1309 case SC_Auto:
1310 case SC_Register:
1311 break;
1312 default: return Scope;
1313 }
1314
1315 // Check for const references bound to temporary. Set type to pointee.
1316 QualType QT = VD->getType();
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001317 if (QT.getTypePtr()->isReferenceType()) {
Richard Smith5a0ef782013-06-27 21:43:17 +00001318 // Attempt to determine whether this declaration lifetime-extends a
1319 // temporary.
1320 //
1321 // FIXME: This is incorrect. Non-reference declarations can lifetime-extend
1322 // temporaries, and a single declaration can extend multiple temporaries.
1323 // We should look at the storage duration on each nested
1324 // MaterializeTemporaryExpr instead.
1325 const Expr *Init = VD->getInit();
1326 if (!Init)
1327 return Scope;
1328 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init))
1329 Init = EWC->getSubExpr();
1330 if (!isa<MaterializeTemporaryExpr>(Init))
Marcin Swiderski5e415732010-09-30 23:05:00 +00001331 return Scope;
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001332
Richard Smith5a0ef782013-06-27 21:43:17 +00001333 // Lifetime-extending a temporary.
1334 QT = getReferenceInitTemporaryType(*Context, Init);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001335 }
1336
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001337 // Check for constant size array. Set type to array element type.
Douglas Gregor6c8f07f2011-11-15 15:29:30 +00001338 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) {
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001339 if (AT->getSize() == 0)
1340 return Scope;
1341 QT = AT->getElementType();
1342 }
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001343
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00001344 // Check if type is a C++ class with non-trivial destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001345 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl())
David Blaikie0f2ae782012-01-24 04:51:48 +00001346 if (!CD->hasTrivialDestructor()) {
Zhongxing Xu614e17d2010-10-05 08:38:06 +00001347 // Add the variable to scope
1348 Scope = createOrReuseLocalScope(Scope);
1349 Scope->addVar(VD);
1350 ScopePos = Scope->begin();
1351 }
Marcin Swiderski5e415732010-09-30 23:05:00 +00001352 return Scope;
1353}
1354
1355/// addLocalScopeAndDtors - For given statement add local scope for it and
1356/// add destructors that will cleanup the scope. Will reuse Scope if not NULL.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001357void CFGBuilder::addLocalScopeAndDtors(Stmt *S) {
Marcin Swiderski5e415732010-09-30 23:05:00 +00001358 if (!BuildOpts.AddImplicitDtors)
1359 return;
1360
1361 LocalScope::const_iterator scopeBeginPos = ScopePos;
Zhongxing Xu81714f22010-10-01 03:00:16 +00001362 addLocalScopeForStmt(S);
Marcin Swiderski5e415732010-09-30 23:05:00 +00001363 addAutomaticObjDtors(ScopePos, scopeBeginPos, S);
1364}
1365
Marcin Swiderski321a7072010-09-30 22:54:37 +00001366/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for
1367/// variables with automatic storage duration to CFGBlock's elements vector.
1368/// Elements will be prepended to physical beginning of the vector which
1369/// happens to be logical end. Use blocks terminator as statement that specifies
1370/// destructors call site.
Chandler Carruthad747252011-09-13 06:09:01 +00001371/// FIXME: This mechanism for adding automatic destructors doesn't handle
1372/// no-return destructors properly.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001373void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk,
Marcin Swiderski321a7072010-09-30 22:54:37 +00001374 LocalScope::const_iterator B, LocalScope::const_iterator E) {
Chandler Carruthad747252011-09-13 06:09:01 +00001375 BumpVectorContext &C = cfg->getBumpVectorContext();
1376 CFGBlock::iterator InsertPos
1377 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C);
1378 for (LocalScope::const_iterator I = B; I != E; ++I)
1379 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I,
1380 Blk->getTerminator());
Marcin Swiderski321a7072010-09-30 22:54:37 +00001381}
1382
Ted Kremenek93668002009-07-17 22:18:43 +00001383/// Visit - Walk the subtree of a statement and add extra
Mike Stump31feda52009-07-17 01:31:16 +00001384/// blocks for ternary operators, &&, and ||. We also process "," and
1385/// DeclStmts (which may contain nested control-flow).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001386CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001387 if (!S) {
1388 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00001389 return nullptr;
Ted Kremenekbc1416d2010-04-30 22:25:53 +00001390 }
Jordy Rose17347372011-06-10 08:49:37 +00001391
1392 if (Expr *E = dyn_cast<Expr>(S))
1393 S = E->IgnoreParens();
1394
Ted Kremenek93668002009-07-17 22:18:43 +00001395 switch (S->getStmtClass()) {
1396 default:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001397 return VisitStmt(S, asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001398
1399 case Stmt::AddrLabelExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001400 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCallc07a0c72011-02-17 10:25:35 +00001402 case Stmt::BinaryConditionalOperatorClass:
1403 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc);
1404
Ted Kremenek93668002009-07-17 22:18:43 +00001405 case Stmt::BinaryOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001406 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001407
Ted Kremenek93668002009-07-17 22:18:43 +00001408 case Stmt::BlockExprClass:
Ted Kremeneke2499842012-04-12 20:03:44 +00001409 return VisitNoRecurse(cast<Expr>(S), asc);
Ted Kremenek93668002009-07-17 22:18:43 +00001410
Ted Kremenek93668002009-07-17 22:18:43 +00001411 case Stmt::BreakStmtClass:
1412 return VisitBreakStmt(cast<BreakStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001413
Ted Kremenek93668002009-07-17 22:18:43 +00001414 case Stmt::CallExprClass:
Ted Kremenek128d04d2010-08-31 18:47:34 +00001415 case Stmt::CXXOperatorCallExprClass:
John McCallc67067f2011-05-11 07:19:11 +00001416 case Stmt::CXXMemberCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001417 case Stmt::UserDefinedLiteralClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001418 return VisitCallExpr(cast<CallExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001419
Ted Kremenek93668002009-07-17 22:18:43 +00001420 case Stmt::CaseStmtClass:
1421 return VisitCaseStmt(cast<CaseStmt>(S));
1422
1423 case Stmt::ChooseExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001424 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001425
Ted Kremenek93668002009-07-17 22:18:43 +00001426 case Stmt::CompoundStmtClass:
1427 return VisitCompoundStmt(cast<CompoundStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001428
Ted Kremenek93668002009-07-17 22:18:43 +00001429 case Stmt::ConditionalOperatorClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001430 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001431
Ted Kremenek93668002009-07-17 22:18:43 +00001432 case Stmt::ContinueStmtClass:
1433 return VisitContinueStmt(cast<ContinueStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001434
Ted Kremenekb27378c2010-01-19 20:40:33 +00001435 case Stmt::CXXCatchStmtClass:
1436 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
1437
John McCall5d413782010-12-06 08:20:24 +00001438 case Stmt::ExprWithCleanupsClass:
1439 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
Ted Kremenek82bfc862010-08-28 00:19:02 +00001440
Jordan Rosee5d53932012-08-23 18:10:53 +00001441 case Stmt::CXXDefaultArgExprClass:
Richard Smith852c9db2013-04-20 22:23:05 +00001442 case Stmt::CXXDefaultInitExprClass:
Jordan Rosee5d53932012-08-23 18:10:53 +00001443 // FIXME: The expression inside a CXXDefaultArgExpr is owned by the
1444 // called function's declaration, not by the caller. If we simply add
1445 // this expression to the CFG, we could end up with the same Expr
1446 // appearing multiple times.
1447 // PR13385 / <rdar://problem/12156507>
Richard Smith852c9db2013-04-20 22:23:05 +00001448 //
1449 // It's likewise possible for multiple CXXDefaultInitExprs for the same
1450 // expression to be used in the same function (through aggregate
1451 // initialization).
Jordan Rosee5d53932012-08-23 18:10:53 +00001452 return VisitStmt(S, asc);
1453
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001454 case Stmt::CXXBindTemporaryExprClass:
1455 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc);
1456
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001457 case Stmt::CXXConstructExprClass:
1458 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc);
1459
Jordan Rosec9176072014-01-13 17:59:19 +00001460 case Stmt::CXXNewExprClass:
1461 return VisitCXXNewExpr(cast<CXXNewExpr>(S), asc);
1462
Jordan Rosed2f40792013-09-03 17:00:57 +00001463 case Stmt::CXXDeleteExprClass:
1464 return VisitCXXDeleteExpr(cast<CXXDeleteExpr>(S), asc);
1465
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001466 case Stmt::CXXFunctionalCastExprClass:
1467 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc);
1468
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00001469 case Stmt::CXXTemporaryObjectExprClass:
1470 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc);
1471
Ted Kremenekb27378c2010-01-19 20:40:33 +00001472 case Stmt::CXXThrowExprClass:
1473 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001474
Ted Kremenekb27378c2010-01-19 20:40:33 +00001475 case Stmt::CXXTryStmtClass:
1476 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001477
Richard Smith02e85f32011-04-14 22:09:26 +00001478 case Stmt::CXXForRangeStmtClass:
1479 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
1480
Ted Kremenek93668002009-07-17 22:18:43 +00001481 case Stmt::DeclStmtClass:
1482 return VisitDeclStmt(cast<DeclStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001483
Ted Kremenek93668002009-07-17 22:18:43 +00001484 case Stmt::DefaultStmtClass:
1485 return VisitDefaultStmt(cast<DefaultStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001486
Ted Kremenek93668002009-07-17 22:18:43 +00001487 case Stmt::DoStmtClass:
1488 return VisitDoStmt(cast<DoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001489
Ted Kremenek93668002009-07-17 22:18:43 +00001490 case Stmt::ForStmtClass:
1491 return VisitForStmt(cast<ForStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001492
Ted Kremenek93668002009-07-17 22:18:43 +00001493 case Stmt::GotoStmtClass:
1494 return VisitGotoStmt(cast<GotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001495
Ted Kremenek93668002009-07-17 22:18:43 +00001496 case Stmt::IfStmtClass:
1497 return VisitIfStmt(cast<IfStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001498
Ted Kremenek8219b822010-12-16 07:46:53 +00001499 case Stmt::ImplicitCastExprClass:
1500 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00001501
Ted Kremenek93668002009-07-17 22:18:43 +00001502 case Stmt::IndirectGotoStmtClass:
1503 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001504
Ted Kremenek93668002009-07-17 22:18:43 +00001505 case Stmt::LabelStmtClass:
1506 return VisitLabelStmt(cast<LabelStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001507
Ted Kremenekda76a942012-04-12 20:34:52 +00001508 case Stmt::LambdaExprClass:
1509 return VisitLambdaExpr(cast<LambdaExpr>(S), asc);
1510
Ted Kremenek5868ec62010-04-11 17:02:10 +00001511 case Stmt::MemberExprClass:
1512 return VisitMemberExpr(cast<MemberExpr>(S), asc);
1513
Ted Kremenek04268232011-11-05 00:10:15 +00001514 case Stmt::NullStmtClass:
1515 return Block;
1516
Ted Kremenek93668002009-07-17 22:18:43 +00001517 case Stmt::ObjCAtCatchStmtClass:
Mike Stump11289f42009-09-09 15:08:12 +00001518 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
1519
Ted Kremenek5022f1d2012-03-06 23:40:47 +00001520 case Stmt::ObjCAutoreleasePoolStmtClass:
1521 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S));
1522
Ted Kremenek93668002009-07-17 22:18:43 +00001523 case Stmt::ObjCAtSynchronizedStmtClass:
1524 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001525
Ted Kremenek93668002009-07-17 22:18:43 +00001526 case Stmt::ObjCAtThrowStmtClass:
1527 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001528
Ted Kremenek93668002009-07-17 22:18:43 +00001529 case Stmt::ObjCAtTryStmtClass:
1530 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001531
Ted Kremenek93668002009-07-17 22:18:43 +00001532 case Stmt::ObjCForCollectionStmtClass:
1533 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001534
Ted Kremenek04268232011-11-05 00:10:15 +00001535 case Stmt::OpaqueValueExprClass:
Ted Kremenek93668002009-07-17 22:18:43 +00001536 return Block;
Mike Stump11289f42009-09-09 15:08:12 +00001537
John McCallfe96e0b2011-11-06 09:01:30 +00001538 case Stmt::PseudoObjectExprClass:
1539 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S));
1540
Ted Kremenek93668002009-07-17 22:18:43 +00001541 case Stmt::ReturnStmtClass:
1542 return VisitReturnStmt(cast<ReturnStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001543
Peter Collingbournee190dee2011-03-11 19:24:49 +00001544 case Stmt::UnaryExprOrTypeTraitExprClass:
1545 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1546 asc);
Mike Stump11289f42009-09-09 15:08:12 +00001547
Ted Kremenek93668002009-07-17 22:18:43 +00001548 case Stmt::StmtExprClass:
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001549 return VisitStmtExpr(cast<StmtExpr>(S), asc);
Mike Stump11289f42009-09-09 15:08:12 +00001550
Ted Kremenek93668002009-07-17 22:18:43 +00001551 case Stmt::SwitchStmtClass:
1552 return VisitSwitchStmt(cast<SwitchStmt>(S));
Mike Stump11289f42009-09-09 15:08:12 +00001553
Zhanyong Wan6dace612010-11-22 08:45:56 +00001554 case Stmt::UnaryOperatorClass:
1555 return VisitUnaryOperator(cast<UnaryOperator>(S), asc);
1556
Ted Kremenek93668002009-07-17 22:18:43 +00001557 case Stmt::WhileStmtClass:
1558 return VisitWhileStmt(cast<WhileStmt>(S));
1559 }
1560}
Mike Stump11289f42009-09-09 15:08:12 +00001561
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001562CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001563 if (asc.alwaysAdd(*this, S)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001564 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001565 appendStmt(Block, S);
Mike Stump31feda52009-07-17 01:31:16 +00001566 }
Mike Stump11289f42009-09-09 15:08:12 +00001567
Ted Kremenek93668002009-07-17 22:18:43 +00001568 return VisitChildren(S);
Ted Kremenek9e248872007-08-27 21:27:44 +00001569}
Mike Stump31feda52009-07-17 01:31:16 +00001570
Ted Kremenek93668002009-07-17 22:18:43 +00001571/// VisitChildren - Visit the children of a Stmt.
Ted Kremenek8ae67872013-02-05 22:00:19 +00001572CFGBlock *CFGBuilder::VisitChildren(Stmt *S) {
1573 CFGBlock *B = Block;
Ted Kremenek828f6312011-02-21 22:11:26 +00001574
Ted Kremenek8ae67872013-02-05 22:00:19 +00001575 // Visit the children in their reverse order so that they appear in
1576 // left-to-right (natural) order in the CFG.
1577 reverse_children RChildren(S);
1578 for (reverse_children::iterator I = RChildren.begin(), E = RChildren.end();
1579 I != E; ++I) {
1580 if (Stmt *Child = *I)
1581 if (CFGBlock *R = Visit(Child))
1582 B = R;
1583 }
1584 return B;
Ted Kremenek9e248872007-08-27 21:27:44 +00001585}
Mike Stump11289f42009-09-09 15:08:12 +00001586
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001587CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
1588 AddStmtChoice asc) {
Ted Kremenek93668002009-07-17 22:18:43 +00001589 AddressTakenLabels.insert(A->getLabel());
Ted Kremenek9e248872007-08-27 21:27:44 +00001590
Ted Kremenek7c58d352011-03-10 01:14:11 +00001591 if (asc.alwaysAdd(*this, A)) {
Ted Kremenek93668002009-07-17 22:18:43 +00001592 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001593 appendStmt(Block, A);
Ted Kremenek93668002009-07-17 22:18:43 +00001594 }
Ted Kremenek81e14852007-08-27 19:46:09 +00001595
Ted Kremenek9aae5132007-08-23 21:42:29 +00001596 return Block;
1597}
Mike Stump11289f42009-09-09 15:08:12 +00001598
Zhanyong Wan6dace612010-11-22 08:45:56 +00001599CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U,
Ted Kremenek8219b822010-12-16 07:46:53 +00001600 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001601 if (asc.alwaysAdd(*this, U)) {
Zhanyong Wan6dace612010-11-22 08:45:56 +00001602 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001603 appendStmt(Block, U);
Zhanyong Wan6dace612010-11-22 08:45:56 +00001604 }
1605
Ted Kremenek8219b822010-12-16 07:46:53 +00001606 return Visit(U->getSubExpr(), AddStmtChoice());
Zhanyong Wan6dace612010-11-22 08:45:56 +00001607}
1608
Ted Kremeneka16436f2012-07-14 05:04:06 +00001609CFGBlock *CFGBuilder::VisitLogicalOperator(BinaryOperator *B) {
1610 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
1611 appendStmt(ConfluenceBlock, B);
Mike Stump11289f42009-09-09 15:08:12 +00001612
Ted Kremeneka16436f2012-07-14 05:04:06 +00001613 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001614 return nullptr;
Ted Kremeneka16436f2012-07-14 05:04:06 +00001615
Craig Topper25542942014-05-20 04:30:07 +00001616 return VisitLogicalOperator(B, nullptr, ConfluenceBlock,
1617 ConfluenceBlock).first;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001618}
1619
1620std::pair<CFGBlock*, CFGBlock*>
1621CFGBuilder::VisitLogicalOperator(BinaryOperator *B,
1622 Stmt *Term,
1623 CFGBlock *TrueBlock,
1624 CFGBlock *FalseBlock) {
1625
1626 // Introspect the RHS. If it is a nested logical operation, we recursively
1627 // build the CFG using this function. Otherwise, resort to default
1628 // CFG construction behavior.
1629 Expr *RHS = B->getRHS()->IgnoreParens();
1630 CFGBlock *RHSBlock, *ExitBlock;
1631
1632 do {
1633 if (BinaryOperator *B_RHS = dyn_cast<BinaryOperator>(RHS))
1634 if (B_RHS->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001635 std::tie(RHSBlock, ExitBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00001636 VisitLogicalOperator(B_RHS, Term, TrueBlock, FalseBlock);
1637 break;
1638 }
1639
1640 // The RHS is not a nested logical operation. Don't push the terminator
1641 // down further, but instead visit RHS and construct the respective
1642 // pieces of the CFG, and link up the RHSBlock with the terminator
1643 // we have been provided.
1644 ExitBlock = RHSBlock = createBlock(false);
1645
1646 if (!Term) {
1647 assert(TrueBlock == FalseBlock);
1648 addSuccessor(RHSBlock, TrueBlock);
1649 }
1650 else {
1651 RHSBlock->setTerminator(Term);
1652 TryResult KnownVal = tryEvaluateBool(RHS);
Richard Trieuf935b562014-04-05 05:17:01 +00001653 if (!KnownVal.isKnown())
1654 KnownVal = tryEvaluateBool(B);
Ted Kremenek782f0032014-03-07 02:25:53 +00001655 addSuccessor(RHSBlock, TrueBlock, !KnownVal.isFalse());
1656 addSuccessor(RHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremenekb50e7162012-07-14 05:04:10 +00001657 }
1658
1659 Block = RHSBlock;
1660 RHSBlock = addStmt(RHS);
1661 }
1662 while (false);
1663
1664 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001665 return std::make_pair(nullptr, nullptr);
Ted Kremenekb50e7162012-07-14 05:04:10 +00001666
1667 // Generate the blocks for evaluating the LHS.
1668 Expr *LHS = B->getLHS()->IgnoreParens();
1669
1670 if (BinaryOperator *B_LHS = dyn_cast<BinaryOperator>(LHS))
1671 if (B_LHS->isLogicalOp()) {
1672 if (B->getOpcode() == BO_LOr)
1673 FalseBlock = RHSBlock;
1674 else
1675 TrueBlock = RHSBlock;
1676
1677 // For the LHS, treat 'B' as the terminator that we want to sink
1678 // into the nested branch. The RHS always gets the top-most
1679 // terminator.
1680 return VisitLogicalOperator(B_LHS, B, TrueBlock, FalseBlock);
1681 }
1682
1683 // Create the block evaluating the LHS.
1684 // This contains the '&&' or '||' as the terminator.
Ted Kremeneka16436f2012-07-14 05:04:06 +00001685 CFGBlock *LHSBlock = createBlock(false);
1686 LHSBlock->setTerminator(B);
1687
Ted Kremeneka16436f2012-07-14 05:04:06 +00001688 Block = LHSBlock;
Ted Kremenekb50e7162012-07-14 05:04:10 +00001689 CFGBlock *EntryLHSBlock = addStmt(LHS);
1690
1691 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001692 return std::make_pair(nullptr, nullptr);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001693
1694 // See if this is a known constant.
Ted Kremenekb50e7162012-07-14 05:04:10 +00001695 TryResult KnownVal = tryEvaluateBool(LHS);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001696
1697 // Now link the LHSBlock with RHSBlock.
1698 if (B->getOpcode() == BO_LOr) {
Ted Kremenek782f0032014-03-07 02:25:53 +00001699 addSuccessor(LHSBlock, TrueBlock, !KnownVal.isFalse());
1700 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001701 } else {
1702 assert(B->getOpcode() == BO_LAnd);
Ted Kremenek782f0032014-03-07 02:25:53 +00001703 addSuccessor(LHSBlock, RHSBlock, !KnownVal.isFalse());
1704 addSuccessor(LHSBlock, FalseBlock, !KnownVal.isTrue());
Ted Kremeneka16436f2012-07-14 05:04:06 +00001705 }
1706
Ted Kremenekb50e7162012-07-14 05:04:10 +00001707 return std::make_pair(EntryLHSBlock, ExitBlock);
Ted Kremeneka16436f2012-07-14 05:04:06 +00001708}
1709
Ted Kremenekb50e7162012-07-14 05:04:10 +00001710
Ted Kremeneka16436f2012-07-14 05:04:06 +00001711CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
1712 AddStmtChoice asc) {
1713 // && or ||
1714 if (B->isLogicalOp())
1715 return VisitLogicalOperator(B);
1716
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001717 if (B->getOpcode() == BO_Comma) { // ,
Ted Kremenekfe9b7682009-07-17 22:57:50 +00001718 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001719 appendStmt(Block, B);
Ted Kremenek93668002009-07-17 22:18:43 +00001720 addStmt(B->getRHS());
1721 return addStmt(B->getLHS());
1722 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00001723
1724 if (B->isAssignmentOp()) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001725 if (asc.alwaysAdd(*this, B)) {
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001726 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001727 appendStmt(Block, B);
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001728 }
Ted Kremenek8219b822010-12-16 07:46:53 +00001729 Visit(B->getLHS());
Marcin Swiderski77232492010-10-24 08:21:40 +00001730 return Visit(B->getRHS());
Zhongxing Xu41cdf582010-06-03 06:23:18 +00001731 }
Mike Stump11289f42009-09-09 15:08:12 +00001732
Ted Kremenek7c58d352011-03-10 01:14:11 +00001733 if (asc.alwaysAdd(*this, B)) {
Marcin Swiderski77232492010-10-24 08:21:40 +00001734 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001735 appendStmt(Block, B);
Marcin Swiderski77232492010-10-24 08:21:40 +00001736 }
1737
Zhongxing Xud95ccd52010-10-27 03:23:10 +00001738 CFGBlock *RBlock = Visit(B->getRHS());
1739 CFGBlock *LBlock = Visit(B->getLHS());
1740 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr
1741 // containing a DoStmt, and the LHS doesn't create a new block, then we should
1742 // return RBlock. Otherwise we'll incorrectly return NULL.
1743 return (LBlock ? LBlock : RBlock);
Ted Kremenek93668002009-07-17 22:18:43 +00001744}
1745
Ted Kremeneke2499842012-04-12 20:03:44 +00001746CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00001747 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek470bfa42009-11-25 01:34:30 +00001748 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001749 appendStmt(Block, E);
Ted Kremenek470bfa42009-11-25 01:34:30 +00001750 }
1751 return Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001752}
1753
Ted Kremenek93668002009-07-17 22:18:43 +00001754CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
1755 // "break" is a control-flow statement. Thus we stop processing the current
1756 // block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001757 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001758 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001759
Ted Kremenek93668002009-07-17 22:18:43 +00001760 // Now create a new block that ends with the break statement.
1761 Block = createBlock(false);
1762 Block->setTerminator(B);
Mike Stump11289f42009-09-09 15:08:12 +00001763
Ted Kremenek93668002009-07-17 22:18:43 +00001764 // If there is no target for the break, then we are looking at an incomplete
1765 // AST. This means that the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00001766 if (BreakJumpTarget.block) {
1767 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B);
1768 addSuccessor(Block, BreakJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00001769 } else
Ted Kremenek93668002009-07-17 22:18:43 +00001770 badCFG = true;
Mike Stump11289f42009-09-09 15:08:12 +00001771
1772
Ted Kremenek9aae5132007-08-23 21:42:29 +00001773 return Block;
1774}
Mike Stump11289f42009-09-09 15:08:12 +00001775
Sebastian Redl31ad7542011-03-13 17:09:40 +00001776static bool CanThrow(Expr *E, ASTContext &Ctx) {
Mike Stump04c68512010-01-21 15:20:48 +00001777 QualType Ty = E->getType();
1778 if (Ty->isFunctionPointerType())
1779 Ty = Ty->getAs<PointerType>()->getPointeeType();
1780 else if (Ty->isBlockPointerType())
1781 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
Ted Kremenekdc03bd02010-08-02 23:46:59 +00001782
Mike Stump04c68512010-01-21 15:20:48 +00001783 const FunctionType *FT = Ty->getAs<FunctionType>();
1784 if (FT) {
1785 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
Richard Smithd3b5c9082012-07-27 04:22:15 +00001786 if (!isUnresolvedExceptionSpec(Proto->getExceptionSpecType()) &&
Richard Smithf623c962012-04-17 00:58:00 +00001787 Proto->isNothrow(Ctx))
Mike Stump04c68512010-01-21 15:20:48 +00001788 return false;
1789 }
1790 return true;
1791}
1792
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001793CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
John McCallc67067f2011-05-11 07:19:11 +00001794 // Compute the callee type.
1795 QualType calleeType = C->getCallee()->getType();
1796 if (calleeType == Context->BoundMemberTy) {
1797 QualType boundType = Expr::findBoundMemberType(C->getCallee());
1798
1799 // We should only get a null bound type if processing a dependent
1800 // CFG. Recover by assuming nothing.
1801 if (!boundType.isNull()) calleeType = boundType;
Ted Kremenek93668002009-07-17 22:18:43 +00001802 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001803
John McCallc67067f2011-05-11 07:19:11 +00001804 // If this is a call to a no-return function, this stops the block here.
1805 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn();
1806
Mike Stump04c68512010-01-21 15:20:48 +00001807 bool AddEHEdge = false;
Mike Stump92244b02010-01-19 22:00:14 +00001808
1809 // Languages without exceptions are assumed to not throw.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001810 if (Context->getLangOpts().Exceptions) {
Ted Kremeneke97b1eb2010-09-14 23:41:16 +00001811 if (BuildOpts.AddEHEdges)
Mike Stump04c68512010-01-21 15:20:48 +00001812 AddEHEdge = true;
Mike Stump92244b02010-01-19 22:00:14 +00001813 }
1814
Jordan Rose5374c072013-08-19 16:27:28 +00001815 // If this is a call to a builtin function, it might not actually evaluate
1816 // its arguments. Don't add them to the CFG if this is the case.
1817 bool OmitArguments = false;
1818
Mike Stump92244b02010-01-19 22:00:14 +00001819 if (FunctionDecl *FD = C->getDirectCallee()) {
Richard Smith10876ef2013-01-17 01:30:42 +00001820 if (FD->isNoReturn())
Mike Stump8c5d7992009-07-25 21:26:53 +00001821 NoReturn = true;
Mike Stump92244b02010-01-19 22:00:14 +00001822 if (FD->hasAttr<NoThrowAttr>())
Mike Stump04c68512010-01-21 15:20:48 +00001823 AddEHEdge = false;
Jordan Rose5374c072013-08-19 16:27:28 +00001824 if (FD->getBuiltinID() == Builtin::BI__builtin_object_size)
1825 OmitArguments = true;
Mike Stump92244b02010-01-19 22:00:14 +00001826 }
Mike Stump8c5d7992009-07-25 21:26:53 +00001827
Sebastian Redl31ad7542011-03-13 17:09:40 +00001828 if (!CanThrow(C->getCallee(), *Context))
Mike Stump04c68512010-01-21 15:20:48 +00001829 AddEHEdge = false;
1830
Jordan Rose5374c072013-08-19 16:27:28 +00001831 if (OmitArguments) {
1832 assert(!NoReturn && "noreturn calls with unevaluated args not implemented");
1833 assert(!AddEHEdge && "EH calls with unevaluated args not implemented");
1834 autoCreateBlock();
1835 appendStmt(Block, C);
1836 return Visit(C->getCallee());
1837 }
1838
1839 if (!NoReturn && !AddEHEdge) {
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001840 return VisitStmt(C, asc.withAlwaysAdd(true));
Jordan Rose5374c072013-08-19 16:27:28 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Mike Stump92244b02010-01-19 22:00:14 +00001843 if (Block) {
1844 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001845 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001846 return nullptr;
Mike Stump92244b02010-01-19 22:00:14 +00001847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Chandler Carrutha70991b2011-09-13 09:13:49 +00001849 if (NoReturn)
1850 Block = createNoReturnBlock();
1851 else
1852 Block = createBlock();
1853
Ted Kremenek2866bab2011-03-10 01:14:08 +00001854 appendStmt(Block, C);
Mike Stump8c5d7992009-07-25 21:26:53 +00001855
Mike Stump04c68512010-01-21 15:20:48 +00001856 if (AddEHEdge) {
Mike Stump92244b02010-01-19 22:00:14 +00001857 // Add exceptional edges.
1858 if (TryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001859 addSuccessor(Block, TryTerminatedBlock);
Mike Stump92244b02010-01-19 22:00:14 +00001860 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001861 addSuccessor(Block, &cfg->getExit());
Mike Stump92244b02010-01-19 22:00:14 +00001862 }
Mike Stump11289f42009-09-09 15:08:12 +00001863
Mike Stump8c5d7992009-07-25 21:26:53 +00001864 return VisitChildren(C);
Ted Kremenek93668002009-07-17 22:18:43 +00001865}
Ted Kremenek9aae5132007-08-23 21:42:29 +00001866
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001867CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
1868 AddStmtChoice asc) {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001869 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001870 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001871 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001872 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001873
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001874 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek21822592009-07-17 18:20:32 +00001875 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001876 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001877 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001878 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001879 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001880
Ted Kremenek21822592009-07-17 18:20:32 +00001881 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001882 Block = nullptr;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001883 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001884 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001885 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001886
Ted Kremenek21822592009-07-17 18:20:32 +00001887 Block = createBlock(false);
Mike Stump773582d2009-07-23 23:25:26 +00001888 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001889 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Craig Topper25542942014-05-20 04:30:07 +00001890 addSuccessor(Block, KnownVal.isFalse() ? nullptr : LHSBlock);
1891 addSuccessor(Block, KnownVal.isTrue() ? nullptr : RHSBlock);
Ted Kremenek21822592009-07-17 18:20:32 +00001892 Block->setTerminator(C);
Mike Stump11289f42009-09-09 15:08:12 +00001893 return addStmt(C->getCond());
Ted Kremenek21822592009-07-17 18:20:32 +00001894}
Mike Stump11289f42009-09-09 15:08:12 +00001895
1896
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001897CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) {
Marcin Swiderski667ffec2010-10-01 00:23:17 +00001898 addLocalScopeAndDtors(C);
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001899 CFGBlock *LastBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00001900
1901 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
1902 I != E; ++I ) {
Ted Kremenek4f2ab5a2010-08-17 21:00:06 +00001903 // If we hit a segment of code just containing ';' (NullStmts), we can
1904 // get a null block back. In such cases, just use the LastBlock
1905 if (CFGBlock *newBlock = addStmt(*I))
1906 LastBlock = newBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001907
Ted Kremenekce499c22009-08-27 23:16:26 +00001908 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001909 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001910 }
Mike Stump92244b02010-01-19 22:00:14 +00001911
Ted Kremenek93668002009-07-17 22:18:43 +00001912 return LastBlock;
1913}
Mike Stump11289f42009-09-09 15:08:12 +00001914
John McCallc07a0c72011-02-17 10:25:35 +00001915CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C,
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00001916 AddStmtChoice asc) {
John McCallc07a0c72011-02-17 10:25:35 +00001917 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C);
Craig Topper25542942014-05-20 04:30:07 +00001918 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : nullptr);
John McCallc07a0c72011-02-17 10:25:35 +00001919
Ted Kremenek51d40b02009-07-17 18:15:54 +00001920 // Create the confluence block that will "merge" the results of the ternary
1921 // expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001922 CFGBlock *ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00001923 appendStmt(ConfluenceBlock, C);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001924 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001925 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001926
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00001927 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true);
Ted Kremenek5868ec62010-04-11 17:02:10 +00001928
Ted Kremenek51d40b02009-07-17 18:15:54 +00001929 // Create a block for the LHS expression if there is an LHS expression. A
1930 // GCC extension allows LHS to be NULL, causing the condition to be the
1931 // value that is returned instead.
1932 // e.g: x ?: y is shorthand for: x ? x : y;
1933 Succ = ConfluenceBlock;
Craig Topper25542942014-05-20 04:30:07 +00001934 Block = nullptr;
1935 CFGBlock *LHSBlock = nullptr;
John McCallc07a0c72011-02-17 10:25:35 +00001936 const Expr *trueExpr = C->getTrueExpr();
1937 if (trueExpr != opaqueValue) {
1938 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001939 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001940 return nullptr;
1941 Block = nullptr;
Ted Kremenek51d40b02009-07-17 18:15:54 +00001942 }
Ted Kremenekd8138012011-02-24 03:09:15 +00001943 else
1944 LHSBlock = ConfluenceBlock;
Mike Stump11289f42009-09-09 15:08:12 +00001945
Ted Kremenek51d40b02009-07-17 18:15:54 +00001946 // Create the block for the RHS expression.
1947 Succ = ConfluenceBlock;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001948 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00001949 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00001950 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001951
Richard Smithf676e452012-07-24 21:02:14 +00001952 // If the condition is a logical '&&' or '||', build a more accurate CFG.
1953 if (BinaryOperator *Cond =
1954 dyn_cast<BinaryOperator>(C->getCond()->IgnoreParens()))
1955 if (Cond->isLogicalOp())
1956 return VisitLogicalOperator(Cond, C, LHSBlock, RHSBlock).first;
1957
Ted Kremenek51d40b02009-07-17 18:15:54 +00001958 // Create the block that will contain the condition.
1959 Block = createBlock(false);
Mike Stump11289f42009-09-09 15:08:12 +00001960
Mike Stump773582d2009-07-23 23:25:26 +00001961 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00001962 const TryResult& KnownVal = tryEvaluateBool(C->getCond());
Ted Kremenek5a095272014-03-04 21:53:26 +00001963 addSuccessor(Block, LHSBlock, !KnownVal.isFalse());
1964 addSuccessor(Block, RHSBlock, !KnownVal.isTrue());
Ted Kremenek51d40b02009-07-17 18:15:54 +00001965 Block->setTerminator(C);
John McCallc07a0c72011-02-17 10:25:35 +00001966 Expr *condExpr = C->getCond();
John McCall68cc3352011-02-19 03:13:26 +00001967
Ted Kremenekd8138012011-02-24 03:09:15 +00001968 if (opaqueValue) {
1969 // Run the condition expression if it's not trivially expressed in
1970 // terms of the opaque value (or if there is no opaque value).
1971 if (condExpr != opaqueValue)
1972 addStmt(condExpr);
John McCall68cc3352011-02-19 03:13:26 +00001973
Ted Kremenekd8138012011-02-24 03:09:15 +00001974 // Before that, run the common subexpression if there was one.
1975 // At least one of this or the above will be run.
1976 return addStmt(BCO->getCommon());
1977 }
1978
1979 return addStmt(condExpr);
Ted Kremenek51d40b02009-07-17 18:15:54 +00001980}
1981
Ted Kremenek93668002009-07-17 22:18:43 +00001982CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek6878c362011-05-10 18:42:15 +00001983 // Check if the Decl is for an __label__. If so, elide it from the
1984 // CFG entirely.
1985 if (isa<LabelDecl>(*DS->decl_begin()))
1986 return Block;
1987
Ted Kremenek3a601142011-05-24 20:41:31 +00001988 // This case also handles static_asserts.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00001989 if (DS->isSingleDecl())
1990 return VisitDeclSubExpr(DS);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Craig Topper25542942014-05-20 04:30:07 +00001992 CFGBlock *B = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001993
Jordan Rose8c6c8a92012-07-20 18:50:48 +00001994 // Build an individual DeclStmt for each decl.
1995 for (DeclStmt::reverse_decl_iterator I = DS->decl_rbegin(),
1996 E = DS->decl_rend();
1997 I != E; ++I) {
Ted Kremenek93668002009-07-17 22:18:43 +00001998 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
1999 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
2000 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Mike Stump11289f42009-09-09 15:08:12 +00002001
Ted Kremenek93668002009-07-17 22:18:43 +00002002 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
2003 // automatically freed with the CFG.
2004 DeclGroupRef DG(*I);
2005 Decl *D = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002006 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
Ted Kremenek93668002009-07-17 22:18:43 +00002007 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Jordan Rosecf10ea82013-06-06 21:53:45 +00002008 cfg->addSyntheticDeclStmt(DSNew, DS);
Mike Stump11289f42009-09-09 15:08:12 +00002009
Ted Kremenek93668002009-07-17 22:18:43 +00002010 // Append the fake DeclStmt to block.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002011 B = VisitDeclSubExpr(DSNew);
Ted Kremenek93668002009-07-17 22:18:43 +00002012 }
Mike Stump11289f42009-09-09 15:08:12 +00002013
2014 return B;
Ted Kremenek93668002009-07-17 22:18:43 +00002015}
Mike Stump11289f42009-09-09 15:08:12 +00002016
Ted Kremenek93668002009-07-17 22:18:43 +00002017/// VisitDeclSubExpr - Utility method to add block-level expressions for
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002018/// DeclStmts and initializers in them.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002019CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002020 assert(DS->isSingleDecl() && "Can handle single declarations only.");
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002021 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002022
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002023 if (!VD) {
Jordan Rose5250b872013-06-03 22:59:41 +00002024 // Of everything that can be declared in a DeclStmt, only VarDecls impact
2025 // runtime semantics.
Ted Kremenek93668002009-07-17 22:18:43 +00002026 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002027 }
Mike Stump11289f42009-09-09 15:08:12 +00002028
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002029 bool HasTemporaries = false;
2030
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002031 // Guard static initializers under a branch.
Craig Topper25542942014-05-20 04:30:07 +00002032 CFGBlock *blockAfterStaticInit = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002033
2034 if (BuildOpts.AddStaticInitBranches && VD->isStaticLocal()) {
2035 // For static variables, we need to create a branch to track
2036 // whether or not they are initialized.
2037 if (Block) {
2038 Succ = Block;
Craig Topper25542942014-05-20 04:30:07 +00002039 Block = nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002040 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002041 return nullptr;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002042 }
2043 blockAfterStaticInit = Succ;
2044 }
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002045
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002046 // Destructors of temporaries in initialization expression should be called
2047 // after initialization finishes.
Ted Kremenek93668002009-07-17 22:18:43 +00002048 Expr *Init = VD->getInit();
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002049 if (Init) {
John McCall5d413782010-12-06 08:20:24 +00002050 HasTemporaries = isa<ExprWithCleanups>(Init);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002051
Jordan Rose6d671cc2012-09-05 22:55:23 +00002052 if (BuildOpts.AddTemporaryDtors && HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002053 // Generate destructors for temporaries in initialization expression.
Manuel Klimekdeb02622014-08-08 07:37:13 +00002054 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00002055 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(),
2056 /*BindToTemporary=*/false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002057 }
2058 }
2059
2060 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002061 appendStmt(Block, DS);
Ted Kremenek213d0532012-03-22 05:57:43 +00002062
2063 // Keep track of the last non-null block, as 'Block' can be nulled out
2064 // if the initializer expression is something like a 'while' in a
2065 // statement-expression.
2066 CFGBlock *LastBlock = Block;
Mike Stump11289f42009-09-09 15:08:12 +00002067
Ted Kremenek93668002009-07-17 22:18:43 +00002068 if (Init) {
Ted Kremenek213d0532012-03-22 05:57:43 +00002069 if (HasTemporaries) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00002070 // For expression with temporaries go directly to subexpression to omit
2071 // generating destructors for the second time.
Ted Kremenek213d0532012-03-22 05:57:43 +00002072 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init);
2073 if (CFGBlock *newBlock = Visit(EC->getSubExpr()))
2074 LastBlock = newBlock;
2075 }
2076 else {
2077 if (CFGBlock *newBlock = Visit(Init))
2078 LastBlock = newBlock;
2079 }
Ted Kremenek93668002009-07-17 22:18:43 +00002080 }
Mike Stump11289f42009-09-09 15:08:12 +00002081
Ted Kremenek93668002009-07-17 22:18:43 +00002082 // If the type of VD is a VLA, then we must process its size expressions.
John McCall424cec92011-01-19 06:33:43 +00002083 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002084 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr())) {
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002085 if (CFGBlock *newBlock = addStmt(VA->getSizeExpr()))
2086 LastBlock = newBlock;
2087 }
Mike Stump11289f42009-09-09 15:08:12 +00002088
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002089 // Remove variable from local scope.
2090 if (ScopePos && VD == *ScopePos)
2091 ++ScopePos;
2092
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002093 CFGBlock *B = LastBlock;
Ted Kremenekf82d5782013-03-29 00:42:56 +00002094 if (blockAfterStaticInit) {
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002095 Succ = B;
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002096 Block = createBlock(false);
2097 Block->setTerminator(DS);
Ted Kremenekf82d5782013-03-29 00:42:56 +00002098 addSuccessor(Block, blockAfterStaticInit);
Ted Kremenek338c3aa2013-03-29 00:09:28 +00002099 addSuccessor(Block, B);
2100 B = Block;
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00002101 }
2102
2103 return B;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002104}
2105
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002106CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00002107 // We may see an if statement in the middle of a basic block, or it may be the
2108 // first statement we are processing. In either case, we create a new basic
2109 // block. First, we create the blocks for the then...else statements, and
2110 // then we create the block containing the if statement. If we were in the
Ted Kremenek0868eea2009-09-24 18:45:41 +00002111 // middle of a block, we stop processing that block. That block is then the
2112 // implicit successor for the "then" and "else" clauses.
Mike Stump31feda52009-07-17 01:31:16 +00002113
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002114 // Save local scope position because in case of condition variable ScopePos
2115 // won't be restored when traversing AST.
2116 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2117
2118 // Create local scope for possible condition variable.
2119 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002120 if (VarDecl *VD = I->getConditionVariable()) {
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002121 LocalScope::const_iterator BeginScopePos = ScopePos;
2122 addLocalScopeForVarDecl(VD);
2123 addAutomaticObjDtors(ScopePos, BeginScopePos, I);
2124 }
2125
Chris Lattner57540c52011-04-15 05:22:18 +00002126 // The block we were processing is now finished. Make it the successor
Mike Stump31feda52009-07-17 01:31:16 +00002127 // block.
2128 if (Block) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002129 Succ = Block;
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002130 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002131 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002132 }
Mike Stump31feda52009-07-17 01:31:16 +00002133
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002134 // Process the false branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002135 CFGBlock *ElseBlock = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002136
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002137 if (Stmt *Else = I->getElse()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002138 SaveAndRestore<CFGBlock*> sv(Succ);
Mike Stump31feda52009-07-17 01:31:16 +00002139
Ted Kremenek9aae5132007-08-23 21:42:29 +00002140 // NULL out Block so that the recursive call to Visit will
Mike Stump31feda52009-07-17 01:31:16 +00002141 // create a new basic block.
Craig Topper25542942014-05-20 04:30:07 +00002142 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002143
2144 // If branch is not a compound statement create implicit scope
2145 // and add destructors.
2146 if (!isa<CompoundStmt>(Else))
2147 addLocalScopeAndDtors(Else);
2148
Ted Kremenek93668002009-07-17 22:18:43 +00002149 ElseBlock = addStmt(Else);
Mike Stump31feda52009-07-17 01:31:16 +00002150
Ted Kremenekbbad8ce2007-08-30 18:13:31 +00002151 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
2152 ElseBlock = sv.get();
Ted Kremenek55957a82009-05-02 00:13:27 +00002153 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002154 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002155 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002156 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002157 }
Mike Stump31feda52009-07-17 01:31:16 +00002158
Ted Kremenek0bcdc982009-07-17 18:04:55 +00002159 // Process the true branch.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002160 CFGBlock *ThenBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002161 {
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002162 Stmt *Then = I->getThen();
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002163 assert(Then);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002164 SaveAndRestore<CFGBlock*> sv(Succ);
Craig Topper25542942014-05-20 04:30:07 +00002165 Block = nullptr;
Marcin Swiderskif883ade2010-10-01 00:52:17 +00002166
2167 // If branch is not a compound statement create implicit scope
2168 // and add destructors.
2169 if (!isa<CompoundStmt>(Then))
2170 addLocalScopeAndDtors(Then);
2171
Ted Kremenek93668002009-07-17 22:18:43 +00002172 ThenBlock = addStmt(Then);
Mike Stump31feda52009-07-17 01:31:16 +00002173
Ted Kremenek1b379512009-04-01 03:52:47 +00002174 if (!ThenBlock) {
2175 // We can reach here if the "then" body has all NullStmts.
2176 // Create an empty block so we can distinguish between true and false
2177 // branches in path-sensitive analyses.
2178 ThenBlock = createBlock(false);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002179 addSuccessor(ThenBlock, sv.get());
Mike Stump31feda52009-07-17 01:31:16 +00002180 } else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002181 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002182 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002183 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002184 }
2185
Ted Kremenekb50e7162012-07-14 05:04:10 +00002186 // Specially handle "if (expr1 || ...)" and "if (expr1 && ...)" by
2187 // having these handle the actual control-flow jump. Note that
2188 // if we introduce a condition variable, e.g. "if (int x = exp1 || exp2)"
2189 // we resort to the old control-flow behavior. This special handling
2190 // removes infeasible paths from the control-flow graph by having the
2191 // control-flow transfer of '&&' or '||' go directly into the then/else
2192 // blocks directly.
2193 if (!I->getConditionVariable())
Richard Smithf676e452012-07-24 21:02:14 +00002194 if (BinaryOperator *Cond =
2195 dyn_cast<BinaryOperator>(I->getCond()->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002196 if (Cond->isLogicalOp())
2197 return VisitLogicalOperator(Cond, I, ThenBlock, ElseBlock).first;
2198
Mike Stump31feda52009-07-17 01:31:16 +00002199 // Now create a new block containing the if statement.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002200 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002201
Ted Kremenek9aae5132007-08-23 21:42:29 +00002202 // Set the terminator of the new block to the If statement.
2203 Block->setTerminator(I);
Mike Stump31feda52009-07-17 01:31:16 +00002204
Mike Stump773582d2009-07-23 23:25:26 +00002205 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002206 const TryResult &KnownVal = tryEvaluateBool(I->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002207
Ted Kremenekf3898612014-02-27 00:24:03 +00002208 // Add the successors. If we know that specific branches are
2209 // unreachable, inform addSuccessor() of that knowledge.
2210 addSuccessor(Block, ThenBlock, /* isReachable = */ !KnownVal.isFalse());
2211 addSuccessor(Block, ElseBlock, /* isReachable = */ !KnownVal.isTrue());
Mike Stump31feda52009-07-17 01:31:16 +00002212
2213 // Add the condition as the last statement in the new block. This may create
2214 // new blocks as the condition may contain control-flow. Any newly created
2215 // blocks will be pointed to be "Block".
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002216 CFGBlock *LastBlock = addStmt(I->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002217
Manuel Klimek75f34c12014-05-05 18:21:06 +00002218 // Finally, if the IfStmt contains a condition variable, add it and its
2219 // initializer to the CFG.
2220 if (const DeclStmt* DS = I->getConditionVariableDeclStmt()) {
2221 autoCreateBlock();
2222 LastBlock = addStmt(const_cast<DeclStmt *>(DS));
Ted Kremeneka7bcbde2009-12-23 04:49:01 +00002223 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002224
Ted Kremeneke6ee6712012-11-13 00:12:13 +00002225 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002226}
Mike Stump31feda52009-07-17 01:31:16 +00002227
2228
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002229CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002230 // If we were in the middle of a block we stop processing that block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002231 //
Mike Stump31feda52009-07-17 01:31:16 +00002232 // NOTE: If a "return" appears in the middle of a block, this means that the
2233 // code afterwards is DEAD (unreachable). We still keep a basic block
2234 // for that code; a simple "mark-and-sweep" from the entry block will be
2235 // able to report such dead blocks.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002236
2237 // Create the new block.
2238 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002239
Marcin Swiderski667ffec2010-10-01 00:23:17 +00002240 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R);
Pavel Labath921e7652013-09-06 08:12:48 +00002241
2242 // If the one of the destructors does not return, we already have the Exit
2243 // block as a successor.
2244 if (!Block->hasNoReturnElement())
2245 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002246
2247 // Add the return statement to the block. This may create new blocks if R
2248 // contains control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002249 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002250}
2251
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002252CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002253 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek93668002009-07-17 22:18:43 +00002254 addStmt(L->getSubStmt());
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002255 CFGBlock *LabelBlock = Block;
Mike Stump31feda52009-07-17 01:31:16 +00002256
Ted Kremenek93668002009-07-17 22:18:43 +00002257 if (!LabelBlock) // This can happen when the body is empty, i.e.
2258 LabelBlock = createBlock(); // scopes that only contains NullStmts.
Mike Stump31feda52009-07-17 01:31:16 +00002259
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002260 assert(LabelMap.find(L->getDecl()) == LabelMap.end() &&
2261 "label already in map");
2262 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002263
2264 // Labels partition blocks, so this is the end of the basic block we were
2265 // processing (L is the block's label). Because this is label (and we have
2266 // already processed the substatement) there is no extra control-flow to worry
2267 // about.
Ted Kremenek71eca012007-08-29 23:20:49 +00002268 LabelBlock->setLabel(L);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002269 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002270 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002271
2272 // We set Block to NULL to allow lazy creation of a new block (if necessary);
Craig Topper25542942014-05-20 04:30:07 +00002273 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002274
Ted Kremenek9aae5132007-08-23 21:42:29 +00002275 // This block is now the implicit successor of other blocks.
2276 Succ = LabelBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002277
Ted Kremenek9aae5132007-08-23 21:42:29 +00002278 return LabelBlock;
2279}
2280
Ted Kremenekda76a942012-04-12 20:34:52 +00002281CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) {
2282 CFGBlock *LastBlock = VisitNoRecurse(E, asc);
2283 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(),
2284 et = E->capture_init_end(); it != et; ++it) {
2285 if (Expr *Init = *it) {
2286 CFGBlock *Tmp = Visit(Init);
Craig Topper25542942014-05-20 04:30:07 +00002287 if (Tmp)
Ted Kremenekda76a942012-04-12 20:34:52 +00002288 LastBlock = Tmp;
2289 }
2290 }
2291 return LastBlock;
2292}
2293
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002294CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) {
Mike Stump31feda52009-07-17 01:31:16 +00002295 // Goto is a control-flow statement. Thus we stop processing the current
2296 // block and create a new one.
Ted Kremenek93668002009-07-17 22:18:43 +00002297
Ted Kremenek9aae5132007-08-23 21:42:29 +00002298 Block = createBlock(false);
2299 Block->setTerminator(G);
Mike Stump31feda52009-07-17 01:31:16 +00002300
2301 // If we already know the mapping to the label block add the successor now.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002302 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
Mike Stump31feda52009-07-17 01:31:16 +00002303
Ted Kremenek9aae5132007-08-23 21:42:29 +00002304 if (I == LabelMap.end())
2305 // We will need to backpatch this block later.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002306 BackpatchBlocks.push_back(JumpSource(Block, ScopePos));
2307 else {
2308 JumpTarget JT = I->second;
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002309 addAutomaticObjDtors(ScopePos, JT.scopePosition, G);
2310 addSuccessor(Block, JT.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002311 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00002312
Mike Stump31feda52009-07-17 01:31:16 +00002313 return Block;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002314}
2315
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002316CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) {
Craig Topper25542942014-05-20 04:30:07 +00002317 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002318
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002319 // Save local scope position because in case of condition variable ScopePos
2320 // won't be restored when traversing AST.
2321 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2322
2323 // Create local scope for init statement and possible condition variable.
2324 // Add destructor for init statement and condition variable.
2325 // Store scope position for continue statement.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002326 if (Stmt *Init = F->getInit())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002327 addLocalScopeForStmt(Init);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002328 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
2329
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002330 if (VarDecl *VD = F->getConditionVariable())
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002331 addLocalScopeForVarDecl(VD);
2332 LocalScope::const_iterator ContinueScopePos = ScopePos;
2333
2334 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F);
2335
Mike Stump014b3ea2009-07-21 01:12:51 +00002336 // "for" is a control-flow statement. Thus we stop processing the current
2337 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002338 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002339 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002340 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002341 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002342 } else
2343 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002344
Ted Kremenek304a9532010-05-21 20:30:15 +00002345 // Save the current value for the break targets.
2346 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002347 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002348 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Ted Kremenek304a9532010-05-21 20:30:15 +00002349
Craig Topper25542942014-05-20 04:30:07 +00002350 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002351
Ted Kremenek9aae5132007-08-23 21:42:29 +00002352 // Now create the loop body.
2353 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002354 assert(F->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002355
Ted Kremenekb50e7162012-07-14 05:04:10 +00002356 // Save the current values for Block, Succ, continue and break targets.
2357 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2358 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002359
Ted Kremenekb50e7162012-07-14 05:04:10 +00002360 // Create an empty block to represent the transition block for looping back
2361 // to the head of the loop. If we have increment code, it will
2362 // go in this block as well.
2363 Block = Succ = TransitionBlock = createBlock(false);
2364 TransitionBlock->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002365
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002366 if (Stmt *I = F->getInc()) {
Mike Stump31feda52009-07-17 01:31:16 +00002367 // Generate increment code in its own basic block. This is the target of
2368 // continue statements.
Ted Kremenek93668002009-07-17 22:18:43 +00002369 Succ = addStmt(I);
Ted Kremenekb0746ca2008-09-04 21:48:47 +00002370 }
Mike Stump31feda52009-07-17 01:31:16 +00002371
Ted Kremenek902393b2009-04-28 00:51:56 +00002372 // Finish up the increment (or empty) block if it hasn't been already.
2373 if (Block) {
2374 assert(Block == Succ);
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002375 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002376 return nullptr;
2377 Block = nullptr;
Ted Kremenek902393b2009-04-28 00:51:56 +00002378 }
Mike Stump31feda52009-07-17 01:31:16 +00002379
Ted Kremenekb50e7162012-07-14 05:04:10 +00002380 // The starting block for the loop increment is the block that should
2381 // represent the 'loop target' for looping back to the start of the loop.
2382 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
2383 ContinueJumpTarget.block->setLoopTarget(F);
Mike Stump31feda52009-07-17 01:31:16 +00002384
Ted Kremenekb50e7162012-07-14 05:04:10 +00002385 // Loop body should end with destructor of Condition variable (if any).
2386 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F);
Ted Kremenek902393b2009-04-28 00:51:56 +00002387
Marcin Swiderski6d5ee0c2010-10-01 01:38:14 +00002388 // If body is not a compound statement create implicit scope
2389 // and add destructors.
2390 if (!isa<CompoundStmt>(F->getBody()))
2391 addLocalScopeAndDtors(F->getBody());
2392
Mike Stump31feda52009-07-17 01:31:16 +00002393 // Now populate the body block, and in the process create new blocks as we
2394 // walk the body of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002395 BodyBlock = addStmt(F->getBody());
Ted Kremeneke9610502007-08-30 18:39:40 +00002396
Ted Kremenekb50e7162012-07-14 05:04:10 +00002397 if (!BodyBlock) {
2398 // In the case of "for (...;...;...);" we can have a null BodyBlock.
2399 // Use the continue jump target as the proxy for the body.
2400 BodyBlock = ContinueJumpTarget.block;
2401 }
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002402 else if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002403 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002404 }
Ted Kremenekb50e7162012-07-14 05:04:10 +00002405
2406 // Because of short-circuit evaluation, the condition of the loop can span
2407 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2408 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002409 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002410
Ted Kremenekb50e7162012-07-14 05:04:10 +00002411 do {
2412 Expr *C = F->getCond();
2413
2414 // Specially handle logical operators, which have a slightly
2415 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002416 if (BinaryOperator *Cond =
Craig Topper25542942014-05-20 04:30:07 +00002417 dyn_cast_or_null<BinaryOperator>(C ? C->IgnoreParens() : nullptr))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002418 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002419 std::tie(EntryConditionBlock, ExitConditionBlock) =
Ted Kremenekb50e7162012-07-14 05:04:10 +00002420 VisitLogicalOperator(Cond, F, BodyBlock, LoopSuccessor);
2421 break;
2422 }
2423
2424 // The default case when not handling logical operators.
2425 EntryConditionBlock = ExitConditionBlock = createBlock(false);
2426 ExitConditionBlock->setTerminator(F);
2427
2428 // See if this is a known constant.
2429 TryResult KnownVal(true);
2430
2431 if (C) {
2432 // Now add the actual condition to the condition block.
2433 // Because the condition itself may contain control-flow, new blocks may
2434 // be created. Thus we update "Succ" after adding the condition.
2435 Block = ExitConditionBlock;
2436 EntryConditionBlock = addStmt(C);
2437
2438 // If this block contains a condition variable, add both the condition
2439 // variable and initializer to the CFG.
2440 if (VarDecl *VD = F->getConditionVariable()) {
2441 if (Expr *Init = VD->getInit()) {
2442 autoCreateBlock();
2443 appendStmt(Block, F->getConditionVariableDeclStmt());
2444 EntryConditionBlock = addStmt(Init);
2445 assert(Block == EntryConditionBlock);
2446 }
2447 }
2448
2449 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002450 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002451
2452 KnownVal = tryEvaluateBool(C);
2453 }
2454
2455 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002456 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002457 // Link up the condition block with the code that follows the loop. (the
2458 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002459 addSuccessor(ExitConditionBlock,
2460 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002461
2462 } while (false);
2463
2464 // Link up the loop-back block to the entry condition block.
2465 addSuccessor(TransitionBlock, EntryConditionBlock);
2466
2467 // The condition block is the implicit successor for any code above the loop.
2468 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002469
Ted Kremenek9aae5132007-08-23 21:42:29 +00002470 // If the loop contains initialization, create a new block for those
Mike Stump31feda52009-07-17 01:31:16 +00002471 // statements. This block can also contain statements that precede the loop.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002472 if (Stmt *I = F->getInit()) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002473 Block = createBlock();
Ted Kremenek81e14852007-08-27 19:46:09 +00002474 return addStmt(I);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002475 }
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002476
2477 // There is no loop initialization. We are thus basically a while loop.
2478 // NULL out Block to force lazy block construction.
Craig Topper25542942014-05-20 04:30:07 +00002479 Block = nullptr;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00002480 Succ = EntryConditionBlock;
2481 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002482}
2483
Ted Kremenek5868ec62010-04-11 17:02:10 +00002484CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002485 if (asc.alwaysAdd(*this, M)) {
Ted Kremenek5868ec62010-04-11 17:02:10 +00002486 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002487 appendStmt(Block, M);
Ted Kremenek5868ec62010-04-11 17:02:10 +00002488 }
Ted Kremenek8219b822010-12-16 07:46:53 +00002489 return Visit(M->getBase());
Ted Kremenek5868ec62010-04-11 17:02:10 +00002490}
2491
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002492CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Ted Kremenek9d56e642008-11-11 17:10:00 +00002493 // Objective-C fast enumeration 'for' statements:
2494 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
2495 //
2496 // for ( Type newVariable in collection_expression ) { statements }
2497 //
2498 // becomes:
2499 //
2500 // prologue:
2501 // 1. collection_expression
2502 // T. jump to loop_entry
2503 // loop_entry:
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002504 // 1. side-effects of element expression
Ted Kremenek9d56e642008-11-11 17:10:00 +00002505 // 1. ObjCForCollectionStmt [performs binding to newVariable]
2506 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
2507 // TB:
2508 // statements
2509 // T. jump to loop_entry
2510 // FB:
2511 // what comes after
2512 //
2513 // and
2514 //
2515 // Type existingItem;
2516 // for ( existingItem in expression ) { statements }
2517 //
2518 // becomes:
2519 //
Mike Stump31feda52009-07-17 01:31:16 +00002520 // the same with newVariable replaced with existingItem; the binding works
2521 // the same except that for one ObjCForCollectionStmt::getElement() returns
2522 // a DeclStmt and the other returns a DeclRefExpr.
Ted Kremenek9d56e642008-11-11 17:10:00 +00002523 //
Mike Stump31feda52009-07-17 01:31:16 +00002524
Craig Topper25542942014-05-20 04:30:07 +00002525 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002526
Ted Kremenek9d56e642008-11-11 17:10:00 +00002527 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002528 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002529 return nullptr;
Ted Kremenek9d56e642008-11-11 17:10:00 +00002530 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002531 Block = nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00002532 } else
2533 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002534
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002535 // Build the condition blocks.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002536 CFGBlock *ExitConditionBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002537
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002538 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002539 ExitConditionBlock->setTerminator(S);
2540
2541 // The last statement in the block should be the ObjCForCollectionStmt, which
2542 // performs the actual binding to 'element' and determines if there are any
2543 // more items in the collection.
Ted Kremenek8219b822010-12-16 07:46:53 +00002544 appendStmt(ExitConditionBlock, S);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002545 Block = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002546
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002547 // Walk the 'element' expression to see if there are any side-effects. We
Chris Lattner57540c52011-04-15 05:22:18 +00002548 // generate new blocks as necessary. We DON'T add the statement by default to
Mike Stump31feda52009-07-17 01:31:16 +00002549 // the CFG unless it contains control-flow.
Ted Kremenekc14efa72011-08-17 21:04:19 +00002550 CFGBlock *EntryConditionBlock = Visit(S->getElement(),
2551 AddStmtChoice::NotAlwaysAdd);
Mike Stump31feda52009-07-17 01:31:16 +00002552 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002553 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002554 return nullptr;
2555 Block = nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002556 }
Mike Stump31feda52009-07-17 01:31:16 +00002557
2558 // The condition block is the implicit successor for the loop body as well as
2559 // any code above the loop.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002560 Succ = EntryConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002561
Ted Kremenek9d56e642008-11-11 17:10:00 +00002562 // Now create the true branch.
Mike Stump31feda52009-07-17 01:31:16 +00002563 {
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002564 // Save the current values for Succ, continue and break targets.
Anna Zaks56b49752013-06-22 00:23:20 +00002565 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002566 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Anna Zaks56b49752013-06-22 00:23:20 +00002567 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002568
Anna Zaks56b49752013-06-22 00:23:20 +00002569 // Add an intermediate block between the BodyBlock and the
2570 // EntryConditionBlock to represent the "loop back" transition, for looping
2571 // back to the head of the loop.
Craig Topper25542942014-05-20 04:30:07 +00002572 CFGBlock *LoopBackBlock = nullptr;
Anna Zaks56b49752013-06-22 00:23:20 +00002573 Succ = LoopBackBlock = createBlock();
2574 LoopBackBlock->setLoopTarget(S);
2575
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002576 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Anna Zaks56b49752013-06-22 00:23:20 +00002577 ContinueJumpTarget = JumpTarget(Succ, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002578
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002579 CFGBlock *BodyBlock = addStmt(S->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002580
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002581 if (!BodyBlock)
Anna Zaks56b49752013-06-22 00:23:20 +00002582 BodyBlock = ContinueJumpTarget.block; // can happen for "for (X in Y) ;"
Ted Kremenek55957a82009-05-02 00:13:27 +00002583 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002584 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002585 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002586 }
Mike Stump31feda52009-07-17 01:31:16 +00002587
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002588 // This new body block is a successor to our "exit" condition block.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002589 addSuccessor(ExitConditionBlock, BodyBlock);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002590 }
Mike Stump31feda52009-07-17 01:31:16 +00002591
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002592 // Link up the condition block with the code that follows the loop.
2593 // (the false branch).
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002594 addSuccessor(ExitConditionBlock, LoopSuccessor);
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002595
Ted Kremenek9d56e642008-11-11 17:10:00 +00002596 // Now create a prologue block to contain the collection expression.
Ted Kremenek5cf87ff2008-11-14 01:57:41 +00002597 Block = createBlock();
Ted Kremenek9d56e642008-11-11 17:10:00 +00002598 return addStmt(S->getCollection());
Mike Stump31feda52009-07-17 01:31:16 +00002599}
2600
Ted Kremenek5022f1d2012-03-06 23:40:47 +00002601CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
2602 // Inline the body.
2603 return addStmt(S->getSubStmt());
2604 // TODO: consider adding cleanups for the end of @autoreleasepool scope.
2605}
2606
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002607CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Ted Kremenek49805452009-05-02 01:49:13 +00002608 // FIXME: Add locking 'primitives' to CFG for @synchronized.
Mike Stump31feda52009-07-17 01:31:16 +00002609
Ted Kremenek49805452009-05-02 01:49:13 +00002610 // Inline the body.
Ted Kremenek93668002009-07-17 22:18:43 +00002611 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
Mike Stump31feda52009-07-17 01:31:16 +00002612
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002613 // The sync body starts its own basic block. This makes it a little easier
2614 // for diagnostic clients.
2615 if (SyncBlock) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002616 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002617 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002618
Craig Topper25542942014-05-20 04:30:07 +00002619 Block = nullptr;
Ted Kremenekecc31c92010-05-13 16:38:08 +00002620 Succ = SyncBlock;
Ted Kremenekb3c657b2009-05-05 23:11:51 +00002621 }
Mike Stump31feda52009-07-17 01:31:16 +00002622
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002623 // Add the @synchronized to the CFG.
2624 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00002625 appendStmt(Block, S);
Ted Kremeneked12f1b2010-09-10 03:05:33 +00002626
Ted Kremenek49805452009-05-02 01:49:13 +00002627 // Inline the sync expression.
Ted Kremenek93668002009-07-17 22:18:43 +00002628 return addStmt(S->getSynchExpr());
Ted Kremenek49805452009-05-02 01:49:13 +00002629}
Mike Stump31feda52009-07-17 01:31:16 +00002630
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002631CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002632 // FIXME
Ted Kremenek89be6522009-04-07 04:26:02 +00002633 return NYS();
Ted Kremenek89cc8ea2009-03-30 22:29:21 +00002634}
Ted Kremenek9d56e642008-11-11 17:10:00 +00002635
John McCallfe96e0b2011-11-06 09:01:30 +00002636CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) {
2637 autoCreateBlock();
2638
2639 // Add the PseudoObject as the last thing.
2640 appendStmt(Block, E);
2641
2642 CFGBlock *lastBlock = Block;
2643
2644 // Before that, evaluate all of the semantics in order. In
2645 // CFG-land, that means appending them in reverse order.
2646 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) {
2647 Expr *Semantic = E->getSemanticExpr(--i);
2648
2649 // If the semantic is an opaque value, we're being asked to bind
2650 // it to its source expression.
2651 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
2652 Semantic = OVE->getSourceExpr();
2653
2654 if (CFGBlock *B = Visit(Semantic))
2655 lastBlock = B;
2656 }
2657
2658 return lastBlock;
2659}
2660
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002661CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) {
Craig Topper25542942014-05-20 04:30:07 +00002662 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002663
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002664 // Save local scope position because in case of condition variable ScopePos
2665 // won't be restored when traversing AST.
2666 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2667
2668 // Create local scope for possible condition variable.
2669 // Store scope position for continue statement.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002670 LocalScope::const_iterator LoopBeginScopePos = ScopePos;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002671 if (VarDecl *VD = W->getConditionVariable()) {
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002672 addLocalScopeForVarDecl(VD);
2673 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2674 }
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002675
Mike Stump014b3ea2009-07-21 01:12:51 +00002676 // "while" is a control-flow statement. Thus we stop processing the current
2677 // block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002678 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002679 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002680 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002681 LoopSuccessor = Block;
Craig Topper25542942014-05-20 04:30:07 +00002682 Block = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002683 } else {
Ted Kremenek93668002009-07-17 22:18:43 +00002684 LoopSuccessor = Succ;
Ted Kremenek81e14852007-08-27 19:46:09 +00002685 }
Mike Stump31feda52009-07-17 01:31:16 +00002686
Craig Topper25542942014-05-20 04:30:07 +00002687 CFGBlock *BodyBlock = nullptr, *TransitionBlock = nullptr;
Mike Stump773582d2009-07-23 23:25:26 +00002688
Ted Kremenek9aae5132007-08-23 21:42:29 +00002689 // Process the loop body.
2690 {
Ted Kremenek49936f72009-04-28 03:09:44 +00002691 assert(W->getBody());
Ted Kremenek9aae5132007-08-23 21:42:29 +00002692
Ted Kremenekb50e7162012-07-14 05:04:10 +00002693 // Save the current values for Block, Succ, continue and break targets.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002694 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2695 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
Ted Kremenekb50e7162012-07-14 05:04:10 +00002696 save_break(BreakJumpTarget);
Ted Kremenek49936f72009-04-28 03:09:44 +00002697
Mike Stump31feda52009-07-17 01:31:16 +00002698 // Create an empty block to represent the transition block for looping back
2699 // to the head of the loop.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002700 Succ = TransitionBlock = createBlock(false);
2701 TransitionBlock->setLoopTarget(W);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002702 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002703
Ted Kremenek9aae5132007-08-23 21:42:29 +00002704 // All breaks should go to the code following the loop.
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002705 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002706
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002707 // Loop body should end with destructor of Condition variable (if any).
2708 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W);
2709
2710 // If body is not a compound statement create implicit scope
2711 // and add destructors.
2712 if (!isa<CompoundStmt>(W->getBody()))
2713 addLocalScopeAndDtors(W->getBody());
2714
Ted Kremenek9aae5132007-08-23 21:42:29 +00002715 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekb50e7162012-07-14 05:04:10 +00002716 BodyBlock = addStmt(W->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002717
Ted Kremeneke9610502007-08-30 18:39:40 +00002718 if (!BodyBlock)
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002719 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;"
Ted Kremenekb50e7162012-07-14 05:04:10 +00002720 else if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002721 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002722 }
2723
2724 // Because of short-circuit evaluation, the condition of the loop can span
2725 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2726 // evaluate the condition.
Craig Topper25542942014-05-20 04:30:07 +00002727 CFGBlock *EntryConditionBlock = nullptr, *ExitConditionBlock = nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002728
2729 do {
2730 Expr *C = W->getCond();
2731
2732 // Specially handle logical operators, which have a slightly
2733 // more optimal CFG representation.
Richard Smithf676e452012-07-24 21:02:14 +00002734 if (BinaryOperator *Cond = dyn_cast<BinaryOperator>(C->IgnoreParens()))
Ted Kremenekb50e7162012-07-14 05:04:10 +00002735 if (Cond->isLogicalOp()) {
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002736 std::tie(EntryConditionBlock, ExitConditionBlock) =
2737 VisitLogicalOperator(Cond, W, BodyBlock, LoopSuccessor);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002738 break;
2739 }
2740
2741 // The default case when not handling logical operators.
Ted Kremenek451c4d52012-10-12 22:56:26 +00002742 ExitConditionBlock = createBlock(false);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002743 ExitConditionBlock->setTerminator(W);
2744
2745 // Now add the actual condition to the condition block.
2746 // Because the condition itself may contain control-flow, new blocks may
2747 // be created. Thus we update "Succ" after adding the condition.
2748 Block = ExitConditionBlock;
2749 Block = EntryConditionBlock = addStmt(C);
2750
2751 // If this block contains a condition variable, add both the condition
2752 // variable and initializer to the CFG.
2753 if (VarDecl *VD = W->getConditionVariable()) {
2754 if (Expr *Init = VD->getInit()) {
2755 autoCreateBlock();
2756 appendStmt(Block, W->getConditionVariableDeclStmt());
2757 EntryConditionBlock = addStmt(Init);
2758 assert(Block == EntryConditionBlock);
2759 }
Ted Kremenek55957a82009-05-02 00:13:27 +00002760 }
Mike Stump31feda52009-07-17 01:31:16 +00002761
Ted Kremenekb50e7162012-07-14 05:04:10 +00002762 if (Block && badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002763 return nullptr;
Ted Kremenekb50e7162012-07-14 05:04:10 +00002764
2765 // See if this is a known constant.
2766 const TryResult& KnownVal = tryEvaluateBool(C);
2767
Ted Kremenek30754282009-07-24 04:47:11 +00002768 // Add the loop body entry as a successor to the condition.
Craig Topper25542942014-05-20 04:30:07 +00002769 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? nullptr : BodyBlock);
Ted Kremenekb50e7162012-07-14 05:04:10 +00002770 // Link up the condition block with the code that follows the loop. (the
2771 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00002772 addSuccessor(ExitConditionBlock,
2773 KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002774
Ted Kremenekb50e7162012-07-14 05:04:10 +00002775 } while(false);
2776
2777 // Link up the loop-back block to the entry condition block.
2778 addSuccessor(TransitionBlock, EntryConditionBlock);
Mike Stump31feda52009-07-17 01:31:16 +00002779
2780 // There can be no more statements in the condition block since we loop back
2781 // to this block. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002782 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002783
Ted Kremenek1ce53c42009-12-24 01:34:10 +00002784 // Return the condition block, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002785 Succ = EntryConditionBlock;
Ted Kremenek81e14852007-08-27 19:46:09 +00002786 return EntryConditionBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002787}
Mike Stump11289f42009-09-09 15:08:12 +00002788
2789
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002790CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
Ted Kremenek93668002009-07-17 22:18:43 +00002791 // FIXME: For now we pretend that @catch and the code it contains does not
2792 // exit.
2793 return Block;
2794}
Mike Stump31feda52009-07-17 01:31:16 +00002795
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002796CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
Ted Kremenek93041ba2008-12-09 20:20:09 +00002797 // FIXME: This isn't complete. We basically treat @throw like a return
2798 // statement.
Mike Stump31feda52009-07-17 01:31:16 +00002799
Ted Kremenek0868eea2009-09-24 18:45:41 +00002800 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002801 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002802 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002803
Ted Kremenek93041ba2008-12-09 20:20:09 +00002804 // Create the new block.
2805 Block = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00002806
Ted Kremenek93041ba2008-12-09 20:20:09 +00002807 // The Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002808 addSuccessor(Block, &cfg->getExit());
Mike Stump31feda52009-07-17 01:31:16 +00002809
2810 // Add the statement to the block. This may create new blocks if S contains
2811 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002812 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
Ted Kremenek93041ba2008-12-09 20:20:09 +00002813}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002814
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002815CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) {
Ted Kremenek0868eea2009-09-24 18:45:41 +00002816 // If we were in the middle of a block we stop processing that block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002817 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002818 return nullptr;
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002819
2820 // Create the new block.
2821 Block = createBlock(false);
2822
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002823 if (TryTerminatedBlock)
2824 // The current try statement is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002825 addSuccessor(Block, TryTerminatedBlock);
Ted Kremenekdc03bd02010-08-02 23:46:59 +00002826 else
Mike Stumpbbf5ba62010-01-19 02:20:09 +00002827 // otherwise the Exit block is the only successor.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002828 addSuccessor(Block, &cfg->getExit());
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002829
2830 // Add the statement to the block. This may create new blocks if S contains
2831 // control-flow (short-circuit operations).
Ted Kremenek4cad5fc2009-12-16 03:18:58 +00002832 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
Mike Stump8dd1b6b2009-07-22 22:56:04 +00002833}
2834
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002835CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) {
Craig Topper25542942014-05-20 04:30:07 +00002836 CFGBlock *LoopSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002837
Mike Stump8d50b6a2009-07-21 01:27:50 +00002838 // "do...while" is a control-flow statement. Thus we stop processing the
2839 // current block.
Ted Kremenek9aae5132007-08-23 21:42:29 +00002840 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002841 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002842 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002843 LoopSuccessor = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00002844 } else
2845 LoopSuccessor = Succ;
Mike Stump31feda52009-07-17 01:31:16 +00002846
2847 // Because of short-circuit evaluation, the condition of the loop can span
2848 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
2849 // evaluate the condition.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002850 CFGBlock *ExitConditionBlock = createBlock(false);
2851 CFGBlock *EntryConditionBlock = ExitConditionBlock;
Mike Stump31feda52009-07-17 01:31:16 +00002852
Ted Kremenek81e14852007-08-27 19:46:09 +00002853 // Set the terminator for the "exit" condition block.
Mike Stump31feda52009-07-17 01:31:16 +00002854 ExitConditionBlock->setTerminator(D);
2855
2856 // Now add the actual condition to the condition block. Because the condition
2857 // itself may contain control-flow, new blocks may be created.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002858 if (Stmt *C = D->getCond()) {
Ted Kremenek81e14852007-08-27 19:46:09 +00002859 Block = ExitConditionBlock;
2860 EntryConditionBlock = addStmt(C);
Ted Kremenek55957a82009-05-02 00:13:27 +00002861 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002862 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002863 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002864 }
Ted Kremenek81e14852007-08-27 19:46:09 +00002865 }
Mike Stump31feda52009-07-17 01:31:16 +00002866
Ted Kremeneka1523a32008-02-27 07:20:00 +00002867 // The condition block is the implicit successor for the loop body.
Ted Kremenek81e14852007-08-27 19:46:09 +00002868 Succ = EntryConditionBlock;
2869
Mike Stump773582d2009-07-23 23:25:26 +00002870 // See if this is a known constant.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002871 const TryResult &KnownVal = tryEvaluateBool(D->getCond());
Mike Stump773582d2009-07-23 23:25:26 +00002872
Ted Kremenek9aae5132007-08-23 21:42:29 +00002873 // Process the loop body.
Craig Topper25542942014-05-20 04:30:07 +00002874 CFGBlock *BodyBlock = nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002875 {
Ted Kremenek1362b8b2010-01-19 20:46:35 +00002876 assert(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002877
Ted Kremenek9aae5132007-08-23 21:42:29 +00002878 // Save the current values for Block, Succ, and continue and break targets
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002879 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
2880 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget),
2881 save_break(BreakJumpTarget);
Mike Stump31feda52009-07-17 01:31:16 +00002882
Ted Kremenek9aae5132007-08-23 21:42:29 +00002883 // All continues within this loop should go to the condition block
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002884 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002885
Ted Kremenek9aae5132007-08-23 21:42:29 +00002886 // All breaks should go to the code following the loop.
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002887 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00002888
Ted Kremenek9aae5132007-08-23 21:42:29 +00002889 // NULL out Block to force lazy instantiation of blocks for the body.
Craig Topper25542942014-05-20 04:30:07 +00002890 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002891
Marcin Swiderski1f4e15c2010-10-01 01:14:17 +00002892 // If body is not a compound statement create implicit scope
2893 // and add destructors.
2894 if (!isa<CompoundStmt>(D->getBody()))
2895 addLocalScopeAndDtors(D->getBody());
2896
Ted Kremenek9aae5132007-08-23 21:42:29 +00002897 // Create the body. The returned block is the entry to the loop body.
Ted Kremenek93668002009-07-17 22:18:43 +00002898 BodyBlock = addStmt(D->getBody());
Mike Stump31feda52009-07-17 01:31:16 +00002899
Ted Kremeneke9610502007-08-30 18:39:40 +00002900 if (!BodyBlock)
Ted Kremenek39321aa2008-02-27 00:28:17 +00002901 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek55957a82009-05-02 00:13:27 +00002902 else if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002903 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002904 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00002905 }
Mike Stump31feda52009-07-17 01:31:16 +00002906
Ted Kremenek110974d2010-08-17 20:59:56 +00002907 if (!KnownVal.isFalse()) {
2908 // Add an intermediate block between the BodyBlock and the
2909 // ExitConditionBlock to represent the "loop back" transition. Create an
2910 // empty block to represent the transition block for looping back to the
2911 // head of the loop.
2912 // FIXME: Can we do this more efficiently without adding another block?
Craig Topper25542942014-05-20 04:30:07 +00002913 Block = nullptr;
Ted Kremenek110974d2010-08-17 20:59:56 +00002914 Succ = BodyBlock;
2915 CFGBlock *LoopBackBlock = createBlock();
2916 LoopBackBlock->setLoopTarget(D);
Mike Stump31feda52009-07-17 01:31:16 +00002917
Ted Kremenek110974d2010-08-17 20:59:56 +00002918 // Add the loop body entry as a successor to the condition.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00002919 addSuccessor(ExitConditionBlock, LoopBackBlock);
Ted Kremenek110974d2010-08-17 20:59:56 +00002920 }
2921 else
Craig Topper25542942014-05-20 04:30:07 +00002922 addSuccessor(ExitConditionBlock, nullptr);
Ted Kremenek9aae5132007-08-23 21:42:29 +00002923 }
Mike Stump31feda52009-07-17 01:31:16 +00002924
Ted Kremenek30754282009-07-24 04:47:11 +00002925 // Link up the condition block with the code that follows the loop.
2926 // (the false branch).
Craig Topper25542942014-05-20 04:30:07 +00002927 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00002928
2929 // There can be no more statements in the body block(s) since we loop back to
2930 // the body. NULL out Block to force lazy creation of another block.
Craig Topper25542942014-05-20 04:30:07 +00002931 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002932
Ted Kremenek9aae5132007-08-23 21:42:29 +00002933 // Return the loop body, which is the dominating block for the loop.
Ted Kremeneka1523a32008-02-27 07:20:00 +00002934 Succ = BodyBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002935 return BodyBlock;
2936}
2937
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002938CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00002939 // "continue" is a control-flow statement. Thus we stop processing the
2940 // current block.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00002941 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00002942 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002943
Ted Kremenek9aae5132007-08-23 21:42:29 +00002944 // Now create a new block that ends with the continue statement.
2945 Block = createBlock(false);
2946 Block->setTerminator(C);
Mike Stump31feda52009-07-17 01:31:16 +00002947
Ted Kremenek9aae5132007-08-23 21:42:29 +00002948 // If there is no target for the continue, then we are looking at an
Ted Kremenek882cf062009-04-07 18:53:24 +00002949 // incomplete AST. This means the CFG cannot be constructed.
Ted Kremenekef81e9e2011-01-07 19:37:16 +00002950 if (ContinueJumpTarget.block) {
2951 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C);
2952 addSuccessor(Block, ContinueJumpTarget.block);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00002953 } else
Ted Kremenek882cf062009-04-07 18:53:24 +00002954 badCFG = true;
Mike Stump31feda52009-07-17 01:31:16 +00002955
Ted Kremenek9aae5132007-08-23 21:42:29 +00002956 return Block;
2957}
Mike Stump11289f42009-09-09 15:08:12 +00002958
Peter Collingbournee190dee2011-03-11 19:24:49 +00002959CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E,
2960 AddStmtChoice asc) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002961
Ted Kremenek7c58d352011-03-10 01:14:11 +00002962 if (asc.alwaysAdd(*this, E)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002963 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002964 appendStmt(Block, E);
Ted Kremenek0747de62009-07-18 00:47:21 +00002965 }
Mike Stump11289f42009-09-09 15:08:12 +00002966
Ted Kremenek93668002009-07-17 22:18:43 +00002967 // VLA types have expressions that must be evaluated.
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002968 CFGBlock *lastBlock = Block;
2969
Ted Kremenek93668002009-07-17 22:18:43 +00002970 if (E->isArgumentType()) {
John McCall424cec92011-01-19 06:33:43 +00002971 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr());
Craig Topper25542942014-05-20 04:30:07 +00002972 VA != nullptr; VA = FindVA(VA->getElementType().getTypePtr()))
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002973 lastBlock = addStmt(VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +00002974 }
Ted Kremenek9eb0b7d2011-04-14 01:50:50 +00002975 return lastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00002976}
Mike Stump11289f42009-09-09 15:08:12 +00002977
Ted Kremenek93668002009-07-17 22:18:43 +00002978/// VisitStmtExpr - Utility method to handle (nested) statement
2979/// expressions (a GCC extension).
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002980CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00002981 if (asc.alwaysAdd(*this, SE)) {
Ted Kremenek0747de62009-07-18 00:47:21 +00002982 autoCreateBlock();
Ted Kremenek8219b822010-12-16 07:46:53 +00002983 appendStmt(Block, SE);
Ted Kremenek0747de62009-07-18 00:47:21 +00002984 }
Ted Kremenek93668002009-07-17 22:18:43 +00002985 return VisitCompoundStmt(SE->getSubStmt());
2986}
Ted Kremenek9aae5132007-08-23 21:42:29 +00002987
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002988CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00002989 // "switch" is a control-flow statement. Thus we stop processing the current
2990 // block.
Craig Topper25542942014-05-20 04:30:07 +00002991 CFGBlock *SwitchSuccessor = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00002992
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00002993 // Save local scope position because in case of condition variable ScopePos
2994 // won't be restored when traversing AST.
2995 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
2996
2997 // Create local scope for possible condition variable.
2998 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00002999 if (VarDecl *VD = Terminator->getConditionVariable()) {
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003000 LocalScope::const_iterator SwitchBeginScopePos = ScopePos;
3001 addLocalScopeForVarDecl(VD);
3002 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator);
3003 }
3004
Ted Kremenek9aae5132007-08-23 21:42:29 +00003005 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003006 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003007 return nullptr;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003008 SwitchSuccessor = Block;
Mike Stump31feda52009-07-17 01:31:16 +00003009 } else SwitchSuccessor = Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003010
3011 // Save the current "switch" context.
3012 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek654c78f2008-02-13 22:05:39 +00003013 save_default(DefaultCaseBlock);
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003014 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
Ted Kremenek654c78f2008-02-13 22:05:39 +00003015
Mike Stump31feda52009-07-17 01:31:16 +00003016 // Set the "default" case to be the block after the switch statement. If the
3017 // switch statement contains a "default:", this value will be overwritten with
3018 // the block for that code.
Ted Kremenek654c78f2008-02-13 22:05:39 +00003019 DefaultCaseBlock = SwitchSuccessor;
Mike Stump31feda52009-07-17 01:31:16 +00003020
Ted Kremenek9aae5132007-08-23 21:42:29 +00003021 // Create a new block that will contain the switch statement.
3022 SwitchTerminatedBlock = createBlock(false);
Mike Stump31feda52009-07-17 01:31:16 +00003023
Ted Kremenek9aae5132007-08-23 21:42:29 +00003024 // Now process the switch body. The code after the switch is the implicit
3025 // successor.
3026 Succ = SwitchSuccessor;
Marcin Swiderski8b99b8a2010-09-25 11:05:21 +00003027 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos);
Mike Stump31feda52009-07-17 01:31:16 +00003028
3029 // When visiting the body, the case statements should automatically get linked
3030 // up to the switch. We also don't keep a pointer to the body, since all
3031 // control-flow from the switch goes to case/default statements.
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003032 assert(Terminator->getBody() && "switch must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003033 Block = nullptr;
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003034
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003035 // For pruning unreachable case statements, save the current state
3036 // for tracking the condition value.
3037 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered,
3038 false);
Ted Kremenekbe528712011-03-04 01:03:41 +00003039
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003040 // Determine if the switch condition can be explicitly evaluated.
3041 assert(Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekbe528712011-03-04 01:03:41 +00003042 Expr::EvalResult result;
Ted Kremenek53e65382011-03-13 03:48:04 +00003043 bool b = tryEvaluate(Terminator->getCond(), result);
3044 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond,
Craig Topper25542942014-05-20 04:30:07 +00003045 b ? &result : nullptr);
Ted Kremenekbe528712011-03-04 01:03:41 +00003046
Marcin Swiderskie407a3b2010-10-01 01:24:41 +00003047 // If body is not a compound statement create implicit scope
3048 // and add destructors.
3049 if (!isa<CompoundStmt>(Terminator->getBody()))
3050 addLocalScopeAndDtors(Terminator->getBody());
3051
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003052 addStmt(Terminator->getBody());
Ted Kremenek55957a82009-05-02 00:13:27 +00003053 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003054 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003055 return nullptr;
Ted Kremenek55957a82009-05-02 00:13:27 +00003056 }
Ted Kremenek81e14852007-08-27 19:46:09 +00003057
Mike Stump31feda52009-07-17 01:31:16 +00003058 // If we have no "default:" case, the default transition is to the code
Ted Kremenek35c70f62011-03-16 04:32:01 +00003059 // following the switch body. Moreover, take into account if all the
3060 // cases of a switch are covered (e.g., switching on an enum value).
David Majnemerf69ce862013-06-04 17:38:44 +00003061 //
3062 // Note: We add a successor to a switch that is considered covered yet has no
3063 // case statements if the enumeration has no enumerators.
3064 bool SwitchAlwaysHasSuccessor = false;
3065 SwitchAlwaysHasSuccessor |= switchExclusivelyCovered;
3066 SwitchAlwaysHasSuccessor |= Terminator->isAllEnumCasesCovered() &&
3067 Terminator->getSwitchCaseList();
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003068 addSuccessor(SwitchTerminatedBlock, DefaultCaseBlock,
3069 !SwitchAlwaysHasSuccessor);
Mike Stump31feda52009-07-17 01:31:16 +00003070
Ted Kremenek81e14852007-08-27 19:46:09 +00003071 // Add the terminator and condition in the switch block.
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003072 SwitchTerminatedBlock->setTerminator(Terminator);
Ted Kremenek9aae5132007-08-23 21:42:29 +00003073 Block = SwitchTerminatedBlock;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003074 CFGBlock *LastBlock = addStmt(Terminator->getCond());
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003075
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003076 // Finally, if the SwitchStmt contains a condition variable, add both the
3077 // SwitchStmt and the condition variable initialization to the CFG.
3078 if (VarDecl *VD = Terminator->getConditionVariable()) {
3079 if (Expr *Init = VD->getInit()) {
3080 autoCreateBlock();
Ted Kremenek37881932011-04-04 23:29:12 +00003081 appendStmt(Block, Terminator->getConditionVariableDeclStmt());
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003082 LastBlock = addStmt(Init);
Ted Kremenek8b5dc122009-12-24 00:39:26 +00003083 }
3084 }
Ted Kremenekdc03bd02010-08-02 23:46:59 +00003085
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003086 return LastBlock;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003087}
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003088
3089static bool shouldAddCase(bool &switchExclusivelyCovered,
Ted Kremenek53e65382011-03-13 03:48:04 +00003090 const Expr::EvalResult *switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003091 const CaseStmt *CS,
3092 ASTContext &Ctx) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003093 if (!switchCond)
3094 return true;
3095
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003096 bool addCase = false;
Ted Kremenekbe528712011-03-04 01:03:41 +00003097
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003098 if (!switchExclusivelyCovered) {
Ted Kremenek53e65382011-03-13 03:48:04 +00003099 if (switchCond->Val.isInt()) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003100 // Evaluate the LHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003101 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx);
Ted Kremenek53e65382011-03-13 03:48:04 +00003102 const llvm::APSInt &condInt = switchCond->Val.getInt();
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003103
3104 if (condInt == lhsInt) {
3105 addCase = true;
3106 switchExclusivelyCovered = true;
3107 }
3108 else if (condInt < lhsInt) {
3109 if (const Expr *RHS = CS->getRHS()) {
3110 // Evaluate the RHS of the case value.
Richard Smithfaa32a92011-10-14 20:22:00 +00003111 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx);
3112 if (V2 <= condInt) {
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003113 addCase = true;
3114 switchExclusivelyCovered = true;
3115 }
3116 }
3117 }
3118 }
3119 else
3120 addCase = true;
3121 }
3122 return addCase;
3123}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003124
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003125CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) {
Mike Stump31feda52009-07-17 01:31:16 +00003126 // CaseStmts are essentially labels, so they are the first statement in a
3127 // block.
Craig Topper25542942014-05-20 04:30:07 +00003128 CFGBlock *TopBlock = nullptr, *LastBlock = nullptr;
Ted Kremenekbe528712011-03-04 01:03:41 +00003129
Ted Kremenek60fa6572010-08-04 23:54:30 +00003130 if (Stmt *Sub = CS->getSubStmt()) {
3131 // For deeply nested chains of CaseStmts, instead of doing a recursion
3132 // (which can blow out the stack), manually unroll and create blocks
3133 // along the way.
3134 while (isa<CaseStmt>(Sub)) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003135 CFGBlock *currentBlock = createBlock(false);
3136 currentBlock->setLabel(CS);
Ted Kremenek55e91e82007-08-30 18:48:11 +00003137
Ted Kremenek60fa6572010-08-04 23:54:30 +00003138 if (TopBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003139 addSuccessor(LastBlock, currentBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003140 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003141 TopBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003142
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003143 addSuccessor(SwitchTerminatedBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003144 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003145 CS, *Context)
Craig Topper25542942014-05-20 04:30:07 +00003146 ? currentBlock : nullptr);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003147
Ted Kremenekeff9a7f2011-03-01 23:12:55 +00003148 LastBlock = currentBlock;
Ted Kremenek60fa6572010-08-04 23:54:30 +00003149 CS = cast<CaseStmt>(Sub);
3150 Sub = CS->getSubStmt();
3151 }
3152
3153 addStmt(Sub);
3154 }
Mike Stump11289f42009-09-09 15:08:12 +00003155
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003156 CFGBlock *CaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003157 if (!CaseBlock)
3158 CaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003159
3160 // Cases statements partition blocks, so this is the top of the basic block we
3161 // were processing (the "case XXX:" is the label).
Ted Kremenek93668002009-07-17 22:18:43 +00003162 CaseBlock->setLabel(CS);
3163
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003164 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003165 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003166
3167 // Add this block to the list of successors for the block with the switch
3168 // statement.
Ted Kremenek93668002009-07-17 22:18:43 +00003169 assert(SwitchTerminatedBlock);
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003170 addSuccessor(SwitchTerminatedBlock, CaseBlock,
Ted Kremenek53e65382011-03-13 03:48:04 +00003171 shouldAddCase(switchExclusivelyCovered, switchCond,
Ted Kremenek9238c5c2014-02-27 21:56:44 +00003172 CS, *Context));
Mike Stump31feda52009-07-17 01:31:16 +00003173
Ted Kremenek9aae5132007-08-23 21:42:29 +00003174 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003175 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003176
Ted Kremenek60fa6572010-08-04 23:54:30 +00003177 if (TopBlock) {
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003178 addSuccessor(LastBlock, CaseBlock);
Ted Kremenek60fa6572010-08-04 23:54:30 +00003179 Succ = TopBlock;
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003180 } else {
Ted Kremenek60fa6572010-08-04 23:54:30 +00003181 // This block is now the implicit successor of other blocks.
3182 Succ = CaseBlock;
3183 }
Mike Stump31feda52009-07-17 01:31:16 +00003184
Ted Kremenek60fa6572010-08-04 23:54:30 +00003185 return Succ;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003186}
Mike Stump31feda52009-07-17 01:31:16 +00003187
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003188CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) {
Ted Kremenek93668002009-07-17 22:18:43 +00003189 if (Terminator->getSubStmt())
3190 addStmt(Terminator->getSubStmt());
Mike Stump11289f42009-09-09 15:08:12 +00003191
Ted Kremenek654c78f2008-02-13 22:05:39 +00003192 DefaultCaseBlock = Block;
Ted Kremenek93668002009-07-17 22:18:43 +00003193
3194 if (!DefaultCaseBlock)
3195 DefaultCaseBlock = createBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003196
3197 // Default statements partition blocks, so this is the top of the basic block
3198 // we were processing (the "default:" is the label).
Ted Kremenekc1f9a282008-04-16 21:10:48 +00003199 DefaultCaseBlock->setLabel(Terminator);
Mike Stump11289f42009-09-09 15:08:12 +00003200
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003201 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003202 return nullptr;
Ted Kremenek654c78f2008-02-13 22:05:39 +00003203
Mike Stump31feda52009-07-17 01:31:16 +00003204 // Unlike case statements, we don't add the default block to the successors
3205 // for the switch statement immediately. This is done when we finish
3206 // processing the switch statement. This allows for the default case
3207 // (including a fall-through to the code after the switch statement) to always
3208 // be the last successor of a switch-terminated block.
3209
Ted Kremenek654c78f2008-02-13 22:05:39 +00003210 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003211 Block = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00003212
Ted Kremenek654c78f2008-02-13 22:05:39 +00003213 // This block is now the implicit successor of other blocks.
3214 Succ = DefaultCaseBlock;
Mike Stump31feda52009-07-17 01:31:16 +00003215
3216 return DefaultCaseBlock;
Ted Kremenek9682be12008-02-13 21:46:34 +00003217}
Ted Kremenek9aae5132007-08-23 21:42:29 +00003218
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003219CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
3220 // "try"/"catch" is a control-flow statement. Thus we stop processing the
3221 // current block.
Craig Topper25542942014-05-20 04:30:07 +00003222 CFGBlock *TrySuccessor = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003223
3224 if (Block) {
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003225 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003226 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003227 TrySuccessor = Block;
3228 } else TrySuccessor = Succ;
3229
Mike Stump0bdba6c2010-01-20 01:15:34 +00003230 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003231
3232 // Create a new block that will contain the try statement.
Mike Stump845384a2010-01-20 01:30:58 +00003233 CFGBlock *NewTryTerminatedBlock = createBlock(false);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003234 // Add the terminator in the try block.
Mike Stump845384a2010-01-20 01:30:58 +00003235 NewTryTerminatedBlock->setTerminator(Terminator);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003236
Mike Stump0bdba6c2010-01-20 01:15:34 +00003237 bool HasCatchAll = false;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003238 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
3239 // The code after the try is the implicit successor.
3240 Succ = TrySuccessor;
3241 CXXCatchStmt *CS = Terminator->getHandler(h);
Craig Topper25542942014-05-20 04:30:07 +00003242 if (CS->getExceptionDecl() == nullptr) {
Mike Stump0bdba6c2010-01-20 01:15:34 +00003243 HasCatchAll = true;
3244 }
Craig Topper25542942014-05-20 04:30:07 +00003245 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003246 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
Craig Topper25542942014-05-20 04:30:07 +00003247 if (!CatchBlock)
3248 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003249 // Add this block to the list of successors for the block with the try
3250 // statement.
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003251 addSuccessor(NewTryTerminatedBlock, CatchBlock);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003252 }
Mike Stump0bdba6c2010-01-20 01:15:34 +00003253 if (!HasCatchAll) {
3254 if (PrevTryTerminatedBlock)
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003255 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
Mike Stump0bdba6c2010-01-20 01:15:34 +00003256 else
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003257 addSuccessor(NewTryTerminatedBlock, &cfg->getExit());
Mike Stump0bdba6c2010-01-20 01:15:34 +00003258 }
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003259
3260 // The code after the try is the implicit successor.
3261 Succ = TrySuccessor;
3262
Mike Stump845384a2010-01-20 01:30:58 +00003263 // Save the current "try" context.
Ted Kremenek6b9964d2011-08-23 23:05:07 +00003264 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock);
3265 cfg->addTryDispatchBlock(TryTerminatedBlock);
Mike Stump845384a2010-01-20 01:30:58 +00003266
Ted Kremenek1362b8b2010-01-19 20:46:35 +00003267 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
Craig Topper25542942014-05-20 04:30:07 +00003268 Block = nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003269 return addStmt(Terminator->getTryBlock());
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003270}
3271
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003272CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003273 // CXXCatchStmt are treated like labels, so they are the first statement in a
3274 // block.
3275
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003276 // Save local scope position because in case of exception variable ScopePos
3277 // won't be restored when traversing AST.
3278 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3279
3280 // Create local scope for possible exception variable.
3281 // Store scope position. Add implicit destructor.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003282 if (VarDecl *VD = CS->getExceptionDecl()) {
Marcin Swiderski3546b1a2010-10-01 01:46:52 +00003283 LocalScope::const_iterator BeginScopePos = ScopePos;
3284 addLocalScopeForVarDecl(VD);
3285 addAutomaticObjDtors(ScopePos, BeginScopePos, CS);
3286 }
3287
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003288 if (CS->getHandlerBlock())
3289 addStmt(CS->getHandlerBlock());
3290
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003291 CFGBlock *CatchBlock = Block;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003292 if (!CatchBlock)
3293 CatchBlock = createBlock();
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003294
3295 // CXXCatchStmt is more than just a label. They have semantic meaning
3296 // as well, as they implicitly "initialize" the catch variable. Add
3297 // it to the CFG as a CFGElement so that the control-flow of these
3298 // semantics gets captured.
3299 appendStmt(CatchBlock, CS);
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003300
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003301 // Also add the CXXCatchStmt as a label, to mirror handling of regular
3302 // labels.
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003303 CatchBlock->setLabel(CS);
3304
Ted Kremenek8fdb59f2012-03-10 01:34:17 +00003305 // Bail out if the CFG is bad.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003306 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003307 return nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003308
3309 // We set Block to NULL to allow lazy creation of a new block (if necessary)
Craig Topper25542942014-05-20 04:30:07 +00003310 Block = nullptr;
Mike Stumpbbf5ba62010-01-19 02:20:09 +00003311
3312 return CatchBlock;
3313}
3314
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003315CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
Richard Smith02e85f32011-04-14 22:09:26 +00003316 // C++0x for-range statements are specified as [stmt.ranged]:
3317 //
3318 // {
3319 // auto && __range = range-init;
3320 // for ( auto __begin = begin-expr,
3321 // __end = end-expr;
3322 // __begin != __end;
3323 // ++__begin ) {
3324 // for-range-declaration = *__begin;
3325 // statement
3326 // }
3327 // }
3328
3329 // Save local scope position before the addition of the implicit variables.
3330 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos);
3331
3332 // Create local scopes and destructors for range, begin and end variables.
3333 if (Stmt *Range = S->getRangeStmt())
3334 addLocalScopeForStmt(Range);
3335 if (Stmt *BeginEnd = S->getBeginEndStmt())
3336 addLocalScopeForStmt(BeginEnd);
3337 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S);
3338
3339 LocalScope::const_iterator ContinueScopePos = ScopePos;
3340
3341 // "for" is a control-flow statement. Thus we stop processing the current
3342 // block.
Craig Topper25542942014-05-20 04:30:07 +00003343 CFGBlock *LoopSuccessor = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003344 if (Block) {
3345 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003346 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003347 LoopSuccessor = Block;
3348 } else
3349 LoopSuccessor = Succ;
3350
3351 // Save the current value for the break targets.
3352 // All breaks should go to the code following the loop.
3353 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget);
3354 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos);
3355
3356 // The block for the __begin != __end expression.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003357 CFGBlock *ConditionBlock = createBlock(false);
Richard Smith02e85f32011-04-14 22:09:26 +00003358 ConditionBlock->setTerminator(S);
3359
3360 // Now add the actual condition to the condition block.
3361 if (Expr *C = S->getCond()) {
3362 Block = ConditionBlock;
3363 CFGBlock *BeginConditionBlock = addStmt(C);
3364 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003365 return nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003366 assert(BeginConditionBlock == ConditionBlock &&
3367 "condition block in for-range was unexpectedly complex");
3368 (void)BeginConditionBlock;
3369 }
3370
3371 // The condition block is the implicit successor for the loop body as well as
3372 // any code above the loop.
3373 Succ = ConditionBlock;
3374
3375 // See if this is a known constant.
3376 TryResult KnownVal(true);
3377
3378 if (S->getCond())
3379 KnownVal = tryEvaluateBool(S->getCond());
3380
3381 // Now create the loop body.
3382 {
3383 assert(S->getBody());
3384
3385 // Save the current values for Block, Succ, and continue targets.
3386 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ);
3387 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget);
3388
3389 // Generate increment code in its own basic block. This is the target of
3390 // continue statements.
Craig Topper25542942014-05-20 04:30:07 +00003391 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003392 Succ = addStmt(S->getInc());
3393 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos);
3394
3395 // The starting block for the loop increment is the block that should
3396 // represent the 'loop target' for looping back to the start of the loop.
3397 ContinueJumpTarget.block->setLoopTarget(S);
3398
3399 // Finish up the increment block and prepare to start the loop body.
3400 assert(Block);
3401 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003402 return nullptr;
3403 Block = nullptr;
Richard Smith02e85f32011-04-14 22:09:26 +00003404
3405 // Add implicit scope and dtors for loop variable.
3406 addLocalScopeAndDtors(S->getLoopVarStmt());
3407
3408 // Populate a new block to contain the loop body and loop variable.
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003409 addStmt(S->getBody());
Richard Smith02e85f32011-04-14 22:09:26 +00003410 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003411 return nullptr;
Ted Kremeneke6ee6712012-11-13 00:12:13 +00003412 CFGBlock *LoopVarStmtBlock = addStmt(S->getLoopVarStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003413 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003414 return nullptr;
3415
Richard Smith02e85f32011-04-14 22:09:26 +00003416 // This new body block is a successor to our condition block.
Craig Topper25542942014-05-20 04:30:07 +00003417 addSuccessor(ConditionBlock,
3418 KnownVal.isFalse() ? nullptr : LoopVarStmtBlock);
Richard Smith02e85f32011-04-14 22:09:26 +00003419 }
3420
3421 // Link up the condition block with the code that follows the loop (the
3422 // false branch).
Craig Topper25542942014-05-20 04:30:07 +00003423 addSuccessor(ConditionBlock, KnownVal.isTrue() ? nullptr : LoopSuccessor);
Richard Smith02e85f32011-04-14 22:09:26 +00003424
3425 // Add the initialization statements.
3426 Block = createBlock();
Richard Smith0c502d22011-04-18 15:49:25 +00003427 addStmt(S->getBeginEndStmt());
3428 return addStmt(S->getRangeStmt());
Richard Smith02e85f32011-04-14 22:09:26 +00003429}
3430
John McCall5d413782010-12-06 08:20:24 +00003431CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E,
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003432 AddStmtChoice asc) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003433 if (BuildOpts.AddTemporaryDtors) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003434 // If adding implicit destructors visit the full expression for adding
3435 // destructors of temporaries.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003436 TempDtorContext Context;
Manuel Klimekb5616c92014-08-07 10:42:17 +00003437 VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003438
3439 // Full expression has to be added as CFGStmt so it will be sequenced
3440 // before destructors of it's temporaries.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003441 asc = asc.withAlwaysAdd(true);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003442 }
3443 return Visit(E->getSubExpr(), asc);
3444}
3445
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003446CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E,
3447 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003448 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003449 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003450 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003451
3452 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003453 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003454 }
3455 return Visit(E->getSubExpr(), asc);
3456}
3457
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003458CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C,
3459 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003460 autoCreateBlock();
Zhongxing Xuf0cb43f2012-01-11 02:39:07 +00003461 appendStmt(Block, C);
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003462
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003463 return VisitChildren(C);
3464}
3465
Jordan Rosec9176072014-01-13 17:59:19 +00003466CFGBlock *CFGBuilder::VisitCXXNewExpr(CXXNewExpr *NE,
3467 AddStmtChoice asc) {
3468
3469 autoCreateBlock();
3470 appendStmt(Block, NE);
Jordan Rose6f5f7192014-01-14 17:29:12 +00003471
Jordan Rosec9176072014-01-13 17:59:19 +00003472 if (NE->getInitializer())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003473 Block = Visit(NE->getInitializer());
Jordan Rosec9176072014-01-13 17:59:19 +00003474 if (BuildOpts.AddCXXNewAllocator)
3475 appendNewAllocator(Block, NE);
3476 if (NE->isArray())
Jordan Rose6f5f7192014-01-14 17:29:12 +00003477 Block = Visit(NE->getArraySize());
Jordan Rosec9176072014-01-13 17:59:19 +00003478 for (CXXNewExpr::arg_iterator I = NE->placement_arg_begin(),
3479 E = NE->placement_arg_end(); I != E; ++I)
Jordan Rose6f5f7192014-01-14 17:29:12 +00003480 Block = Visit(*I);
Jordan Rosec9176072014-01-13 17:59:19 +00003481 return Block;
3482}
Jordan Rosed2f40792013-09-03 17:00:57 +00003483
3484CFGBlock *CFGBuilder::VisitCXXDeleteExpr(CXXDeleteExpr *DE,
3485 AddStmtChoice asc) {
3486 autoCreateBlock();
3487 appendStmt(Block, DE);
3488 QualType DTy = DE->getDestroyedType();
3489 DTy = DTy.getNonReferenceType();
3490 CXXRecordDecl *RD = Context->getBaseElementType(DTy)->getAsCXXRecordDecl();
3491 if (RD) {
Matt Beaumont-Gay093f2402013-09-09 21:07:58 +00003492 if (RD->isCompleteDefinition() && !RD->hasTrivialDestructor())
Jordan Rosed2f40792013-09-03 17:00:57 +00003493 appendDeleteDtor(Block, RD, DE);
3494 }
3495
3496 return VisitChildren(DE);
3497}
3498
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003499CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E,
3500 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003501 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003502 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003503 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003504 // We do not want to propagate the AlwaysAdd property.
Zhanyong Wanb5d11c12010-11-24 03:28:53 +00003505 asc = asc.withAlwaysAdd(false);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003506 }
3507 return Visit(E->getSubExpr(), asc);
3508}
3509
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003510CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C,
3511 AddStmtChoice asc) {
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003512 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003513 appendStmt(Block, C);
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00003514 return VisitChildren(C);
3515}
3516
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003517CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E,
3518 AddStmtChoice asc) {
Ted Kremenek7c58d352011-03-10 01:14:11 +00003519 if (asc.alwaysAdd(*this, E)) {
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003520 autoCreateBlock();
Ted Kremenek2866bab2011-03-10 01:14:08 +00003521 appendStmt(Block, E);
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003522 }
Ted Kremenek8219b822010-12-16 07:46:53 +00003523 return Visit(E->getSubExpr(), AddStmtChoice());
Zhongxing Xue1dbeb22010-11-01 13:04:58 +00003524}
3525
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003526CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Mike Stump31feda52009-07-17 01:31:16 +00003527 // Lazily create the indirect-goto dispatch block if there isn't one already.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003528 CFGBlock *IBlock = cfg->getIndirectGotoBlock();
Mike Stump31feda52009-07-17 01:31:16 +00003529
Ted Kremenekeda180e22007-08-28 19:26:49 +00003530 if (!IBlock) {
3531 IBlock = createBlock(false);
3532 cfg->setIndirectGotoBlock(IBlock);
3533 }
Mike Stump31feda52009-07-17 01:31:16 +00003534
Ted Kremenekeda180e22007-08-28 19:26:49 +00003535 // IndirectGoto is a control-flow statement. Thus we stop processing the
3536 // current block and create a new one.
Zhongxing Xu33dfc072010-09-06 07:32:31 +00003537 if (badCFG)
Craig Topper25542942014-05-20 04:30:07 +00003538 return nullptr;
Ted Kremenek93668002009-07-17 22:18:43 +00003539
Ted Kremenekeda180e22007-08-28 19:26:49 +00003540 Block = createBlock(false);
3541 Block->setTerminator(I);
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003542 addSuccessor(Block, IBlock);
Ted Kremenekeda180e22007-08-28 19:26:49 +00003543 return addStmt(I->getTarget());
3544}
3545
Manuel Klimekb5616c92014-08-07 10:42:17 +00003546CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary,
3547 TempDtorContext &Context) {
Jordan Rose6d671cc2012-09-05 22:55:23 +00003548 assert(BuildOpts.AddImplicitDtors && BuildOpts.AddTemporaryDtors);
3549
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003550tryAgain:
3551 if (!E) {
3552 badCFG = true;
Craig Topper25542942014-05-20 04:30:07 +00003553 return nullptr;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003554 }
3555 switch (E->getStmtClass()) {
3556 default:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003557 return VisitChildrenForTemporaryDtors(E, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003558
3559 case Stmt::BinaryOperatorClass:
Manuel Klimekb5616c92014-08-07 10:42:17 +00003560 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E),
3561 Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003562
3563 case Stmt::CXXBindTemporaryExprClass:
3564 return VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003565 cast<CXXBindTemporaryExpr>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003566
John McCallc07a0c72011-02-17 10:25:35 +00003567 case Stmt::BinaryConditionalOperatorClass:
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003568 case Stmt::ConditionalOperatorClass:
3569 return VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003570 cast<AbstractConditionalOperator>(E), BindToTemporary, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003571
3572 case Stmt::ImplicitCastExprClass:
3573 // For implicit cast we want BindToTemporary to be passed further.
3574 E = cast<CastExpr>(E)->getSubExpr();
3575 goto tryAgain;
3576
Manuel Klimekb0042c42014-07-30 08:34:42 +00003577 case Stmt::CXXFunctionalCastExprClass:
3578 // For functional cast we want BindToTemporary to be passed further.
3579 E = cast<CXXFunctionalCastExpr>(E)->getSubExpr();
3580 goto tryAgain;
3581
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003582 case Stmt::ParenExprClass:
3583 E = cast<ParenExpr>(E)->getSubExpr();
3584 goto tryAgain;
Richard Smith4137af22014-07-27 05:12:49 +00003585
Manuel Klimekb0042c42014-07-30 08:34:42 +00003586 case Stmt::MaterializeTemporaryExprClass: {
3587 const MaterializeTemporaryExpr* MTE = cast<MaterializeTemporaryExpr>(E);
3588 BindToTemporary = (MTE->getStorageDuration() != SD_FullExpression);
3589 SmallVector<const Expr *, 2> CommaLHSs;
3590 SmallVector<SubobjectAdjustment, 2> Adjustments;
3591 // Find the expression whose lifetime needs to be extended.
3592 E = const_cast<Expr *>(
3593 cast<MaterializeTemporaryExpr>(E)
3594 ->GetTemporaryExpr()
3595 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
3596 // Visit the skipped comma operator left-hand sides for other temporaries.
3597 for (const Expr *CommaLHS : CommaLHSs) {
3598 VisitForTemporaryDtors(const_cast<Expr *>(CommaLHS),
Manuel Klimekb5616c92014-08-07 10:42:17 +00003599 /*BindToTemporary=*/false, Context);
Manuel Klimekb0042c42014-07-30 08:34:42 +00003600 }
Douglas Gregorfe314812011-06-21 17:03:29 +00003601 goto tryAgain;
Manuel Klimekb0042c42014-07-30 08:34:42 +00003602 }
Richard Smith4137af22014-07-27 05:12:49 +00003603
3604 case Stmt::BlockExprClass:
3605 // Don't recurse into blocks; their subexpressions don't get evaluated
3606 // here.
3607 return Block;
3608
3609 case Stmt::LambdaExprClass: {
3610 // For lambda expressions, only recurse into the capture initializers,
3611 // and not the body.
3612 auto *LE = cast<LambdaExpr>(E);
3613 CFGBlock *B = Block;
3614 for (Expr *Init : LE->capture_inits()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003615 if (CFGBlock *R = VisitForTemporaryDtors(
3616 Init, /*BindToTemporary=*/false, Context))
Richard Smith4137af22014-07-27 05:12:49 +00003617 B = R;
3618 }
3619 return B;
3620 }
3621
3622 case Stmt::CXXDefaultArgExprClass:
3623 E = cast<CXXDefaultArgExpr>(E)->getExpr();
3624 goto tryAgain;
3625
3626 case Stmt::CXXDefaultInitExprClass:
3627 E = cast<CXXDefaultInitExpr>(E)->getExpr();
3628 goto tryAgain;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003629 }
3630}
3631
Manuel Klimekb5616c92014-08-07 10:42:17 +00003632CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E,
3633 TempDtorContext &Context) {
3634 if (isa<LambdaExpr>(E)) {
3635 // Do not visit the children of lambdas; they have their own CFGs.
3636 return Block;
3637 }
3638
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003639 // When visiting children for destructors we want to visit them in reverse
Ted Kremenek8ae67872013-02-05 22:00:19 +00003640 // order that they will appear in the CFG. Because the CFG is built
3641 // bottom-up, this means we visit them in their natural order, which
3642 // reverses them in the CFG.
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003643 CFGBlock *B = Block;
Ted Kremenek8ae67872013-02-05 22:00:19 +00003644 for (Stmt::child_range I = E->children(); I; ++I) {
3645 if (Stmt *Child = *I)
Manuel Klimekb5616c92014-08-07 10:42:17 +00003646 if (CFGBlock *R = VisitForTemporaryDtors(Child, false, Context))
Ted Kremenek8ae67872013-02-05 22:00:19 +00003647 B = R;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003648 }
3649 return B;
3650}
3651
Manuel Klimekb5616c92014-08-07 10:42:17 +00003652CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(
3653 BinaryOperator *E, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003654 if (E->isLogicalOp()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003655 VisitForTemporaryDtors(E->getLHS(), false, Context);
Manuel Klimekedf925b92014-08-07 18:44:19 +00003656 TryResult RHSExecuted = tryEvaluateBool(E->getLHS());
3657 if (RHSExecuted.isKnown() && E->getOpcode() == BO_LOr)
3658 RHSExecuted.negate();
Manuel Klimek7c030132014-08-07 16:05:51 +00003659
Manuel Klimekedf925b92014-08-07 18:44:19 +00003660 // We do not know at CFG-construction time whether the right-hand-side was
3661 // executed, thus we add a branch node that depends on the temporary
3662 // constructor call.
Manuel Klimekdeb02622014-08-08 07:37:13 +00003663 TempDtorContext RHSContext(
3664 bothKnownTrue(Context.KnownExecuted, RHSExecuted));
Manuel Klimekedf925b92014-08-07 18:44:19 +00003665 VisitForTemporaryDtors(E->getRHS(), false, RHSContext);
Manuel Klimekdeb02622014-08-08 07:37:13 +00003666 InsertTempDtorDecisionBlock(RHSContext);
Manuel Klimek7c030132014-08-07 16:05:51 +00003667
Manuel Klimekb5616c92014-08-07 10:42:17 +00003668 return Block;
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003669 }
3670
Zhanyong Wan59f09c72010-11-22 19:32:14 +00003671 if (E->isAssignmentOp()) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003672 // For assignment operator (=) LHS expression is visited
3673 // before RHS expression. For destructors visit them in reverse order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003674 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
3675 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003676 return LHSBlock ? LHSBlock : RHSBlock;
3677 }
3678
3679 // For any other binary operator RHS expression is visited before
3680 // LHS expression (order of children). For destructors visit them in reverse
3681 // order.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003682 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS(), false, Context);
3683 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS(), false, Context);
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003684 return RHSBlock ? RHSBlock : LHSBlock;
3685}
3686
3687CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003688 CXXBindTemporaryExpr *E, bool BindToTemporary, TempDtorContext &Context) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003689 // First add destructors for temporaries in subexpression.
Manuel Klimekb5616c92014-08-07 10:42:17 +00003690 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr(), false, Context);
Zhongxing Xufee455f2010-11-14 15:23:50 +00003691 if (!BindToTemporary) {
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003692 // If lifetime of temporary is not prolonged (by assigning to constant
3693 // reference) add destructor for it.
Chandler Carruthad747252011-09-13 06:09:01 +00003694
Chandler Carruthad747252011-09-13 06:09:01 +00003695 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003696
Richard Trieu95a192a2015-05-28 00:14:02 +00003697 if (Dtor->getParent()->isAnyDestructorNoReturn()) {
Manuel Klimekb5616c92014-08-07 10:42:17 +00003698 // If the destructor is marked as a no-return destructor, we need to
3699 // create a new block for the destructor which does not have as a
3700 // successor anything built thus far. Control won't flow out of this
3701 // block.
3702 if (B) Succ = B;
Chandler Carrutha70991b2011-09-13 09:13:49 +00003703 Block = createNoReturnBlock();
Manuel Klimekb5616c92014-08-07 10:42:17 +00003704 } else if (Context.needsTempDtorBranch()) {
3705 // If we need to introduce a branch, we add a new block that we will hook
3706 // up to a decision block later.
3707 if (B) Succ = B;
3708 Block = createBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003709 } else {
Chandler Carruthad747252011-09-13 06:09:01 +00003710 autoCreateBlock();
Ted Kremenekff909f92014-03-08 02:22:25 +00003711 }
Manuel Klimekb5616c92014-08-07 10:42:17 +00003712 if (Context.needsTempDtorBranch()) {
3713 Context.setDecisionPoint(Succ, E);
3714 }
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003715 appendTemporaryDtor(Block, E);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003716
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003717 B = Block;
3718 }
3719 return B;
3720}
3721
Manuel Klimekb5616c92014-08-07 10:42:17 +00003722void CFGBuilder::InsertTempDtorDecisionBlock(const TempDtorContext &Context,
3723 CFGBlock *FalseSucc) {
3724 if (!Context.TerminatorExpr) {
3725 // If no temporary was found, we do not need to insert a decision point.
3726 return;
3727 }
3728 assert(Context.TerminatorExpr);
3729 CFGBlock *Decision = createBlock(false);
3730 Decision->setTerminator(CFGTerminator(Context.TerminatorExpr, true));
Manuel Klimekdeb02622014-08-08 07:37:13 +00003731 addSuccessor(Decision, Block, !Context.KnownExecuted.isFalse());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003732 addSuccessor(Decision, FalseSucc ? FalseSucc : Context.Succ,
Manuel Klimekdeb02622014-08-08 07:37:13 +00003733 !Context.KnownExecuted.isTrue());
Manuel Klimekb5616c92014-08-07 10:42:17 +00003734 Block = Decision;
3735}
3736
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003737CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors(
Manuel Klimekb5616c92014-08-07 10:42:17 +00003738 AbstractConditionalOperator *E, bool BindToTemporary,
3739 TempDtorContext &Context) {
3740 VisitForTemporaryDtors(E->getCond(), false, Context);
3741 CFGBlock *ConditionBlock = Block;
3742 CFGBlock *ConditionSucc = Succ;
Manuel Klimek0ce91082014-08-07 14:25:43 +00003743 TryResult ConditionVal = tryEvaluateBool(E->getCond());
Manuel Klimekedf925b92014-08-07 18:44:19 +00003744 TryResult NegatedVal = ConditionVal;
3745 if (NegatedVal.isKnown()) NegatedVal.negate();
Manuel Klimekcadc6032014-08-07 17:02:21 +00003746
Manuel Klimekdeb02622014-08-08 07:37:13 +00003747 TempDtorContext TrueContext(
3748 bothKnownTrue(Context.KnownExecuted, ConditionVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003749 VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary, TrueContext);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003750 CFGBlock *TrueBlock = Block;
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003751
Manuel Klimekb5616c92014-08-07 10:42:17 +00003752 Block = ConditionBlock;
3753 Succ = ConditionSucc;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003754 TempDtorContext FalseContext(
3755 bothKnownTrue(Context.KnownExecuted, NegatedVal));
Manuel Klimekcadc6032014-08-07 17:02:21 +00003756 VisitForTemporaryDtors(E->getFalseExpr(), BindToTemporary, FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003757
Manuel Klimekb5616c92014-08-07 10:42:17 +00003758 if (TrueContext.TerminatorExpr && FalseContext.TerminatorExpr) {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003759 InsertTempDtorDecisionBlock(FalseContext, TrueBlock);
Manuel Klimekb5616c92014-08-07 10:42:17 +00003760 } else if (TrueContext.TerminatorExpr) {
3761 Block = TrueBlock;
Manuel Klimekdeb02622014-08-08 07:37:13 +00003762 InsertTempDtorDecisionBlock(TrueContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003763 } else {
Manuel Klimekdeb02622014-08-08 07:37:13 +00003764 InsertTempDtorDecisionBlock(FalseContext);
Rui Ueyamaa89f9c82014-08-06 22:01:54 +00003765 }
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00003766 return Block;
3767}
3768
Ted Kremenek04cca642007-08-23 21:26:19 +00003769} // end anonymous namespace
Ted Kremenek889073f2007-08-23 16:51:22 +00003770
Mike Stump31feda52009-07-17 01:31:16 +00003771/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
3772/// no successors or predecessors. If this is the first block created in the
3773/// CFG, it is automatically set to be the Entry and Exit of the CFG.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003774CFGBlock *CFG::createBlock() {
Ted Kremenek889073f2007-08-23 16:51:22 +00003775 bool first_block = begin() == end();
3776
3777 // Create the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003778 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
Anna Zaks02a1fc12011-12-05 21:33:11 +00003779 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this);
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003780 Blocks.push_back(Mem, BlkBVC);
Ted Kremenek889073f2007-08-23 16:51:22 +00003781
3782 // If this is the first block, set it as the Entry and Exit.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003783 if (first_block)
3784 Entry = Exit = &back();
Ted Kremenek889073f2007-08-23 16:51:22 +00003785
3786 // Return the block.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003787 return &back();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00003788}
3789
David Blaikiee90195c2014-08-29 18:53:26 +00003790/// buildCFG - Constructs a CFG from an AST.
3791std::unique_ptr<CFG> CFG::buildCFG(const Decl *D, Stmt *Statement,
3792 ASTContext *C, const BuildOptions &BO) {
Ted Kremenekf9d82902011-03-10 01:14:05 +00003793 CFGBuilder Builder(C, BO);
3794 return Builder.buildCFG(D, Statement);
Ted Kremenek889073f2007-08-23 16:51:22 +00003795}
3796
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003797const CXXDestructorDecl *
3798CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003799 switch (getKind()) {
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003800 case CFGElement::Statement:
3801 case CFGElement::Initializer:
Jordan Rosec9176072014-01-13 17:59:19 +00003802 case CFGElement::NewAllocator:
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003803 llvm_unreachable("getDestructorDecl should only be used with "
3804 "ImplicitDtors");
3805 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00003806 const VarDecl *var = castAs<CFGAutomaticObjDtor>().getVarDecl();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003807 QualType ty = var->getType();
Ted Kremenek1676a042011-03-03 01:01:03 +00003808 ty = ty.getNonReferenceType();
Ted Kremeneke7d78882012-03-19 23:48:41 +00003809 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) {
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003810 ty = arrayType->getElementType();
3811 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003812 const RecordType *recordType = ty->getAs<RecordType>();
3813 const CXXRecordDecl *classDecl =
Ted Kremenek1676a042011-03-03 01:01:03 +00003814 cast<CXXRecordDecl>(recordType->getDecl());
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003815 return classDecl->getDestructor();
3816 }
Jordan Rosed2f40792013-09-03 17:00:57 +00003817 case CFGElement::DeleteDtor: {
3818 const CXXDeleteExpr *DE = castAs<CFGDeleteDtor>().getDeleteExpr();
3819 QualType DTy = DE->getDestroyedType();
3820 DTy = DTy.getNonReferenceType();
3821 const CXXRecordDecl *classDecl =
3822 astContext.getBaseElementType(DTy)->getAsCXXRecordDecl();
3823 return classDecl->getDestructor();
3824 }
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003825 case CFGElement::TemporaryDtor: {
3826 const CXXBindTemporaryExpr *bindExpr =
David Blaikie2a01f5d2013-02-21 20:58:29 +00003827 castAs<CFGTemporaryDtor>().getBindTemporaryExpr();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003828 const CXXTemporary *temp = bindExpr->getTemporary();
3829 return temp->getDestructor();
3830 }
3831 case CFGElement::BaseDtor:
3832 case CFGElement::MemberDtor:
3833
3834 // Not yet supported.
Craig Topper25542942014-05-20 04:30:07 +00003835 return nullptr;
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003836 }
Ted Kremenek1676a042011-03-03 01:01:03 +00003837 llvm_unreachable("getKind() returned bogus value");
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003838}
3839
Ted Kremenek8cfe2072011-03-03 01:21:32 +00003840bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const {
Richard Smith10876ef2013-01-17 01:30:42 +00003841 if (const CXXDestructorDecl *DD = getDestructorDecl(astContext))
3842 return DD->isNoReturn();
Ted Kremeneke06a55c2011-03-02 20:32:29 +00003843 return false;
Ted Kremenek96a7a592011-03-01 03:15:10 +00003844}
3845
Ted Kremenekf2d4372b2007-10-01 19:33:33 +00003846//===----------------------------------------------------------------------===//
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003847// CFGBlock operations.
Ted Kremenekb0371852010-09-09 00:06:04 +00003848//===----------------------------------------------------------------------===//
3849
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003850CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, bool IsReachable)
Craig Topper25542942014-05-20 04:30:07 +00003851 : ReachableBlock(IsReachable ? B : nullptr),
3852 UnreachableBlock(!IsReachable ? B : nullptr,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003853 B && IsReachable ? AB_Normal : AB_Unreachable) {}
3854
3855CFGBlock::AdjacentBlock::AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock)
3856 : ReachableBlock(B),
Craig Topper25542942014-05-20 04:30:07 +00003857 UnreachableBlock(B == AlternateBlock ? nullptr : AlternateBlock,
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003858 B == AlternateBlock ? AB_Alternate : AB_Normal) {}
3859
3860void CFGBlock::addSuccessor(AdjacentBlock Succ,
3861 BumpVectorContext &C) {
3862 if (CFGBlock *B = Succ.getReachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003863 B->Preds.push_back(AdjacentBlock(this, Succ.isReachable()), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003864
3865 if (CFGBlock *UnreachableB = Succ.getPossiblyUnreachableBlock())
David Blaikie9afd5da2014-03-04 23:39:18 +00003866 UnreachableB->Preds.push_back(AdjacentBlock(this, false), C);
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003867
3868 Succs.push_back(Succ, C);
3869}
3870
Ted Kremenekb0371852010-09-09 00:06:04 +00003871bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F,
Ted Kremenekf146cd12010-09-09 02:57:48 +00003872 const CFGBlock *From, const CFGBlock *To) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003873
Ted Kremenek4b6fee62014-02-27 00:24:00 +00003874 if (F.IgnoreNullPredecessors && !From)
3875 return true;
3876
3877 if (To && From && F.IgnoreDefaultsWithCoveredEnums) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003878 // If the 'To' has no label or is labeled but the label isn't a
3879 // CaseStmt then filter this edge.
3880 if (const SwitchStmt *S =
Ted Kremenek89794742011-03-07 22:04:39 +00003881 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) {
Ted Kremenekb0371852010-09-09 00:06:04 +00003882 if (S->isAllEnumCasesCovered()) {
Ted Kremenek89794742011-03-07 22:04:39 +00003883 const Stmt *L = To->getLabel();
3884 if (!L || !isa<CaseStmt>(L))
3885 return true;
Ted Kremenekb0371852010-09-09 00:06:04 +00003886 }
3887 }
3888 }
3889
3890 return false;
3891}
3892
3893//===----------------------------------------------------------------------===//
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00003894// CFG pretty printing
3895//===----------------------------------------------------------------------===//
3896
Ted Kremenek7e776b12007-08-22 18:22:34 +00003897namespace {
3898
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00003899class StmtPrinterHelper : public PrinterHelper {
Ted Kremenek96a7a592011-03-01 03:15:10 +00003900 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
3901 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003902 StmtMapTy StmtMap;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003903 DeclMapTy DeclMap;
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003904 signed currentBlock;
Ted Kremenekd94854a2012-08-22 06:26:15 +00003905 unsigned currStmt;
Chris Lattnerc61089a2009-06-30 01:26:17 +00003906 const LangOptions &LangOpts;
Ted Kremenek9aae5132007-08-23 21:42:29 +00003907public:
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003908
Chris Lattnerc61089a2009-06-30 01:26:17 +00003909 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
Ted Kremenekd94854a2012-08-22 06:26:15 +00003910 : currentBlock(0), currStmt(0), LangOpts(LO)
Ted Kremenek96a7a592011-03-01 03:15:10 +00003911 {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003912 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
3913 unsigned j = 1;
Ted Kremenek289ae4f2009-10-12 20:55:07 +00003914 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003915 BI != BEnd; ++BI, ++j ) {
David Blaikie00be69a2013-02-23 00:29:34 +00003916 if (Optional<CFGStmt> SE = BI->getAs<CFGStmt>()) {
3917 const Stmt *stmt= SE->getStmt();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003918 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j);
Ted Kremenek96a7a592011-03-01 03:15:10 +00003919 StmtMap[stmt] = P;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003920
Ted Kremenek96a7a592011-03-01 03:15:10 +00003921 switch (stmt->getStmtClass()) {
3922 case Stmt::DeclStmtClass:
3923 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P;
3924 break;
3925 case Stmt::IfStmtClass: {
3926 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable();
3927 if (var)
3928 DeclMap[var] = P;
3929 break;
3930 }
3931 case Stmt::ForStmtClass: {
3932 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable();
3933 if (var)
3934 DeclMap[var] = P;
3935 break;
3936 }
3937 case Stmt::WhileStmtClass: {
3938 const VarDecl *var =
3939 cast<WhileStmt>(stmt)->getConditionVariable();
3940 if (var)
3941 DeclMap[var] = P;
3942 break;
3943 }
3944 case Stmt::SwitchStmtClass: {
3945 const VarDecl *var =
3946 cast<SwitchStmt>(stmt)->getConditionVariable();
3947 if (var)
3948 DeclMap[var] = P;
3949 break;
3950 }
3951 case Stmt::CXXCatchStmtClass: {
3952 const VarDecl *var =
3953 cast<CXXCatchStmt>(stmt)->getExceptionDecl();
3954 if (var)
3955 DeclMap[var] = P;
3956 break;
3957 }
3958 default:
3959 break;
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003960 }
3961 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003962 }
Zhongxing Xu2cd7a782010-09-16 01:25:47 +00003963 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003964 }
Mike Stump31feda52009-07-17 01:31:16 +00003965
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003966 ~StmtPrinterHelper() override {}
Mike Stump31feda52009-07-17 01:31:16 +00003967
Chris Lattnerc61089a2009-06-30 01:26:17 +00003968 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003969 void setBlockID(signed i) { currentBlock = i; }
Ted Kremenekd94854a2012-08-22 06:26:15 +00003970 void setStmtID(unsigned i) { currStmt = i; }
Mike Stump31feda52009-07-17 01:31:16 +00003971
Craig Topperb45acb82014-03-14 06:02:07 +00003972 bool handledStmt(Stmt *S, raw_ostream &OS) override {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003973 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003974
3975 if (I == StmtMap.end())
3976 return false;
Mike Stump31feda52009-07-17 01:31:16 +00003977
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003978 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003979 && I->second.second == currStmt) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003980 return false;
Ted Kremenek60983dc2010-01-19 20:52:05 +00003981 }
Mike Stump31feda52009-07-17 01:31:16 +00003982
Ted Kremenek60983dc2010-01-19 20:52:05 +00003983 OS << "[B" << I->second.first << "." << I->second.second << "]";
Ted Kremenekf8b50e92007-08-31 22:26:13 +00003984 return true;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00003985 }
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003986
Ted Kremenek5ef32db2011-08-12 23:37:29 +00003987 bool handleDecl(const Decl *D, raw_ostream &OS) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003988 DeclMapTy::iterator I = DeclMap.find(D);
3989
3990 if (I == DeclMap.end())
3991 return false;
3992
Ted Kremenek3a9a2a52010-12-17 04:44:39 +00003993 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock
Ted Kremenekd94854a2012-08-22 06:26:15 +00003994 && I->second.second == currStmt) {
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00003995 return false;
3996 }
3997
3998 OS << "[B" << I->second.first << "." << I->second.second << "]";
3999 return true;
4000 }
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004001};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004002} // end anonymous namespace
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004003
Chris Lattnerc61089a2009-06-30 01:26:17 +00004004
4005namespace {
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +00004006class CFGBlockTerminatorPrint
Ted Kremenek83ebcef2008-01-08 18:15:10 +00004007 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
Mike Stump31feda52009-07-17 01:31:16 +00004008
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004009 raw_ostream &OS;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004010 StmtPrinterHelper* Helper;
Douglas Gregor7de59662009-05-29 20:38:28 +00004011 PrintingPolicy Policy;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004012public:
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004013 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper,
Chris Lattnerc61089a2009-06-30 01:26:17 +00004014 const PrintingPolicy &Policy)
Ted Kremenek5d0fb1e2013-12-11 23:44:05 +00004015 : OS(os), Helper(helper), Policy(Policy) {
4016 this->Policy.IncludeNewlines = false;
4017 }
Mike Stump31feda52009-07-17 01:31:16 +00004018
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004019 void VisitIfStmt(IfStmt *I) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004020 OS << "if ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004021 if (Stmt *C = I->getCond())
4022 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004023 }
Mike Stump31feda52009-07-17 01:31:16 +00004024
Ted Kremenek9aae5132007-08-23 21:42:29 +00004025 // Default case.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004026 void VisitStmt(Stmt *Terminator) {
Mike Stump31feda52009-07-17 01:31:16 +00004027 Terminator->printPretty(OS, Helper, Policy);
4028 }
4029
Ted Kremenek0dd8fee2013-03-28 18:43:15 +00004030 void VisitDeclStmt(DeclStmt *DS) {
4031 VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
4032 OS << "static init " << VD->getName();
4033 }
4034
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004035 void VisitForStmt(ForStmt *F) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004036 OS << "for (" ;
Ted Kremenek60983dc2010-01-19 20:52:05 +00004037 if (F->getInit())
4038 OS << "...";
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004039 OS << "; ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004040 if (Stmt *C = F->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004041 C->printPretty(OS, Helper, Policy);
Ted Kremenekfc7aafc2007-08-30 21:28:02 +00004042 OS << "; ";
Ted Kremenek60983dc2010-01-19 20:52:05 +00004043 if (F->getInc())
4044 OS << "...";
Ted Kremenek15647632008-01-30 23:02:42 +00004045 OS << ")";
Ted Kremenek9aae5132007-08-23 21:42:29 +00004046 }
Mike Stump31feda52009-07-17 01:31:16 +00004047
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004048 void VisitWhileStmt(WhileStmt *W) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004049 OS << "while " ;
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004050 if (Stmt *C = W->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004051 C->printPretty(OS, Helper, Policy);
Ted Kremenek9aae5132007-08-23 21:42:29 +00004052 }
Mike Stump31feda52009-07-17 01:31:16 +00004053
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004054 void VisitDoStmt(DoStmt *D) {
Ted Kremenek9aae5132007-08-23 21:42:29 +00004055 OS << "do ... while ";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004056 if (Stmt *C = D->getCond())
Ted Kremenek60983dc2010-01-19 20:52:05 +00004057 C->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004058 }
Mike Stump31feda52009-07-17 01:31:16 +00004059
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004060 void VisitSwitchStmt(SwitchStmt *Terminator) {
Ted Kremenek9e248872007-08-27 21:27:44 +00004061 OS << "switch ";
Douglas Gregor7de59662009-05-29 20:38:28 +00004062 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9e248872007-08-27 21:27:44 +00004063 }
Mike Stump31feda52009-07-17 01:31:16 +00004064
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004065 void VisitCXXTryStmt(CXXTryStmt *CS) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004066 OS << "try ...";
4067 }
4068
John McCallc07a0c72011-02-17 10:25:35 +00004069 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00004070 if (Stmt *Cond = C->getCond())
4071 Cond->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004072 OS << " ? ... : ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004073 }
Mike Stump31feda52009-07-17 01:31:16 +00004074
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004075 void VisitChooseExpr(ChooseExpr *C) {
Ted Kremenek391f94a2007-08-31 22:29:13 +00004076 OS << "__builtin_choose_expr( ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004077 if (Stmt *Cond = C->getCond())
4078 Cond->printPretty(OS, Helper, Policy);
Ted Kremenek15647632008-01-30 23:02:42 +00004079 OS << " )";
Ted Kremenek391f94a2007-08-31 22:29:13 +00004080 }
Mike Stump31feda52009-07-17 01:31:16 +00004081
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004082 void VisitIndirectGotoStmt(IndirectGotoStmt *I) {
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004083 OS << "goto *";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004084 if (Stmt *T = I->getTarget())
4085 T->printPretty(OS, Helper, Policy);
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004086 }
Mike Stump31feda52009-07-17 01:31:16 +00004087
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004088 void VisitBinaryOperator(BinaryOperator* B) {
4089 if (!B->isLogicalOp()) {
4090 VisitExpr(B);
4091 return;
4092 }
Mike Stump31feda52009-07-17 01:31:16 +00004093
Richard Trieuddd01ce2014-06-09 22:53:25 +00004094 if (B->getLHS())
4095 B->getLHS()->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004096
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004097 switch (B->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004098 case BO_LOr:
Ted Kremenek15647632008-01-30 23:02:42 +00004099 OS << " || ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004100 return;
John McCalle3027922010-08-25 11:45:40 +00004101 case BO_LAnd:
Ted Kremenek15647632008-01-30 23:02:42 +00004102 OS << " && ...";
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004103 return;
4104 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004105 llvm_unreachable("Invalid logical operator.");
Mike Stump31feda52009-07-17 01:31:16 +00004106 }
Ted Kremenek7f7dd762007-08-31 21:49:40 +00004107 }
Mike Stump31feda52009-07-17 01:31:16 +00004108
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004109 void VisitExpr(Expr *E) {
Douglas Gregor7de59662009-05-29 20:38:28 +00004110 E->printPretty(OS, Helper, Policy);
Mike Stump31feda52009-07-17 01:31:16 +00004111 }
Ted Kremenekfcc14172014-03-08 02:22:29 +00004112
4113public:
4114 void print(CFGTerminator T) {
4115 if (T.isTemporaryDtorsBranch())
4116 OS << "(Temp Dtor) ";
4117 Visit(T.getStmt());
4118 }
Ted Kremenek9aae5132007-08-23 21:42:29 +00004119};
Chris Lattnerc61089a2009-06-30 01:26:17 +00004120} // end anonymous namespace
4121
Aaron Ballmanff924b02013-11-18 20:11:50 +00004122static void print_elem(raw_ostream &OS, StmtPrinterHelper &Helper,
Mike Stump92244b02010-01-19 22:00:14 +00004123 const CFGElement &E) {
David Blaikie00be69a2013-02-23 00:29:34 +00004124 if (Optional<CFGStmt> CS = E.getAs<CFGStmt>()) {
4125 const Stmt *S = CS->getStmt();
Richard Trieuddd01ce2014-06-09 22:53:25 +00004126 assert(S != nullptr && "Expecting non-null Stmt");
4127
Aaron Ballmanff924b02013-11-18 20:11:50 +00004128 // special printing for statement-expressions.
4129 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) {
4130 const CompoundStmt *Sub = SE->getSubStmt();
Mike Stump31feda52009-07-17 01:31:16 +00004131
Aaron Ballmanff924b02013-11-18 20:11:50 +00004132 if (Sub->children()) {
4133 OS << "({ ... ; ";
4134 Helper.handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
4135 OS << " })\n";
4136 return;
Ted Kremenekf8b50e92007-08-31 22:26:13 +00004137 }
4138 }
Aaron Ballmanff924b02013-11-18 20:11:50 +00004139 // special printing for comma expressions.
4140 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
4141 if (B->getOpcode() == BO_Comma) {
4142 OS << "... , ";
4143 Helper.handledStmt(B->getRHS(),OS);
4144 OS << '\n';
4145 return;
4146 }
4147 }
4148 S->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Mike Stump31feda52009-07-17 01:31:16 +00004149
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004150 if (isa<CXXOperatorCallExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004151 OS << " (OperatorCall)";
Ted Kremenek0ffba932011-12-21 19:32:38 +00004152 }
4153 else if (isa<CXXBindTemporaryExpr>(S)) {
Zhanyong Wan59f09c72010-11-22 19:32:14 +00004154 OS << " (BindTemporary)";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004155 }
Ted Kremenek1a7648b2011-12-21 19:39:59 +00004156 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) {
4157 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")";
4158 }
Ted Kremenek0ffba932011-12-21 19:32:38 +00004159 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) {
4160 OS << " (" << CE->getStmtClassName() << ", "
4161 << CE->getCastKindName()
4162 << ", " << CE->getType().getAsString()
4163 << ")";
4164 }
Mike Stump31feda52009-07-17 01:31:16 +00004165
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004166 // Expressions need a newline.
4167 if (isa<Expr>(S))
4168 OS << '\n';
Ted Kremenek0f5d8bc2010-08-31 18:47:37 +00004169
David Blaikie00be69a2013-02-23 00:29:34 +00004170 } else if (Optional<CFGInitializer> IE = E.getAs<CFGInitializer>()) {
4171 const CXXCtorInitializer *I = IE->getInitializer();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004172 if (I->isBaseInitializer())
4173 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName();
Jordan Rose69d0aed2013-10-22 23:19:47 +00004174 else if (I->isDelegatingInitializer())
4175 OS << I->getTypeSourceInfo()->getType()->getAsCXXRecordDecl()->getName();
Francois Pichetd583da02010-12-04 09:14:42 +00004176 else OS << I->getAnyMember()->getName();
Mike Stump31feda52009-07-17 01:31:16 +00004177
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004178 OS << "(";
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004179 if (Expr *IE = I->getInit())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004180 IE->printPretty(OS, &Helper, PrintingPolicy(Helper.getLangOpts()));
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004181 OS << ")";
4182
4183 if (I->isBaseInitializer())
4184 OS << " (Base initializer)\n";
Jordan Rose69d0aed2013-10-22 23:19:47 +00004185 else if (I->isDelegatingInitializer())
4186 OS << " (Delegating initializer)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004187 else OS << " (Member initializer)\n";
4188
David Blaikie00be69a2013-02-23 00:29:34 +00004189 } else if (Optional<CFGAutomaticObjDtor> DE =
4190 E.getAs<CFGAutomaticObjDtor>()) {
4191 const VarDecl *VD = DE->getVarDecl();
Aaron Ballmanff924b02013-11-18 20:11:50 +00004192 Helper.handleDecl(VD, OS);
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004193
Marcin Swiderski52e4bc12010-10-25 07:00:40 +00004194 const Type* T = VD->getType().getTypePtr();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004195 if (const ReferenceType* RT = T->getAs<ReferenceType>())
4196 T = RT->getPointeeType().getTypePtr();
Richard Smithf676e452012-07-24 21:02:14 +00004197 T = T->getBaseElementTypeUnsafe();
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004198
4199 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()";
4200 OS << " (Implicit destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004201
Jordan Rosec9176072014-01-13 17:59:19 +00004202 } else if (Optional<CFGNewAllocator> NE = E.getAs<CFGNewAllocator>()) {
4203 OS << "CFGNewAllocator(";
4204 if (const CXXNewExpr *AllocExpr = NE->getAllocatorExpr())
4205 AllocExpr->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
4206 OS << ")\n";
Jordan Rosed2f40792013-09-03 17:00:57 +00004207 } else if (Optional<CFGDeleteDtor> DE = E.getAs<CFGDeleteDtor>()) {
4208 const CXXRecordDecl *RD = DE->getCXXRecordDecl();
4209 if (!RD)
4210 return;
4211 CXXDeleteExpr *DelExpr =
4212 const_cast<CXXDeleteExpr*>(DE->getDeleteExpr());
Aaron Ballmanff924b02013-11-18 20:11:50 +00004213 Helper.handledStmt(cast<Stmt>(DelExpr->getArgument()), OS);
Jordan Rosed2f40792013-09-03 17:00:57 +00004214 OS << "->~" << RD->getName().str() << "()";
4215 OS << " (Implicit destructor)\n";
David Blaikie00be69a2013-02-23 00:29:34 +00004216 } else if (Optional<CFGBaseDtor> BE = E.getAs<CFGBaseDtor>()) {
4217 const CXXBaseSpecifier *BS = BE->getBaseSpecifier();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004218 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004219 OS << " (Base object destructor)\n";
Marcin Swiderski20b88732010-10-05 05:37:00 +00004220
David Blaikie00be69a2013-02-23 00:29:34 +00004221 } else if (Optional<CFGMemberDtor> ME = E.getAs<CFGMemberDtor>()) {
4222 const FieldDecl *FD = ME->getFieldDecl();
Richard Smithf676e452012-07-24 21:02:14 +00004223 const Type *T = FD->getType()->getBaseElementTypeUnsafe();
Marcin Swiderski20b88732010-10-05 05:37:00 +00004224 OS << "this->" << FD->getName();
Marcin Swiderski01769902010-10-25 07:05:54 +00004225 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()";
Zhongxing Xu614e17d2010-10-05 08:38:06 +00004226 OS << " (Member object destructor)\n";
Marcin Swiderski3ab17ad2010-11-03 06:19:35 +00004227
David Blaikie00be69a2013-02-23 00:29:34 +00004228 } else if (Optional<CFGTemporaryDtor> TE = E.getAs<CFGTemporaryDtor>()) {
4229 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr();
Pavel Labathd527cf82013-09-02 09:09:15 +00004230 OS << "~";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004231 BT->getType().print(OS, PrintingPolicy(Helper.getLangOpts()));
Pavel Labathd527cf82013-09-02 09:09:15 +00004232 OS << "() (Temporary object destructor)\n";
Marcin Swiderskic0ca7312010-09-21 05:58:15 +00004233 }
Zhongxing Xu0b51d4d2010-11-01 06:46:05 +00004234}
Mike Stump31feda52009-07-17 01:31:16 +00004235
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004236static void print_block(raw_ostream &OS, const CFG* cfg,
4237 const CFGBlock &B,
Aaron Ballmanff924b02013-11-18 20:11:50 +00004238 StmtPrinterHelper &Helper, bool print_edges,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004239 bool ShowColors) {
Mike Stump31feda52009-07-17 01:31:16 +00004240
Aaron Ballmanff924b02013-11-18 20:11:50 +00004241 Helper.setBlockID(B.getBlockID());
Mike Stump31feda52009-07-17 01:31:16 +00004242
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004243 // Print the header.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004244 if (ShowColors)
4245 OS.changeColor(raw_ostream::YELLOW, true);
4246
4247 OS << "\n [B" << B.getBlockID();
Mike Stump31feda52009-07-17 01:31:16 +00004248
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004249 if (&B == &cfg->getEntry())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004250 OS << " (ENTRY)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004251 else if (&B == &cfg->getExit())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004252 OS << " (EXIT)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004253 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek72be32a2011-12-22 23:33:52 +00004254 OS << " (INDIRECT GOTO DISPATCH)]\n";
Jordan Rose398fb002014-04-01 16:39:33 +00004255 else if (B.hasNoReturnElement())
4256 OS << " (NORETURN)]\n";
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004257 else
Ted Kremenek72be32a2011-12-22 23:33:52 +00004258 OS << "]\n";
4259
4260 if (ShowColors)
4261 OS.resetColor();
Mike Stump31feda52009-07-17 01:31:16 +00004262
Ted Kremenek71eca012007-08-29 23:20:49 +00004263 // Print the label of this block.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004264 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004265
4266 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004267 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004268
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004269 if (LabelStmt *L = dyn_cast<LabelStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004270 OS << L->getName();
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004271 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
Ted Kremenek71eca012007-08-29 23:20:49 +00004272 OS << "case ";
Richard Trieuddd01ce2014-06-09 22:53:25 +00004273 if (C->getLHS())
4274 C->getLHS()->printPretty(OS, &Helper,
4275 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004276 if (C->getRHS()) {
4277 OS << " ... ";
Aaron Ballmanff924b02013-11-18 20:11:50 +00004278 C->getRHS()->printPretty(OS, &Helper,
4279 PrintingPolicy(Helper.getLangOpts()));
Ted Kremenek71eca012007-08-29 23:20:49 +00004280 }
Mike Stump92244b02010-01-19 22:00:14 +00004281 } else if (isa<DefaultStmt>(Label))
Ted Kremenek71eca012007-08-29 23:20:49 +00004282 OS << "default";
Mike Stump92244b02010-01-19 22:00:14 +00004283 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004284 OS << "catch (";
Mike Stump0bdba6c2010-01-20 01:15:34 +00004285 if (CS->getExceptionDecl())
Aaron Ballmanff924b02013-11-18 20:11:50 +00004286 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper.getLangOpts()),
Mike Stump0bdba6c2010-01-20 01:15:34 +00004287 0);
4288 else
4289 OS << "...";
Mike Stumpbbf5ba62010-01-19 02:20:09 +00004290 OS << ")";
4291
4292 } else
David Blaikie83d382b2011-09-23 05:06:16 +00004293 llvm_unreachable("Invalid label statement in CFGBlock.");
Mike Stump31feda52009-07-17 01:31:16 +00004294
Ted Kremenek71eca012007-08-29 23:20:49 +00004295 OS << ":\n";
4296 }
Mike Stump31feda52009-07-17 01:31:16 +00004297
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004298 // Iterate through the statements in the block and print them.
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004299 unsigned j = 1;
Mike Stump31feda52009-07-17 01:31:16 +00004300
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004301 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
4302 I != E ; ++I, ++j ) {
Mike Stump31feda52009-07-17 01:31:16 +00004303
Ted Kremenek71eca012007-08-29 23:20:49 +00004304 // Print the statement # in the basic block and the statement itself.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004305 if (print_edges)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004306 OS << " ";
Mike Stump31feda52009-07-17 01:31:16 +00004307
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004308 OS << llvm::format("%3d", j) << ": ";
Mike Stump31feda52009-07-17 01:31:16 +00004309
Aaron Ballmanff924b02013-11-18 20:11:50 +00004310 Helper.setStmtID(j);
Mike Stump31feda52009-07-17 01:31:16 +00004311
Ted Kremenek72be32a2011-12-22 23:33:52 +00004312 print_elem(OS, Helper, *I);
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004313 }
Mike Stump31feda52009-07-17 01:31:16 +00004314
Ted Kremenek71eca012007-08-29 23:20:49 +00004315 // Print the terminator of this block.
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004316 if (B.getTerminator()) {
Ted Kremenek72be32a2011-12-22 23:33:52 +00004317 if (ShowColors)
4318 OS.changeColor(raw_ostream::GREEN);
Mike Stump31feda52009-07-17 01:31:16 +00004319
Ted Kremenek72be32a2011-12-22 23:33:52 +00004320 OS << " T: ";
Mike Stump31feda52009-07-17 01:31:16 +00004321
Aaron Ballmanff924b02013-11-18 20:11:50 +00004322 Helper.setBlockID(-1);
Mike Stump31feda52009-07-17 01:31:16 +00004323
Aaron Ballmanff924b02013-11-18 20:11:50 +00004324 PrintingPolicy PP(Helper.getLangOpts());
4325 CFGBlockTerminatorPrint TPrinter(OS, &Helper, PP);
Ted Kremenekfcc14172014-03-08 02:22:29 +00004326 TPrinter.print(B.getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004327 OS << '\n';
Ted Kremenek72be32a2011-12-22 23:33:52 +00004328
4329 if (ShowColors)
4330 OS.resetColor();
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004331 }
Mike Stump31feda52009-07-17 01:31:16 +00004332
Ted Kremenek71eca012007-08-29 23:20:49 +00004333 if (print_edges) {
4334 // Print the predecessors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004335 if (!B.pred_empty()) {
4336 const raw_ostream::Colors Color = raw_ostream::BLUE;
4337 if (ShowColors)
4338 OS.changeColor(Color);
4339 OS << " Preds " ;
4340 if (ShowColors)
4341 OS.resetColor();
4342 OS << '(' << B.pred_size() << "):";
4343 unsigned i = 0;
Ted Kremenek71eca012007-08-29 23:20:49 +00004344
Ted Kremenek72be32a2011-12-22 23:33:52 +00004345 if (ShowColors)
4346 OS.changeColor(Color);
4347
4348 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
4349 I != E; ++I, ++i) {
Mike Stump31feda52009-07-17 01:31:16 +00004350
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004351 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004352 OS << "\n ";
Mike Stump31feda52009-07-17 01:31:16 +00004353
Ted Kremenek4b6fee62014-02-27 00:24:00 +00004354 CFGBlock *B = *I;
4355 bool Reachable = true;
4356 if (!B) {
4357 Reachable = false;
4358 B = I->getPossiblyUnreachableBlock();
4359 }
4360
4361 OS << " B" << B->getBlockID();
4362 if (!Reachable)
4363 OS << "(Unreachable)";
Ted Kremenek72be32a2011-12-22 23:33:52 +00004364 }
4365
4366 if (ShowColors)
4367 OS.resetColor();
4368
4369 OS << '\n';
Ted Kremenek71eca012007-08-29 23:20:49 +00004370 }
Mike Stump31feda52009-07-17 01:31:16 +00004371
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004372 // Print the successors of this block.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004373 if (!B.succ_empty()) {
4374 const raw_ostream::Colors Color = raw_ostream::MAGENTA;
4375 if (ShowColors)
4376 OS.changeColor(Color);
4377 OS << " Succs ";
4378 if (ShowColors)
4379 OS.resetColor();
4380 OS << '(' << B.succ_size() << "):";
4381 unsigned i = 0;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004382
Ted Kremenek72be32a2011-12-22 23:33:52 +00004383 if (ShowColors)
4384 OS.changeColor(Color);
Mike Stump31feda52009-07-17 01:31:16 +00004385
Ted Kremenek72be32a2011-12-22 23:33:52 +00004386 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
4387 I != E; ++I, ++i) {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004388
Will Dietzdf9a2bb2013-01-07 09:51:17 +00004389 if (i % 10 == 8)
Ted Kremenek72be32a2011-12-22 23:33:52 +00004390 OS << "\n ";
4391
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004392 CFGBlock *B = *I;
4393
4394 bool Reachable = true;
4395 if (!B) {
4396 Reachable = false;
4397 B = I->getPossiblyUnreachableBlock();
4398 }
4399
4400 if (B) {
4401 OS << " B" << B->getBlockID();
4402 if (!Reachable)
4403 OS << "(Unreachable)";
4404 }
4405 else {
4406 OS << " NULL";
4407 }
Ted Kremenek72be32a2011-12-22 23:33:52 +00004408 }
Ted Kremenek9238c5c2014-02-27 21:56:44 +00004409
Ted Kremenek72be32a2011-12-22 23:33:52 +00004410 if (ShowColors)
4411 OS.resetColor();
4412 OS << '\n';
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004413 }
Ted Kremenek4aa1e8b2007-08-21 21:42:03 +00004414 }
Mike Stump31feda52009-07-17 01:31:16 +00004415}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004416
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004417
4418/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004419void CFG::dump(const LangOptions &LO, bool ShowColors) const {
4420 print(llvm::errs(), LO, ShowColors);
4421}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004422
4423/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004424void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004425 StmtPrinterHelper Helper(this, LO);
Mike Stump31feda52009-07-17 01:31:16 +00004426
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004427 // Print the entry block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004428 print_block(OS, this, getEntry(), Helper, true, ShowColors);
Mike Stump31feda52009-07-17 01:31:16 +00004429
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004430 // Iterate through the CFGBlocks and print them one by one.
4431 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
4432 // Skip the entry block, because we already printed it.
Ted Kremenek289ae4f2009-10-12 20:55:07 +00004433 if (&(**I) == &getEntry() || &(**I) == &getExit())
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004434 continue;
Mike Stump31feda52009-07-17 01:31:16 +00004435
Aaron Ballmanff924b02013-11-18 20:11:50 +00004436 print_block(OS, this, **I, Helper, true, ShowColors);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004437 }
Mike Stump31feda52009-07-17 01:31:16 +00004438
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004439 // Print the exit block.
Aaron Ballmanff924b02013-11-18 20:11:50 +00004440 print_block(OS, this, getExit(), Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004441 OS << '\n';
Ted Kremeneke03879b2008-11-24 20:50:24 +00004442 OS.flush();
Mike Stump31feda52009-07-17 01:31:16 +00004443}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004444
4445/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek72be32a2011-12-22 23:33:52 +00004446void CFGBlock::dump(const CFG* cfg, const LangOptions &LO,
4447 bool ShowColors) const {
4448 print(llvm::errs(), cfg, LO, ShowColors);
Chris Lattnerc61089a2009-06-30 01:26:17 +00004449}
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004450
Anna Zaksa6fea132014-06-13 23:47:38 +00004451void CFGBlock::dump() const {
4452 dump(getParent(), LangOptions(), false);
4453}
4454
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004455/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
4456/// Generally this will only be called from CFG::print.
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004457void CFGBlock::print(raw_ostream &OS, const CFG* cfg,
Ted Kremenek72be32a2011-12-22 23:33:52 +00004458 const LangOptions &LO, bool ShowColors) const {
Chris Lattnerc61089a2009-06-30 01:26:17 +00004459 StmtPrinterHelper Helper(cfg, LO);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004460 print_block(OS, cfg, *this, Helper, true, ShowColors);
Ted Kremenek72be32a2011-12-22 23:33:52 +00004461 OS << '\n';
Ted Kremenek889073f2007-08-23 16:51:22 +00004462}
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004463
Ted Kremenek15647632008-01-30 23:02:42 +00004464/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004465void CFGBlock::printTerminator(raw_ostream &OS,
Mike Stump31feda52009-07-17 01:31:16 +00004466 const LangOptions &LO) const {
Craig Topper25542942014-05-20 04:30:07 +00004467 CFGBlockTerminatorPrint TPrinter(OS, nullptr, PrintingPolicy(LO));
Ted Kremenekfcc14172014-03-08 02:22:29 +00004468 TPrinter.print(getTerminator());
Ted Kremenek15647632008-01-30 23:02:42 +00004469}
4470
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004471Stmt *CFGBlock::getTerminatorCondition(bool StripParens) {
Marcin Swiderskia7d84a72010-10-29 05:21:47 +00004472 Stmt *Terminator = this->Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004473 if (!Terminator)
Craig Topper25542942014-05-20 04:30:07 +00004474 return nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004475
Craig Topper25542942014-05-20 04:30:07 +00004476 Expr *E = nullptr;
Mike Stump31feda52009-07-17 01:31:16 +00004477
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004478 switch (Terminator->getStmtClass()) {
4479 default:
4480 break;
Mike Stump31feda52009-07-17 01:31:16 +00004481
Jordan Rosecf10ea82013-06-06 21:53:45 +00004482 case Stmt::CXXForRangeStmtClass:
4483 E = cast<CXXForRangeStmt>(Terminator)->getCond();
4484 break;
4485
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004486 case Stmt::ForStmtClass:
4487 E = cast<ForStmt>(Terminator)->getCond();
4488 break;
Mike Stump31feda52009-07-17 01:31:16 +00004489
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004490 case Stmt::WhileStmtClass:
4491 E = cast<WhileStmt>(Terminator)->getCond();
4492 break;
Mike Stump31feda52009-07-17 01:31:16 +00004493
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004494 case Stmt::DoStmtClass:
4495 E = cast<DoStmt>(Terminator)->getCond();
4496 break;
Mike Stump31feda52009-07-17 01:31:16 +00004497
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004498 case Stmt::IfStmtClass:
4499 E = cast<IfStmt>(Terminator)->getCond();
4500 break;
Mike Stump31feda52009-07-17 01:31:16 +00004501
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004502 case Stmt::ChooseExprClass:
4503 E = cast<ChooseExpr>(Terminator)->getCond();
4504 break;
Mike Stump31feda52009-07-17 01:31:16 +00004505
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004506 case Stmt::IndirectGotoStmtClass:
4507 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
4508 break;
Mike Stump31feda52009-07-17 01:31:16 +00004509
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004510 case Stmt::SwitchStmtClass:
4511 E = cast<SwitchStmt>(Terminator)->getCond();
4512 break;
Mike Stump31feda52009-07-17 01:31:16 +00004513
John McCallc07a0c72011-02-17 10:25:35 +00004514 case Stmt::BinaryConditionalOperatorClass:
4515 E = cast<BinaryConditionalOperator>(Terminator)->getCond();
4516 break;
4517
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004518 case Stmt::ConditionalOperatorClass:
4519 E = cast<ConditionalOperator>(Terminator)->getCond();
4520 break;
Mike Stump31feda52009-07-17 01:31:16 +00004521
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004522 case Stmt::BinaryOperatorClass: // '&&' and '||'
4523 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004524 break;
Mike Stump31feda52009-07-17 01:31:16 +00004525
Ted Kremenek6d8b46e2008-11-12 21:11:49 +00004526 case Stmt::ObjCForCollectionStmtClass:
Mike Stump31feda52009-07-17 01:31:16 +00004527 return Terminator;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004528 }
Mike Stump31feda52009-07-17 01:31:16 +00004529
Ted Kremenekec3bbf42014-03-29 00:35:20 +00004530 if (!StripParens)
4531 return E;
4532
Craig Topper25542942014-05-20 04:30:07 +00004533 return E ? E->IgnoreParens() : nullptr;
Ted Kremenekc1f9a282008-04-16 21:10:48 +00004534}
4535
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004536//===----------------------------------------------------------------------===//
4537// CFG Graphviz Visualization
4538//===----------------------------------------------------------------------===//
4539
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004540
4541#ifndef NDEBUG
Mike Stump31feda52009-07-17 01:31:16 +00004542static StmtPrinterHelper* GraphHelper;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004543#endif
4544
Chris Lattnerc61089a2009-06-30 01:26:17 +00004545void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004546#ifndef NDEBUG
Chris Lattnerc61089a2009-06-30 01:26:17 +00004547 StmtPrinterHelper H(this, LO);
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004548 GraphHelper = &H;
4549 llvm::ViewGraph(this,"CFG");
Craig Topper25542942014-05-20 04:30:07 +00004550 GraphHelper = nullptr;
Ted Kremenek04f3cee2007-08-31 21:30:12 +00004551#endif
4552}
4553
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004554namespace llvm {
4555template<>
4556struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Tobias Grosser9fc223a2009-11-30 14:16:05 +00004557
4558 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
4559
Ted Kremenek5ef32db2011-08-12 23:37:29 +00004560 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) {
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004561
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004562#ifndef NDEBUG
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004563 std::string OutSStr;
4564 llvm::raw_string_ostream Out(OutSStr);
Aaron Ballmanff924b02013-11-18 20:11:50 +00004565 print_block(Out,Graph, *Node, *GraphHelper, false, false);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00004566 std::string& OutStr = Out.str();
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004567
4568 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
4569
4570 // Process string output to make it nicer...
4571 for (unsigned i = 0; i != OutStr.length(); ++i)
4572 if (OutStr[i] == '\n') { // Left justify
4573 OutStr[i] = '\\';
4574 OutStr.insert(OutStr.begin()+i+1, 'l');
4575 }
Mike Stump31feda52009-07-17 01:31:16 +00004576
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004577 return OutStr;
Hartmut Kaiser04bd2ef2007-09-16 00:28:28 +00004578#else
4579 return "";
4580#endif
Ted Kremenek4e5f99d2007-08-29 21:56:09 +00004581 }
4582};
4583} // end namespace llvm