blob: b26d4fb3703f32b841affffb1e3281f8e1eedbfd [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);
Ted Kremenek87aa1252011-09-16 23:01:39 +000040 void enqueuePredecessors(const CFGBlock *block);
41
42 const CFGBlock *dequeue();
43
44 void sortWorklist();
45};
46
47}
48
49void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
50 if (block && !enqueuedBlocks[block->getBlockID()]) {
51 enqueuedBlocks[block->getBlockID()] = true;
52 worklist.push_back(block);
53 }
54}
Ted Kremenek87aa1252011-09-16 23:01:39 +000055
56void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
57 const unsigned OldWorklistSize = worklist.size();
58 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
59 E = block->pred_end(); I != E; ++I) {
60 enqueueBlock(*I);
61 }
62
63 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
64 return;
65
66 sortWorklist();
67}
68
69void DataflowWorklist::sortWorklist() {
Ted Kremenekedb18632011-10-22 02:14:23 +000070 std::sort(worklist.begin(), worklist.end(), POV->getComparator());
Ted Kremenek87aa1252011-09-16 23:01:39 +000071}
72
Ted Kremenek87aa1252011-09-16 23:01:39 +000073const CFGBlock *DataflowWorklist::dequeue() {
74 if (worklist.empty())
75 return 0;
Robert Wilhelm344472e2013-08-23 16:11:15 +000076 const CFGBlock *b = worklist.pop_back_val();
Ted Kremenek87aa1252011-09-16 23:01:39 +000077 enqueuedBlocks[b->getBlockID()] = false;
78 return b;
79}
80
81namespace {
82class LiveVariablesImpl {
83public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000084 AnalysisDeclContext &analysisContext;
Ted Kremenek87aa1252011-09-16 23:01:39 +000085 std::vector<LiveVariables::LivenessValues> cfgBlockValues;
86 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
87 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
88 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
89 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
90 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
91 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
92 const bool killAtAssign;
93
94 LiveVariables::LivenessValues
95 merge(LiveVariables::LivenessValues valsA,
96 LiveVariables::LivenessValues valsB);
97
98 LiveVariables::LivenessValues runOnBlock(const CFGBlock *block,
99 LiveVariables::LivenessValues val,
100 LiveVariables::Observer *obs = 0);
101
102 void dumpBlockLiveness(const SourceManager& M);
103
Ted Kremenek1d26f482011-10-24 01:32:45 +0000104 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000105 : analysisContext(ac),
106 SSetFact(false), // Do not canonicalize ImmutableSets by default.
107 DSetFact(false), // This is a *major* performance win.
108 killAtAssign(KillAtAssign) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +0000109};
Ted Kremenek88299892011-07-28 23:07:59 +0000110}
Ted Kremenek7deed0c2008-04-15 18:35:30 +0000111
Ted Kremenek9c378f72011-08-12 23:37:29 +0000112static LiveVariablesImpl &getImpl(void *x) {
Ted Kremenek88299892011-07-28 23:07:59 +0000113 return *((LiveVariablesImpl *) x);
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000114}
Ted Kremeneke4e63342007-09-06 00:17:54 +0000115
116//===----------------------------------------------------------------------===//
Ted Kremenek88299892011-07-28 23:07:59 +0000117// Operations and queries on LivenessValues.
118//===----------------------------------------------------------------------===//
119
120bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
121 return liveStmts.contains(S);
122}
123
124bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
125 return liveDecls.contains(D);
126}
127
128namespace {
129 template <typename SET>
Ted Kremenek87aa1252011-09-16 23:01:39 +0000130 SET mergeSets(SET A, SET B) {
131 if (A.isEmpty())
132 return B;
133
Ted Kremenek88299892011-07-28 23:07:59 +0000134 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000135 A = A.add(*it);
Ted Kremenek88299892011-07-28 23:07:59 +0000136 }
137 return A;
138 }
139}
140
David Blaikie99ba9e32011-12-20 02:48:34 +0000141void LiveVariables::Observer::anchor() { }
142
Ted Kremenek88299892011-07-28 23:07:59 +0000143LiveVariables::LivenessValues
144LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
145 LiveVariables::LivenessValues valsB) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000146
147 llvm::ImmutableSetRef<const Stmt *>
148 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
149 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
150
151
152 llvm::ImmutableSetRef<const VarDecl *>
153 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
154 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
155
156
157 SSetRefA = mergeSets(SSetRefA, SSetRefB);
158 DSetRefA = mergeSets(DSetRefA, DSetRefB);
159
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000160 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
161 // comparison afterwards.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000162 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
163 DSetRefA.asImmutableSet());
Ted Kremenek88299892011-07-28 23:07:59 +0000164}
165
166bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
167 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
168}
169
170//===----------------------------------------------------------------------===//
171// Query methods.
172//===----------------------------------------------------------------------===//
173
174static bool isAlwaysAlive(const VarDecl *D) {
175 return D->hasGlobalStorage();
176}
177
178bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
179 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
180}
181
182bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
183 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
184}
185
186bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
187 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
188}
189
190//===----------------------------------------------------------------------===//
191// Dataflow computation.
Mike Stump1eb44332009-09-09 15:08:12 +0000192//===----------------------------------------------------------------------===//
Ted Kremeneke4e63342007-09-06 00:17:54 +0000193
194namespace {
Ted Kremenek88299892011-07-28 23:07:59 +0000195class TransferFunctions : public StmtVisitor<TransferFunctions> {
196 LiveVariablesImpl &LV;
197 LiveVariables::LivenessValues &val;
198 LiveVariables::Observer *observer;
Ted Kremenek848ec832011-02-11 23:24:26 +0000199 const CFGBlock *currentBlock;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000200public:
Ted Kremenek88299892011-07-28 23:07:59 +0000201 TransferFunctions(LiveVariablesImpl &im,
202 LiveVariables::LivenessValues &Val,
203 LiveVariables::Observer *Observer,
204 const CFGBlock *CurrentBlock)
205 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000206
Ted Kremenek88299892011-07-28 23:07:59 +0000207 void VisitBinaryOperator(BinaryOperator *BO);
208 void VisitBlockExpr(BlockExpr *BE);
209 void VisitDeclRefExpr(DeclRefExpr *DR);
210 void VisitDeclStmt(DeclStmt *DS);
211 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
212 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
213 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump1eb44332009-09-09 15:08:12 +0000214 void Visit(Stmt *S);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000215};
Ted Kremenek11e72182007-10-01 20:33:52 +0000216}
Ted Kremenek88299892011-07-28 23:07:59 +0000217
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000218static const VariableArrayType *FindVA(QualType Ty) {
219 const Type *ty = Ty.getTypePtr();
220 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
221 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
222 if (VAT->getSizeExpr())
223 return VAT;
224
225 ty = VT->getElementType().getTypePtr();
226 }
227
228 return 0;
229}
230
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000231static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000232 while (S) {
233 if (const Expr *Ex = dyn_cast<Expr>(S))
234 S = Ex->IgnoreParens();
John McCallf3fb5c52011-11-09 17:10:36 +0000235 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
236 S = EWC->getSubExpr();
237 continue;
238 }
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000239 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
240 S = OVE->getSourceExpr();
241 continue;
242 }
243 break;
244 }
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000245 return S;
246}
247
248static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
249 llvm::ImmutableSet<const Stmt *>::Factory &F,
250 const Stmt *S) {
251 Set = F.add(Set, LookThroughStmt(S));
252}
253
Ted Kremenek88299892011-07-28 23:07:59 +0000254void TransferFunctions::Visit(Stmt *S) {
255 if (observer)
256 observer->observeStmt(S, currentBlock, val);
Ted Kremenekbfbcefb2009-12-24 02:40:30 +0000257
Ted Kremenek88299892011-07-28 23:07:59 +0000258 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000259
Ted Kremenek88299892011-07-28 23:07:59 +0000260 if (isa<Expr>(S)) {
261 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
262 }
263
264 // Mark all children expressions live.
265
266 switch (S->getStmtClass()) {
267 default:
268 break;
269 case Stmt::StmtExprClass: {
270 // For statement expressions, look through the compound statement.
271 S = cast<StmtExpr>(S)->getSubStmt();
272 break;
273 }
274 case Stmt::CXXMemberCallExprClass: {
275 // Include the implicit "this" pointer as being live.
276 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekc8085032011-10-06 20:53:28 +0000277 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000278 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekc8085032011-10-06 20:53:28 +0000279 }
Ted Kremenek88299892011-07-28 23:07:59 +0000280 break;
281 }
Anna Zaksc7394062012-08-14 00:36:20 +0000282 case Stmt::ObjCMessageExprClass: {
283 // In calls to super, include the implicit "self" pointer as being live.
284 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
285 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
286 val.liveDecls = LV.DSetFact.add(val.liveDecls,
287 LV.analysisContext.getSelfDecl());
288 break;
289 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000290 case Stmt::DeclStmtClass: {
291 const DeclStmt *DS = cast<DeclStmt>(S);
292 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
293 for (const VariableArrayType* VA = FindVA(VD->getType());
294 VA != 0; VA = FindVA(VA->getElementType())) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000295 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000296 }
297 }
298 break;
299 }
John McCall4b9c2d22011-11-06 09:01:30 +0000300 case Stmt::PseudoObjectExprClass: {
301 // A pseudo-object operation only directly consumes its result
302 // expression.
303 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
304 if (!child) return;
305 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
306 child = OV->getSourceExpr();
307 child = child->IgnoreParens();
308 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
309 return;
310 }
311
Ted Kremenek88299892011-07-28 23:07:59 +0000312 // FIXME: These cases eventually shouldn't be needed.
313 case Stmt::ExprWithCleanupsClass: {
314 S = cast<ExprWithCleanups>(S)->getSubExpr();
315 break;
316 }
317 case Stmt::CXXBindTemporaryExprClass: {
318 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
319 break;
320 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000321 case Stmt::UnaryExprOrTypeTraitExprClass: {
322 // No need to unconditionally visit subexpressions.
323 return;
324 }
Ted Kremenek88299892011-07-28 23:07:59 +0000325 }
326
327 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
328 it != ei; ++it) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000329 if (Stmt *child = *it)
330 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000331 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000332}
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Ted Kremenek88299892011-07-28 23:07:59 +0000334void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
335 if (B->isAssignmentOp()) {
336 if (!LV.killAtAssign)
Ted Kremenek06529ae2008-11-14 21:07:14 +0000337 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000338
339 // Assigning to a variable?
340 Expr *LHS = B->getLHS()->IgnoreParens();
341
Ted Kremenek9c378f72011-08-12 23:37:29 +0000342 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremenek88299892011-07-28 23:07:59 +0000343 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
344 // Assignments to references don't kill the ref's address
345 if (VD->getType()->isReferenceType())
346 return;
Ted Kremeneke97d9db2008-11-11 19:40:47 +0000347
Ted Kremenek88299892011-07-28 23:07:59 +0000348 if (!isAlwaysAlive(VD)) {
349 // The variable is now dead.
350 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
351 }
Ted Kremenek8f5aab62008-11-11 17:42:10 +0000352
Ted Kremenek88299892011-07-28 23:07:59 +0000353 if (observer)
354 observer->observerKill(DR);
Ted Kremenek56206312008-02-22 00:34:10 +0000355 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000356 }
357}
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Ted Kremenek88299892011-07-28 23:07:59 +0000359void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek15ce1642011-12-22 01:30:46 +0000360 AnalysisDeclContext::referenced_decls_iterator I, E;
Stephen Hines651f13c2014-04-23 16:59:28 -0700361 std::tie(I, E) =
Ted Kremenek15ce1642011-12-22 01:30:46 +0000362 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
363 for ( ; I != E ; ++I) {
364 const VarDecl *VD = *I;
Ted Kremenek88299892011-07-28 23:07:59 +0000365 if (isAlwaysAlive(VD))
366 continue;
367 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000368 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000369}
370
Ted Kremenek88299892011-07-28 23:07:59 +0000371void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
372 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
373 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
374 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
375}
376
377void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700378 for (const auto *DI : DS->decls())
379 if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremenek88299892011-07-28 23:07:59 +0000380 if (!isAlwaysAlive(VD))
381 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekdcc48102008-02-25 22:28:54 +0000382 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000383}
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Ted Kremenek88299892011-07-28 23:07:59 +0000385void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
386 // Kill the iteration variable.
387 DeclRefExpr *DR = 0;
388 const VarDecl *VD = 0;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000389
Ted Kremenek88299892011-07-28 23:07:59 +0000390 Stmt *element = OS->getElement();
391 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
392 VD = cast<VarDecl>(DS->getSingleDecl());
393 }
394 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
395 VD = cast<VarDecl>(DR->getDecl());
396 }
397
398 if (VD) {
399 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
400 if (observer && DR)
401 observer->observerKill(DR);
402 }
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000403}
Ted Kremenek27b07c52007-09-06 21:26:58 +0000404
Ted Kremenek88299892011-07-28 23:07:59 +0000405void TransferFunctions::
406VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
407{
408 // While sizeof(var) doesn't technically extend the liveness of 'var', it
409 // does extent the liveness of metadata if 'var' is a VariableArrayType.
410 // We handle that special case here.
411 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
412 return;
413
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000414 const Expr *subEx = UE->getArgumentExpr();
415 if (subEx->getType()->isVariableArrayType()) {
416 assert(subEx->isLValue());
417 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
418 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000419}
420
Ted Kremenek88299892011-07-28 23:07:59 +0000421void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
422 // Treat ++/-- as a kill.
423 // Note we don't actually have to do anything if we don't have an observer,
424 // since a ++/-- acts as both a kill and a "use".
425 if (!observer)
426 return;
427
428 switch (UO->getOpcode()) {
429 default:
430 return;
431 case UO_PostInc:
432 case UO_PostDec:
433 case UO_PreInc:
434 case UO_PreDec:
435 break;
436 }
437
438 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
439 if (isa<VarDecl>(DR->getDecl())) {
440 // Treat ++/-- as a kill.
441 observer->observerKill(DR);
442 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000443}
444
Ted Kremenek88299892011-07-28 23:07:59 +0000445LiveVariables::LivenessValues
446LiveVariablesImpl::runOnBlock(const CFGBlock *block,
447 LiveVariables::LivenessValues val,
448 LiveVariables::Observer *obs) {
449
450 TransferFunctions TF(*this, val, obs, block);
451
452 // Visit the terminator (if any).
453 if (const Stmt *term = block->getTerminator())
454 TF.Visit(const_cast<Stmt*>(term));
455
456 // Apply the transfer function for all Stmts in the block.
457 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
458 ei = block->rend(); it != ei; ++it) {
459 const CFGElement &elem = *it;
Jordan Rosed7f1d132012-07-26 20:04:08 +0000460
David Blaikieb0780542013-02-23 00:29:34 +0000461 if (Optional<CFGAutomaticObjDtor> Dtor =
462 elem.getAs<CFGAutomaticObjDtor>()) {
463 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Rosed7f1d132012-07-26 20:04:08 +0000464 continue;
465 }
466
David Blaikiefdf6a272013-02-21 20:58:29 +0000467 if (!elem.getAs<CFGStmt>())
Ted Kremenek88299892011-07-28 23:07:59 +0000468 continue;
469
David Blaikiefdf6a272013-02-21 20:58:29 +0000470 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremenek88299892011-07-28 23:07:59 +0000471 TF.Visit(const_cast<Stmt*>(S));
472 stmtsToLiveness[S] = val;
473 }
474 return val;
Ted Kremenek055c2752007-09-06 23:00:42 +0000475}
476
Ted Kremenek88299892011-07-28 23:07:59 +0000477void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
478 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
479 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
480 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek86946742008-01-17 20:48:37 +0000481}
482
Ted Kremenek88299892011-07-28 23:07:59 +0000483LiveVariables::LiveVariables(void *im) : impl(im) {}
484
485LiveVariables::~LiveVariables() {
486 delete (LiveVariablesImpl*) impl;
Ted Kremenek2a9da9c2008-01-18 00:40:21 +0000487}
488
Ted Kremenek88299892011-07-28 23:07:59 +0000489LiveVariables *
Ted Kremenek1d26f482011-10-24 01:32:45 +0000490LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremenek88299892011-07-28 23:07:59 +0000491 bool killAtAssign) {
Ted Kremeneke4e63342007-09-06 00:17:54 +0000492
Ted Kremenek88299892011-07-28 23:07:59 +0000493 // No CFG? Bail out.
494 CFG *cfg = AC.getCFG();
495 if (!cfg)
496 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Ted Kremenekd4aeb802012-07-02 20:21:52 +0000498 // The analysis currently has scalability issues for very large CFGs.
499 // Bail out if it looks too large.
500 if (cfg->getNumBlockIDs() > 300000)
501 return 0;
502
Ted Kremenek88299892011-07-28 23:07:59 +0000503 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
504
505 // Construct the dataflow worklist. Enqueue the exit block as the
506 // start of the analysis.
Ted Kremenekedb18632011-10-22 02:14:23 +0000507 DataflowWorklist worklist(*cfg, AC);
Ted Kremenek88299892011-07-28 23:07:59 +0000508 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
509
510 // FIXME: we should enqueue using post order.
511 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
512 const CFGBlock *block = *it;
513 worklist.enqueueBlock(block);
514
515 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
516 // We need to do this because we lack context in the reverse analysis
517 // to determine if a DeclRefExpr appears in such a context, and thus
518 // doesn't constitute a "use".
519 if (killAtAssign)
520 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
521 bi != be; ++bi) {
David Blaikieb0780542013-02-23 00:29:34 +0000522 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
523 if (const BinaryOperator *BO =
524 dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremenek88299892011-07-28 23:07:59 +0000525 if (BO->getOpcode() == BO_Assign) {
526 if (const DeclRefExpr *DR =
527 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
528 LV->inAssignment[DR] = 1;
529 }
530 }
531 }
532 }
533 }
534 }
535
Ted Kremenek87aa1252011-09-16 23:01:39 +0000536 worklist.sortWorklist();
537
538 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek88299892011-07-28 23:07:59 +0000539 // Determine if the block's end value has changed. If not, we
540 // have nothing left to do for this block.
541 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
542
543 // Merge the values of all successor blocks.
544 LivenessValues val;
545 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
546 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000547 if (const CFGBlock *succ = *it) {
Ted Kremenek88299892011-07-28 23:07:59 +0000548 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek87aa1252011-09-16 23:01:39 +0000549 }
Ted Kremenek88299892011-07-28 23:07:59 +0000550 }
551
552 if (!everAnalyzedBlock[block->getBlockID()])
553 everAnalyzedBlock[block->getBlockID()] = true;
554 else if (prevVal.equals(val))
555 continue;
556
557 prevVal = val;
558
559 // Update the dataflow value for the start of this block.
560 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
561
562 // Enqueue the value to the predecessors.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000563 worklist.enqueuePredecessors(block);
Ted Kremenek88299892011-07-28 23:07:59 +0000564 }
565
566 return new LiveVariables(LV);
567}
568
Ted Kremenek88299892011-07-28 23:07:59 +0000569void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
570 getImpl(impl).dumpBlockLiveness(M);
571}
572
573void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
574 std::vector<const CFGBlock *> vec;
575 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
576 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
577 it != ei; ++it) {
578 vec.push_back(it->first);
579 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700580 std::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
581 return A->getBlockID() < B->getBlockID();
582 });
Ted Kremenek88299892011-07-28 23:07:59 +0000583
584 std::vector<const VarDecl*> declVec;
585
586 for (std::vector<const CFGBlock *>::iterator
587 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
588 llvm::errs() << "\n[ B" << (*it)->getBlockID()
589 << " (live variables at block exit) ]\n";
590
591 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
592 declVec.clear();
593
594 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
595 vals.liveDecls.begin(),
596 se = vals.liveDecls.end(); si != se; ++si) {
597 declVec.push_back(*si);
598 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700599
600 std::sort(declVec.begin(), declVec.end(), [](const Decl *A, const Decl *B) {
601 return A->getLocStart() < B->getLocStart();
602 });
603
Ted Kremenek88299892011-07-28 23:07:59 +0000604 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
605 de = declVec.end(); di != de; ++di) {
606 llvm::errs() << " " << (*di)->getDeclName().getAsString()
607 << " <";
608 (*di)->getLocation().dump(M);
Daniel Dunbarc0d56722009-10-17 18:12:37 +0000609 llvm::errs() << ">\n";
Ted Kremeneke4e63342007-09-06 00:17:54 +0000610 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000611 }
Ted Kremenek88299892011-07-28 23:07:59 +0000612 llvm::errs() << "\n";
Ted Kremenekc0576ca2007-09-10 17:36:42 +0000613}
Ted Kremenek88299892011-07-28 23:07:59 +0000614
Ted Kremeneka5937bb2011-10-07 22:21:02 +0000615const void *LiveVariables::getTag() { static int x; return &x; }
616const void *RelaxedLiveVariables::getTag() { static int x; return &x; }