blob: 38db72a150b3183d5ea39c62f010e146aa47ff5e [file] [log] [blame]
Benjamin Kramera93d0f22012-12-01 17:12:56 +00001//=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Live Variables analysis for source-level CFGs.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcf6e41b2007-12-21 21:42:19 +000014#include "clang/Analysis/Analyses/LiveVariables.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000015#include "clang/AST/Stmt.h"
Ted Kremenek88299892011-07-28 23:07:59 +000016#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Analysis/Analyses/PostOrderCFGView.h"
18#include "clang/Analysis/AnalysisContext.h"
19#include "clang/Analysis/CFG.h"
Ted Kremenek87aa1252011-09-16 23:01:39 +000020#include "llvm/ADT/DenseMap.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000021#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/Support/raw_ostream.h"
Ted Kremenek88299892011-07-28 23:07:59 +000023#include <algorithm>
24#include <vector>
Ted Kremeneke4e63342007-09-06 00:17:54 +000025
26using namespace clang;
27
Ted Kremeneke4e63342007-09-06 00:17:54 +000028namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000029
Ted Kremenek87aa1252011-09-16 23:01:39 +000030class DataflowWorklist {
31 SmallVector<const CFGBlock *, 20> worklist;
32 llvm::BitVector enqueuedBlocks;
Ted Kremenekedb18632011-10-22 02:14:23 +000033 PostOrderCFGView *POV;
Ted Kremenek87aa1252011-09-16 23:01:39 +000034public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000035 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
Ted Kremenek87aa1252011-09-16 23:01:39 +000036 : enqueuedBlocks(cfg.getNumBlockIDs()),
Ted Kremenekedb18632011-10-22 02:14:23 +000037 POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +000038
39 void enqueueBlock(const CFGBlock *block);
40 void enqueueSuccessors(const CFGBlock *block);
41 void enqueuePredecessors(const CFGBlock *block);
42
43 const CFGBlock *dequeue();
44
45 void sortWorklist();
46};
47
48}
49
50void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
51 if (block && !enqueuedBlocks[block->getBlockID()]) {
52 enqueuedBlocks[block->getBlockID()] = true;
53 worklist.push_back(block);
54 }
55}
56
57void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
58 const unsigned OldWorklistSize = worklist.size();
59 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
60 E = block->succ_end(); I != E; ++I) {
61 enqueueBlock(*I);
62 }
63
64 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
65 return;
66
67 sortWorklist();
68}
69
70void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
71 const unsigned OldWorklistSize = worklist.size();
72 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
73 E = block->pred_end(); I != E; ++I) {
74 enqueueBlock(*I);
75 }
76
77 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
78 return;
79
80 sortWorklist();
81}
82
83void DataflowWorklist::sortWorklist() {
Ted Kremenekedb18632011-10-22 02:14:23 +000084 std::sort(worklist.begin(), worklist.end(), POV->getComparator());
Ted Kremenek87aa1252011-09-16 23:01:39 +000085}
86
Ted Kremenek87aa1252011-09-16 23:01:39 +000087const CFGBlock *DataflowWorklist::dequeue() {
88 if (worklist.empty())
89 return 0;
Robert Wilhelm344472e2013-08-23 16:11:15 +000090 const CFGBlock *b = worklist.pop_back_val();
Ted Kremenek87aa1252011-09-16 23:01:39 +000091 enqueuedBlocks[b->getBlockID()] = false;
92 return b;
93}
94
95namespace {
96class LiveVariablesImpl {
97public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000098 AnalysisDeclContext &analysisContext;
Ted Kremenek87aa1252011-09-16 23:01:39 +000099 std::vector<LiveVariables::LivenessValues> cfgBlockValues;
100 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
101 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
102 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
103 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
104 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
105 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
106 const bool killAtAssign;
107
108 LiveVariables::LivenessValues
109 merge(LiveVariables::LivenessValues valsA,
110 LiveVariables::LivenessValues valsB);
111
112 LiveVariables::LivenessValues runOnBlock(const CFGBlock *block,
113 LiveVariables::LivenessValues val,
114 LiveVariables::Observer *obs = 0);
115
116 void dumpBlockLiveness(const SourceManager& M);
117
Ted Kremenek1d26f482011-10-24 01:32:45 +0000118 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000119 : analysisContext(ac),
120 SSetFact(false), // Do not canonicalize ImmutableSets by default.
121 DSetFact(false), // This is a *major* performance win.
122 killAtAssign(KillAtAssign) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +0000123};
Ted Kremenek88299892011-07-28 23:07:59 +0000124}
Ted Kremenek7deed0c2008-04-15 18:35:30 +0000125
Ted Kremenek9c378f72011-08-12 23:37:29 +0000126static LiveVariablesImpl &getImpl(void *x) {
Ted Kremenek88299892011-07-28 23:07:59 +0000127 return *((LiveVariablesImpl *) x);
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000128}
Ted Kremeneke4e63342007-09-06 00:17:54 +0000129
130//===----------------------------------------------------------------------===//
Ted Kremenek88299892011-07-28 23:07:59 +0000131// Operations and queries on LivenessValues.
132//===----------------------------------------------------------------------===//
133
134bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
135 return liveStmts.contains(S);
136}
137
138bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
139 return liveDecls.contains(D);
140}
141
142namespace {
143 template <typename SET>
Ted Kremenek87aa1252011-09-16 23:01:39 +0000144 SET mergeSets(SET A, SET B) {
145 if (A.isEmpty())
146 return B;
147
Ted Kremenek88299892011-07-28 23:07:59 +0000148 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000149 A = A.add(*it);
Ted Kremenek88299892011-07-28 23:07:59 +0000150 }
151 return A;
152 }
153}
154
David Blaikie99ba9e32011-12-20 02:48:34 +0000155void LiveVariables::Observer::anchor() { }
156
Ted Kremenek88299892011-07-28 23:07:59 +0000157LiveVariables::LivenessValues
158LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
159 LiveVariables::LivenessValues valsB) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000160
161 llvm::ImmutableSetRef<const Stmt *>
162 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
163 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
164
165
166 llvm::ImmutableSetRef<const VarDecl *>
167 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
168 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
169
170
171 SSetRefA = mergeSets(SSetRefA, SSetRefB);
172 DSetRefA = mergeSets(DSetRefA, DSetRefB);
173
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000174 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
175 // comparison afterwards.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000176 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
177 DSetRefA.asImmutableSet());
Ted Kremenek88299892011-07-28 23:07:59 +0000178}
179
180bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
181 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
182}
183
184//===----------------------------------------------------------------------===//
185// Query methods.
186//===----------------------------------------------------------------------===//
187
188static bool isAlwaysAlive(const VarDecl *D) {
189 return D->hasGlobalStorage();
190}
191
192bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
193 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
194}
195
196bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
197 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
198}
199
200bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
201 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
202}
203
204//===----------------------------------------------------------------------===//
205// Dataflow computation.
Mike Stump1eb44332009-09-09 15:08:12 +0000206//===----------------------------------------------------------------------===//
Ted Kremeneke4e63342007-09-06 00:17:54 +0000207
208namespace {
Ted Kremenek88299892011-07-28 23:07:59 +0000209class TransferFunctions : public StmtVisitor<TransferFunctions> {
210 LiveVariablesImpl &LV;
211 LiveVariables::LivenessValues &val;
212 LiveVariables::Observer *observer;
Ted Kremenek848ec832011-02-11 23:24:26 +0000213 const CFGBlock *currentBlock;
Pavel Labath6a556a42013-08-23 07:19:22 +0000214
215 void markLogicalExprLeaves(const Expr *E);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000216public:
Ted Kremenek88299892011-07-28 23:07:59 +0000217 TransferFunctions(LiveVariablesImpl &im,
218 LiveVariables::LivenessValues &Val,
219 LiveVariables::Observer *Observer,
220 const CFGBlock *CurrentBlock)
221 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000222
Ted Kremenek88299892011-07-28 23:07:59 +0000223 void VisitBinaryOperator(BinaryOperator *BO);
224 void VisitBlockExpr(BlockExpr *BE);
225 void VisitDeclRefExpr(DeclRefExpr *DR);
226 void VisitDeclStmt(DeclStmt *DS);
227 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
228 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
229 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump1eb44332009-09-09 15:08:12 +0000230 void Visit(Stmt *S);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000231};
Ted Kremenek11e72182007-10-01 20:33:52 +0000232}
Ted Kremenek88299892011-07-28 23:07:59 +0000233
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000234static const VariableArrayType *FindVA(QualType Ty) {
235 const Type *ty = Ty.getTypePtr();
236 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
237 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
238 if (VAT->getSizeExpr())
239 return VAT;
240
241 ty = VT->getElementType().getTypePtr();
242 }
243
244 return 0;
245}
246
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000247static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000248 while (S) {
249 if (const Expr *Ex = dyn_cast<Expr>(S))
250 S = Ex->IgnoreParens();
John McCallf3fb5c52011-11-09 17:10:36 +0000251 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
252 S = EWC->getSubExpr();
253 continue;
254 }
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000255 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
256 S = OVE->getSourceExpr();
257 continue;
258 }
259 break;
260 }
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000261 return S;
262}
263
264static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
265 llvm::ImmutableSet<const Stmt *>::Factory &F,
266 const Stmt *S) {
267 Set = F.add(Set, LookThroughStmt(S));
268}
269
Ted Kremenek88299892011-07-28 23:07:59 +0000270void TransferFunctions::Visit(Stmt *S) {
271 if (observer)
272 observer->observeStmt(S, currentBlock, val);
Ted Kremenekbfbcefb2009-12-24 02:40:30 +0000273
Ted Kremenek88299892011-07-28 23:07:59 +0000274 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000275
Ted Kremenek88299892011-07-28 23:07:59 +0000276 if (isa<Expr>(S)) {
277 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
278 }
279
280 // Mark all children expressions live.
281
282 switch (S->getStmtClass()) {
283 default:
284 break;
285 case Stmt::StmtExprClass: {
286 // For statement expressions, look through the compound statement.
287 S = cast<StmtExpr>(S)->getSubStmt();
288 break;
289 }
290 case Stmt::CXXMemberCallExprClass: {
291 // Include the implicit "this" pointer as being live.
292 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekc8085032011-10-06 20:53:28 +0000293 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000294 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekc8085032011-10-06 20:53:28 +0000295 }
Ted Kremenek88299892011-07-28 23:07:59 +0000296 break;
297 }
Anna Zaksc7394062012-08-14 00:36:20 +0000298 case Stmt::ObjCMessageExprClass: {
299 // In calls to super, include the implicit "self" pointer as being live.
300 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
301 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
302 val.liveDecls = LV.DSetFact.add(val.liveDecls,
303 LV.analysisContext.getSelfDecl());
304 break;
305 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000306 case Stmt::DeclStmtClass: {
307 const DeclStmt *DS = cast<DeclStmt>(S);
308 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
309 for (const VariableArrayType* VA = FindVA(VD->getType());
310 VA != 0; VA = FindVA(VA->getElementType())) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000311 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000312 }
313 }
314 break;
315 }
John McCall4b9c2d22011-11-06 09:01:30 +0000316 case Stmt::PseudoObjectExprClass: {
317 // A pseudo-object operation only directly consumes its result
318 // expression.
319 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
320 if (!child) return;
321 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
322 child = OV->getSourceExpr();
323 child = child->IgnoreParens();
324 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
325 return;
326 }
327
Ted Kremenek88299892011-07-28 23:07:59 +0000328 // FIXME: These cases eventually shouldn't be needed.
329 case Stmt::ExprWithCleanupsClass: {
330 S = cast<ExprWithCleanups>(S)->getSubExpr();
331 break;
332 }
333 case Stmt::CXXBindTemporaryExprClass: {
334 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
335 break;
336 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000337 case Stmt::UnaryExprOrTypeTraitExprClass: {
338 // No need to unconditionally visit subexpressions.
339 return;
340 }
Ted Kremenek88299892011-07-28 23:07:59 +0000341 }
342
343 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
344 it != ei; ++it) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000345 if (Stmt *child = *it)
346 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000347 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000348}
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Ted Kremenek88299892011-07-28 23:07:59 +0000350void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
351 if (B->isAssignmentOp()) {
352 if (!LV.killAtAssign)
Ted Kremenek06529ae2008-11-14 21:07:14 +0000353 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000354
355 // Assigning to a variable?
356 Expr *LHS = B->getLHS()->IgnoreParens();
357
Ted Kremenek9c378f72011-08-12 23:37:29 +0000358 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremenek88299892011-07-28 23:07:59 +0000359 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
360 // Assignments to references don't kill the ref's address
361 if (VD->getType()->isReferenceType())
362 return;
Ted Kremeneke97d9db2008-11-11 19:40:47 +0000363
Ted Kremenek88299892011-07-28 23:07:59 +0000364 if (!isAlwaysAlive(VD)) {
365 // The variable is now dead.
366 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
367 }
Ted Kremenek8f5aab62008-11-11 17:42:10 +0000368
Ted Kremenek88299892011-07-28 23:07:59 +0000369 if (observer)
370 observer->observerKill(DR);
Ted Kremenek56206312008-02-22 00:34:10 +0000371 }
Pavel Labath6a556a42013-08-23 07:19:22 +0000372 } else if (B->isLogicalOp()) {
373 // Leaf expressions in the logical operator tree are live until we reach the
374 // outermost logical operator. Static analyzer relies on this behaviour.
375 markLogicalExprLeaves(B->getLHS()->IgnoreParens());
376 markLogicalExprLeaves(B->getRHS()->IgnoreParens());
Ted Kremenek27b07c52007-09-06 21:26:58 +0000377 }
378}
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Pavel Labath6a556a42013-08-23 07:19:22 +0000380void TransferFunctions::markLogicalExprLeaves(const Expr *E) {
381 const BinaryOperator *B = dyn_cast<BinaryOperator>(E);
382 if (!B || !B->isLogicalOp()) {
383 val.liveStmts = LV.SSetFact.add(val.liveStmts, E);
384 return;
385 }
386
387 markLogicalExprLeaves(B->getLHS()->IgnoreParens());
388 markLogicalExprLeaves(B->getRHS()->IgnoreParens());
389}
390
Ted Kremenek88299892011-07-28 23:07:59 +0000391void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek15ce1642011-12-22 01:30:46 +0000392 AnalysisDeclContext::referenced_decls_iterator I, E;
393 llvm::tie(I, E) =
394 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
395 for ( ; I != E ; ++I) {
396 const VarDecl *VD = *I;
Ted Kremenek88299892011-07-28 23:07:59 +0000397 if (isAlwaysAlive(VD))
398 continue;
399 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000400 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000401}
402
Ted Kremenek88299892011-07-28 23:07:59 +0000403void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
404 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
405 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
406 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
407}
408
409void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek14f8b4f2008-08-05 20:46:55 +0000410 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();
411 DI != DE; ++DI)
Ted Kremenek9c378f72011-08-12 23:37:29 +0000412 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek88299892011-07-28 23:07:59 +0000413 if (!isAlwaysAlive(VD))
414 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekdcc48102008-02-25 22:28:54 +0000415 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000416}
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek88299892011-07-28 23:07:59 +0000418void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
419 // Kill the iteration variable.
420 DeclRefExpr *DR = 0;
421 const VarDecl *VD = 0;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000422
Ted Kremenek88299892011-07-28 23:07:59 +0000423 Stmt *element = OS->getElement();
424 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
425 VD = cast<VarDecl>(DS->getSingleDecl());
426 }
427 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
428 VD = cast<VarDecl>(DR->getDecl());
429 }
430
431 if (VD) {
432 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
433 if (observer && DR)
434 observer->observerKill(DR);
435 }
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000436}
Ted Kremenek27b07c52007-09-06 21:26:58 +0000437
Ted Kremenek88299892011-07-28 23:07:59 +0000438void TransferFunctions::
439VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
440{
441 // While sizeof(var) doesn't technically extend the liveness of 'var', it
442 // does extent the liveness of metadata if 'var' is a VariableArrayType.
443 // We handle that special case here.
444 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
445 return;
446
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000447 const Expr *subEx = UE->getArgumentExpr();
448 if (subEx->getType()->isVariableArrayType()) {
449 assert(subEx->isLValue());
450 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
451 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000452}
453
Ted Kremenek88299892011-07-28 23:07:59 +0000454void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
455 // Treat ++/-- as a kill.
456 // Note we don't actually have to do anything if we don't have an observer,
457 // since a ++/-- acts as both a kill and a "use".
458 if (!observer)
459 return;
460
461 switch (UO->getOpcode()) {
462 default:
463 return;
464 case UO_PostInc:
465 case UO_PostDec:
466 case UO_PreInc:
467 case UO_PreDec:
468 break;
469 }
470
471 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
472 if (isa<VarDecl>(DR->getDecl())) {
473 // Treat ++/-- as a kill.
474 observer->observerKill(DR);
475 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000476}
477
Ted Kremenek88299892011-07-28 23:07:59 +0000478LiveVariables::LivenessValues
479LiveVariablesImpl::runOnBlock(const CFGBlock *block,
480 LiveVariables::LivenessValues val,
481 LiveVariables::Observer *obs) {
482
483 TransferFunctions TF(*this, val, obs, block);
484
485 // Visit the terminator (if any).
486 if (const Stmt *term = block->getTerminator())
487 TF.Visit(const_cast<Stmt*>(term));
488
489 // Apply the transfer function for all Stmts in the block.
490 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
491 ei = block->rend(); it != ei; ++it) {
492 const CFGElement &elem = *it;
Jordan Rosed7f1d132012-07-26 20:04:08 +0000493
David Blaikieb0780542013-02-23 00:29:34 +0000494 if (Optional<CFGAutomaticObjDtor> Dtor =
495 elem.getAs<CFGAutomaticObjDtor>()) {
496 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Rosed7f1d132012-07-26 20:04:08 +0000497 continue;
498 }
499
David Blaikiefdf6a272013-02-21 20:58:29 +0000500 if (!elem.getAs<CFGStmt>())
Ted Kremenek88299892011-07-28 23:07:59 +0000501 continue;
502
David Blaikiefdf6a272013-02-21 20:58:29 +0000503 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremenek88299892011-07-28 23:07:59 +0000504 TF.Visit(const_cast<Stmt*>(S));
505 stmtsToLiveness[S] = val;
506 }
507 return val;
Ted Kremenek055c2752007-09-06 23:00:42 +0000508}
509
Ted Kremenek88299892011-07-28 23:07:59 +0000510void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
511 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
512 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
513 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek86946742008-01-17 20:48:37 +0000514}
515
Ted Kremenek88299892011-07-28 23:07:59 +0000516LiveVariables::LiveVariables(void *im) : impl(im) {}
517
518LiveVariables::~LiveVariables() {
519 delete (LiveVariablesImpl*) impl;
Ted Kremenek2a9da9c2008-01-18 00:40:21 +0000520}
521
Ted Kremenek88299892011-07-28 23:07:59 +0000522LiveVariables *
Ted Kremenek1d26f482011-10-24 01:32:45 +0000523LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremenek88299892011-07-28 23:07:59 +0000524 bool killAtAssign) {
Ted Kremeneke4e63342007-09-06 00:17:54 +0000525
Ted Kremenek88299892011-07-28 23:07:59 +0000526 // No CFG? Bail out.
527 CFG *cfg = AC.getCFG();
528 if (!cfg)
529 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Ted Kremenekd4aeb802012-07-02 20:21:52 +0000531 // The analysis currently has scalability issues for very large CFGs.
532 // Bail out if it looks too large.
533 if (cfg->getNumBlockIDs() > 300000)
534 return 0;
535
Ted Kremenek88299892011-07-28 23:07:59 +0000536 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
537
538 // Construct the dataflow worklist. Enqueue the exit block as the
539 // start of the analysis.
Ted Kremenekedb18632011-10-22 02:14:23 +0000540 DataflowWorklist worklist(*cfg, AC);
Ted Kremenek88299892011-07-28 23:07:59 +0000541 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
542
543 // FIXME: we should enqueue using post order.
544 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
545 const CFGBlock *block = *it;
546 worklist.enqueueBlock(block);
547
548 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
549 // We need to do this because we lack context in the reverse analysis
550 // to determine if a DeclRefExpr appears in such a context, and thus
551 // doesn't constitute a "use".
552 if (killAtAssign)
553 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
554 bi != be; ++bi) {
David Blaikieb0780542013-02-23 00:29:34 +0000555 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
556 if (const BinaryOperator *BO =
557 dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremenek88299892011-07-28 23:07:59 +0000558 if (BO->getOpcode() == BO_Assign) {
559 if (const DeclRefExpr *DR =
560 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
561 LV->inAssignment[DR] = 1;
562 }
563 }
564 }
565 }
566 }
567 }
568
Ted Kremenek87aa1252011-09-16 23:01:39 +0000569 worklist.sortWorklist();
570
571 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek88299892011-07-28 23:07:59 +0000572 // Determine if the block's end value has changed. If not, we
573 // have nothing left to do for this block.
574 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
575
576 // Merge the values of all successor blocks.
577 LivenessValues val;
578 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
579 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000580 if (const CFGBlock *succ = *it) {
Ted Kremenek88299892011-07-28 23:07:59 +0000581 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek87aa1252011-09-16 23:01:39 +0000582 }
Ted Kremenek88299892011-07-28 23:07:59 +0000583 }
584
585 if (!everAnalyzedBlock[block->getBlockID()])
586 everAnalyzedBlock[block->getBlockID()] = true;
587 else if (prevVal.equals(val))
588 continue;
589
590 prevVal = val;
591
592 // Update the dataflow value for the start of this block.
593 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
594
595 // Enqueue the value to the predecessors.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000596 worklist.enqueuePredecessors(block);
Ted Kremenek88299892011-07-28 23:07:59 +0000597 }
598
599 return new LiveVariables(LV);
600}
601
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000602static bool compare_entries(const CFGBlock *A, const CFGBlock *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000603 return A->getBlockID() < B->getBlockID();
604}
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000605
606static bool compare_vd_entries(const Decl *A, const Decl *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000607 SourceLocation ALoc = A->getLocStart();
608 SourceLocation BLoc = B->getLocStart();
609 return ALoc.getRawEncoding() < BLoc.getRawEncoding();
610}
611
612void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
613 getImpl(impl).dumpBlockLiveness(M);
614}
615
616void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
617 std::vector<const CFGBlock *> vec;
618 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
619 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
620 it != ei; ++it) {
621 vec.push_back(it->first);
622 }
623 std::sort(vec.begin(), vec.end(), compare_entries);
624
625 std::vector<const VarDecl*> declVec;
626
627 for (std::vector<const CFGBlock *>::iterator
628 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
629 llvm::errs() << "\n[ B" << (*it)->getBlockID()
630 << " (live variables at block exit) ]\n";
631
632 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
633 declVec.clear();
634
635 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
636 vals.liveDecls.begin(),
637 se = vals.liveDecls.end(); si != se; ++si) {
638 declVec.push_back(*si);
639 }
640
641 std::sort(declVec.begin(), declVec.end(), compare_vd_entries);
642
643 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
644 de = declVec.end(); di != de; ++di) {
645 llvm::errs() << " " << (*di)->getDeclName().getAsString()
646 << " <";
647 (*di)->getLocation().dump(M);
Daniel Dunbarc0d56722009-10-17 18:12:37 +0000648 llvm::errs() << ">\n";
Ted Kremeneke4e63342007-09-06 00:17:54 +0000649 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000650 }
Ted Kremenek88299892011-07-28 23:07:59 +0000651 llvm::errs() << "\n";
Ted Kremenekc0576ca2007-09-10 17:36:42 +0000652}
Ted Kremenek88299892011-07-28 23:07:59 +0000653
Ted Kremeneka5937bb2011-10-07 22:21:02 +0000654const void *LiveVariables::getTag() { static int x; return &x; }
655const void *RelaxedLiveVariables::getTag() { static int x; return &x; }