blob: 38f8199bffce1045181204fc48cceb6b1cc2abdf [file] [log] [blame]
Ted Kremenekcf6e41b2007-12-21 21:42:19 +00001#include "clang/Analysis/Analyses/LiveVariables.h"
Ted Kremenekedb18632011-10-22 02:14:23 +00002#include "clang/Analysis/Analyses/PostOrderCFGView.h"
3
Ted Kremenek88299892011-07-28 23:07:59 +00004#include "clang/AST/Stmt.h"
Ted Kremeneke41611a2009-07-16 18:13:04 +00005#include "clang/Analysis/CFG.h"
Ted Kremenek1309f9a2010-01-25 04:41:41 +00006#include "clang/Analysis/AnalysisContext.h"
Ted Kremenek88299892011-07-28 23:07:59 +00007#include "clang/AST/StmtVisitor.h"
8
Ted Kremenek87aa1252011-09-16 23:01:39 +00009#include "llvm/ADT/PostOrderIterator.h"
10#include "llvm/ADT/DenseMap.h"
11
Ted Kremenek88299892011-07-28 23:07:59 +000012#include <deque>
13#include <algorithm>
14#include <vector>
Ted Kremeneke4e63342007-09-06 00:17:54 +000015
16using namespace clang;
17
Ted Kremeneke4e63342007-09-06 00:17:54 +000018namespace {
Mike Stump1eb44332009-09-09 15:08:12 +000019
Ted Kremenek87aa1252011-09-16 23:01:39 +000020class DataflowWorklist {
21 SmallVector<const CFGBlock *, 20> worklist;
22 llvm::BitVector enqueuedBlocks;
Ted Kremenekedb18632011-10-22 02:14:23 +000023 PostOrderCFGView *POV;
Ted Kremenek87aa1252011-09-16 23:01:39 +000024public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000025 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
Ted Kremenek87aa1252011-09-16 23:01:39 +000026 : enqueuedBlocks(cfg.getNumBlockIDs()),
Ted Kremenekedb18632011-10-22 02:14:23 +000027 POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +000028
29 void enqueueBlock(const CFGBlock *block);
30 void enqueueSuccessors(const CFGBlock *block);
31 void enqueuePredecessors(const CFGBlock *block);
32
33 const CFGBlock *dequeue();
34
35 void sortWorklist();
36};
37
38}
39
40void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
41 if (block && !enqueuedBlocks[block->getBlockID()]) {
42 enqueuedBlocks[block->getBlockID()] = true;
43 worklist.push_back(block);
44 }
45}
46
47void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
48 const unsigned OldWorklistSize = worklist.size();
49 for (CFGBlock::const_succ_iterator I = block->succ_begin(),
50 E = block->succ_end(); I != E; ++I) {
51 enqueueBlock(*I);
52 }
53
54 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
55 return;
56
57 sortWorklist();
58}
59
60void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
61 const unsigned OldWorklistSize = worklist.size();
62 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
63 E = block->pred_end(); I != E; ++I) {
64 enqueueBlock(*I);
65 }
66
67 if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
68 return;
69
70 sortWorklist();
71}
72
73void DataflowWorklist::sortWorklist() {
Ted Kremenekedb18632011-10-22 02:14:23 +000074 std::sort(worklist.begin(), worklist.end(), POV->getComparator());
Ted Kremenek87aa1252011-09-16 23:01:39 +000075}
76
Ted Kremenek87aa1252011-09-16 23:01:39 +000077const CFGBlock *DataflowWorklist::dequeue() {
78 if (worklist.empty())
79 return 0;
80 const CFGBlock *b = worklist.back();
81 worklist.pop_back();
82 enqueuedBlocks[b->getBlockID()] = false;
83 return b;
84}
85
86namespace {
87class LiveVariablesImpl {
88public:
Ted Kremenek1d26f482011-10-24 01:32:45 +000089 AnalysisDeclContext &analysisContext;
Ted Kremenek87aa1252011-09-16 23:01:39 +000090 std::vector<LiveVariables::LivenessValues> cfgBlockValues;
91 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
92 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
93 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
94 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
95 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
96 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
97 const bool killAtAssign;
98
99 LiveVariables::LivenessValues
100 merge(LiveVariables::LivenessValues valsA,
101 LiveVariables::LivenessValues valsB);
102
103 LiveVariables::LivenessValues runOnBlock(const CFGBlock *block,
104 LiveVariables::LivenessValues val,
105 LiveVariables::Observer *obs = 0);
106
107 void dumpBlockLiveness(const SourceManager& M);
108
Ted Kremenek1d26f482011-10-24 01:32:45 +0000109 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000110 : analysisContext(ac),
111 SSetFact(false), // Do not canonicalize ImmutableSets by default.
112 DSetFact(false), // This is a *major* performance win.
113 killAtAssign(KillAtAssign) {}
Ted Kremenek87aa1252011-09-16 23:01:39 +0000114};
Ted Kremenek88299892011-07-28 23:07:59 +0000115}
Ted Kremenek7deed0c2008-04-15 18:35:30 +0000116
Ted Kremenek9c378f72011-08-12 23:37:29 +0000117static LiveVariablesImpl &getImpl(void *x) {
Ted Kremenek88299892011-07-28 23:07:59 +0000118 return *((LiveVariablesImpl *) x);
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000119}
Ted Kremeneke4e63342007-09-06 00:17:54 +0000120
121//===----------------------------------------------------------------------===//
Ted Kremenek88299892011-07-28 23:07:59 +0000122// Operations and queries on LivenessValues.
123//===----------------------------------------------------------------------===//
124
125bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
126 return liveStmts.contains(S);
127}
128
129bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
130 return liveDecls.contains(D);
131}
132
133namespace {
134 template <typename SET>
Ted Kremenek87aa1252011-09-16 23:01:39 +0000135 SET mergeSets(SET A, SET B) {
136 if (A.isEmpty())
137 return B;
138
Ted Kremenek88299892011-07-28 23:07:59 +0000139 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000140 A = A.add(*it);
Ted Kremenek88299892011-07-28 23:07:59 +0000141 }
142 return A;
143 }
144}
145
David Blaikie99ba9e32011-12-20 02:48:34 +0000146void LiveVariables::Observer::anchor() { }
147
Ted Kremenek88299892011-07-28 23:07:59 +0000148LiveVariables::LivenessValues
149LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
150 LiveVariables::LivenessValues valsB) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000151
152 llvm::ImmutableSetRef<const Stmt *>
153 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
154 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
155
156
157 llvm::ImmutableSetRef<const VarDecl *>
158 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
159 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
160
161
162 SSetRefA = mergeSets(SSetRefA, SSetRefB);
163 DSetRefA = mergeSets(DSetRefA, DSetRefB);
164
Ted Kremenek3c2b5f72011-10-02 01:45:37 +0000165 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
166 // comparison afterwards.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000167 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
168 DSetRefA.asImmutableSet());
Ted Kremenek88299892011-07-28 23:07:59 +0000169}
170
171bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
172 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
173}
174
175//===----------------------------------------------------------------------===//
176// Query methods.
177//===----------------------------------------------------------------------===//
178
179static bool isAlwaysAlive(const VarDecl *D) {
180 return D->hasGlobalStorage();
181}
182
183bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
184 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
185}
186
187bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
188 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
189}
190
191bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
192 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
193}
194
195//===----------------------------------------------------------------------===//
196// Dataflow computation.
Mike Stump1eb44332009-09-09 15:08:12 +0000197//===----------------------------------------------------------------------===//
Ted Kremeneke4e63342007-09-06 00:17:54 +0000198
199namespace {
Ted Kremenek88299892011-07-28 23:07:59 +0000200class TransferFunctions : public StmtVisitor<TransferFunctions> {
201 LiveVariablesImpl &LV;
202 LiveVariables::LivenessValues &val;
203 LiveVariables::Observer *observer;
Ted Kremenek848ec832011-02-11 23:24:26 +0000204 const CFGBlock *currentBlock;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000205public:
Ted Kremenek88299892011-07-28 23:07:59 +0000206 TransferFunctions(LiveVariablesImpl &im,
207 LiveVariables::LivenessValues &Val,
208 LiveVariables::Observer *Observer,
209 const CFGBlock *CurrentBlock)
210 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000211
Ted Kremenek88299892011-07-28 23:07:59 +0000212 void VisitBinaryOperator(BinaryOperator *BO);
213 void VisitBlockExpr(BlockExpr *BE);
214 void VisitDeclRefExpr(DeclRefExpr *DR);
215 void VisitDeclStmt(DeclStmt *DS);
216 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
217 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
218 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump1eb44332009-09-09 15:08:12 +0000219 void Visit(Stmt *S);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000220};
Ted Kremenek11e72182007-10-01 20:33:52 +0000221}
Ted Kremenek88299892011-07-28 23:07:59 +0000222
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000223static const VariableArrayType *FindVA(QualType Ty) {
224 const Type *ty = Ty.getTypePtr();
225 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
226 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
227 if (VAT->getSizeExpr())
228 return VAT;
229
230 ty = VT->getElementType().getTypePtr();
231 }
232
233 return 0;
234}
235
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000236static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000237 while (S) {
238 if (const Expr *Ex = dyn_cast<Expr>(S))
239 S = Ex->IgnoreParens();
John McCallf3fb5c52011-11-09 17:10:36 +0000240 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
241 S = EWC->getSubExpr();
242 continue;
243 }
Ted Kremenek6bbecd52011-11-05 07:34:28 +0000244 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
245 S = OVE->getSourceExpr();
246 continue;
247 }
248 break;
249 }
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000250 return S;
251}
252
253static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
254 llvm::ImmutableSet<const Stmt *>::Factory &F,
255 const Stmt *S) {
256 Set = F.add(Set, LookThroughStmt(S));
257}
258
Ted Kremenek88299892011-07-28 23:07:59 +0000259void TransferFunctions::Visit(Stmt *S) {
260 if (observer)
261 observer->observeStmt(S, currentBlock, val);
Ted Kremenekbfbcefb2009-12-24 02:40:30 +0000262
Ted Kremenek88299892011-07-28 23:07:59 +0000263 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000264
Ted Kremenek88299892011-07-28 23:07:59 +0000265 if (isa<Expr>(S)) {
266 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
267 }
268
269 // Mark all children expressions live.
270
271 switch (S->getStmtClass()) {
272 default:
273 break;
274 case Stmt::StmtExprClass: {
275 // For statement expressions, look through the compound statement.
276 S = cast<StmtExpr>(S)->getSubStmt();
277 break;
278 }
279 case Stmt::CXXMemberCallExprClass: {
280 // Include the implicit "this" pointer as being live.
281 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekc8085032011-10-06 20:53:28 +0000282 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000283 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekc8085032011-10-06 20:53:28 +0000284 }
Ted Kremenek88299892011-07-28 23:07:59 +0000285 break;
286 }
Anna Zaksc7394062012-08-14 00:36:20 +0000287 case Stmt::ObjCMessageExprClass: {
288 // In calls to super, include the implicit "self" pointer as being live.
289 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
290 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
291 val.liveDecls = LV.DSetFact.add(val.liveDecls,
292 LV.analysisContext.getSelfDecl());
293 break;
294 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000295 case Stmt::DeclStmtClass: {
296 const DeclStmt *DS = cast<DeclStmt>(S);
297 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
298 for (const VariableArrayType* VA = FindVA(VD->getType());
299 VA != 0; VA = FindVA(VA->getElementType())) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000300 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000301 }
302 }
303 break;
304 }
John McCall4b9c2d22011-11-06 09:01:30 +0000305 case Stmt::PseudoObjectExprClass: {
306 // A pseudo-object operation only directly consumes its result
307 // expression.
308 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
309 if (!child) return;
310 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
311 child = OV->getSourceExpr();
312 child = child->IgnoreParens();
313 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
314 return;
315 }
316
Ted Kremenek88299892011-07-28 23:07:59 +0000317 // FIXME: These cases eventually shouldn't be needed.
318 case Stmt::ExprWithCleanupsClass: {
319 S = cast<ExprWithCleanups>(S)->getSubExpr();
320 break;
321 }
322 case Stmt::CXXBindTemporaryExprClass: {
323 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
324 break;
325 }
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000326 case Stmt::UnaryExprOrTypeTraitExprClass: {
327 // No need to unconditionally visit subexpressions.
328 return;
329 }
Ted Kremenek88299892011-07-28 23:07:59 +0000330 }
331
332 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
333 it != ei; ++it) {
Ted Kremenekddaec0d2011-11-05 00:26:53 +0000334 if (Stmt *child = *it)
335 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenekb1a7b652009-11-26 02:31:33 +0000336 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000337}
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek88299892011-07-28 23:07:59 +0000339void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
340 if (B->isAssignmentOp()) {
341 if (!LV.killAtAssign)
Ted Kremenek06529ae2008-11-14 21:07:14 +0000342 return;
Ted Kremenek88299892011-07-28 23:07:59 +0000343
344 // Assigning to a variable?
345 Expr *LHS = B->getLHS()->IgnoreParens();
346
Ted Kremenek9c378f72011-08-12 23:37:29 +0000347 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremenek88299892011-07-28 23:07:59 +0000348 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
349 // Assignments to references don't kill the ref's address
350 if (VD->getType()->isReferenceType())
351 return;
Ted Kremeneke97d9db2008-11-11 19:40:47 +0000352
Ted Kremenek88299892011-07-28 23:07:59 +0000353 if (!isAlwaysAlive(VD)) {
354 // The variable is now dead.
355 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
356 }
Ted Kremenek8f5aab62008-11-11 17:42:10 +0000357
Ted Kremenek88299892011-07-28 23:07:59 +0000358 if (observer)
359 observer->observerKill(DR);
Ted Kremenek56206312008-02-22 00:34:10 +0000360 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000361 }
362}
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Ted Kremenek88299892011-07-28 23:07:59 +0000364void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek15ce1642011-12-22 01:30:46 +0000365 AnalysisDeclContext::referenced_decls_iterator I, E;
366 llvm::tie(I, E) =
367 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
368 for ( ; I != E ; ++I) {
369 const VarDecl *VD = *I;
Ted Kremenek88299892011-07-28 23:07:59 +0000370 if (isAlwaysAlive(VD))
371 continue;
372 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremeneke4e63342007-09-06 00:17:54 +0000373 }
Ted Kremeneke4e63342007-09-06 00:17:54 +0000374}
375
Ted Kremenek88299892011-07-28 23:07:59 +0000376void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
377 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
378 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
379 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
380}
381
382void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek14f8b4f2008-08-05 20:46:55 +0000383 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();
384 DI != DE; ++DI)
Ted Kremenek9c378f72011-08-12 23:37:29 +0000385 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) {
Ted Kremenek88299892011-07-28 23:07:59 +0000386 if (!isAlwaysAlive(VD))
387 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekdcc48102008-02-25 22:28:54 +0000388 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000389}
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Ted Kremenek88299892011-07-28 23:07:59 +0000391void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
392 // Kill the iteration variable.
393 DeclRefExpr *DR = 0;
394 const VarDecl *VD = 0;
Ted Kremeneke4e63342007-09-06 00:17:54 +0000395
Ted Kremenek88299892011-07-28 23:07:59 +0000396 Stmt *element = OS->getElement();
397 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
398 VD = cast<VarDecl>(DS->getSingleDecl());
399 }
400 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
401 VD = cast<VarDecl>(DR->getDecl());
402 }
403
404 if (VD) {
405 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
406 if (observer && DR)
407 observer->observerKill(DR);
408 }
Ted Kremenekfdd225e2007-09-25 04:31:27 +0000409}
Ted Kremenek27b07c52007-09-06 21:26:58 +0000410
Ted Kremenek88299892011-07-28 23:07:59 +0000411void TransferFunctions::
412VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
413{
414 // While sizeof(var) doesn't technically extend the liveness of 'var', it
415 // does extent the liveness of metadata if 'var' is a VariableArrayType.
416 // We handle that special case here.
417 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
418 return;
419
Ted Kremenekf91a5b02011-08-06 00:30:00 +0000420 const Expr *subEx = UE->getArgumentExpr();
421 if (subEx->getType()->isVariableArrayType()) {
422 assert(subEx->isLValue());
423 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
424 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000425}
426
Ted Kremenek88299892011-07-28 23:07:59 +0000427void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
428 // Treat ++/-- as a kill.
429 // Note we don't actually have to do anything if we don't have an observer,
430 // since a ++/-- acts as both a kill and a "use".
431 if (!observer)
432 return;
433
434 switch (UO->getOpcode()) {
435 default:
436 return;
437 case UO_PostInc:
438 case UO_PostDec:
439 case UO_PreInc:
440 case UO_PreDec:
441 break;
442 }
443
444 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
445 if (isa<VarDecl>(DR->getDecl())) {
446 // Treat ++/-- as a kill.
447 observer->observerKill(DR);
448 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000449}
450
Ted Kremenek88299892011-07-28 23:07:59 +0000451LiveVariables::LivenessValues
452LiveVariablesImpl::runOnBlock(const CFGBlock *block,
453 LiveVariables::LivenessValues val,
454 LiveVariables::Observer *obs) {
455
456 TransferFunctions TF(*this, val, obs, block);
457
458 // Visit the terminator (if any).
459 if (const Stmt *term = block->getTerminator())
460 TF.Visit(const_cast<Stmt*>(term));
461
462 // Apply the transfer function for all Stmts in the block.
463 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
464 ei = block->rend(); it != ei; ++it) {
465 const CFGElement &elem = *it;
Jordan Rosed7f1d132012-07-26 20:04:08 +0000466
467 if (const CFGAutomaticObjDtor *Dtor = dyn_cast<CFGAutomaticObjDtor>(&elem)){
468 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
469 continue;
470 }
471
Ted Kremenek88299892011-07-28 23:07:59 +0000472 if (!isa<CFGStmt>(elem))
473 continue;
474
475 const Stmt *S = cast<CFGStmt>(elem).getStmt();
476 TF.Visit(const_cast<Stmt*>(S));
477 stmtsToLiveness[S] = val;
478 }
479 return val;
Ted Kremenek055c2752007-09-06 23:00:42 +0000480}
481
Ted Kremenek88299892011-07-28 23:07:59 +0000482void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
483 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
484 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
485 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek86946742008-01-17 20:48:37 +0000486}
487
Ted Kremenek88299892011-07-28 23:07:59 +0000488LiveVariables::LiveVariables(void *im) : impl(im) {}
489
490LiveVariables::~LiveVariables() {
491 delete (LiveVariablesImpl*) impl;
Ted Kremenek2a9da9c2008-01-18 00:40:21 +0000492}
493
Ted Kremenek88299892011-07-28 23:07:59 +0000494LiveVariables *
Ted Kremenek1d26f482011-10-24 01:32:45 +0000495LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremenek88299892011-07-28 23:07:59 +0000496 bool killAtAssign) {
Ted Kremeneke4e63342007-09-06 00:17:54 +0000497
Ted Kremenek88299892011-07-28 23:07:59 +0000498 // No CFG? Bail out.
499 CFG *cfg = AC.getCFG();
500 if (!cfg)
501 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Ted Kremenekd4aeb802012-07-02 20:21:52 +0000503 // The analysis currently has scalability issues for very large CFGs.
504 // Bail out if it looks too large.
505 if (cfg->getNumBlockIDs() > 300000)
506 return 0;
507
Ted Kremenek88299892011-07-28 23:07:59 +0000508 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
509
510 // Construct the dataflow worklist. Enqueue the exit block as the
511 // start of the analysis.
Ted Kremenekedb18632011-10-22 02:14:23 +0000512 DataflowWorklist worklist(*cfg, AC);
Ted Kremenek88299892011-07-28 23:07:59 +0000513 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
514
515 // FIXME: we should enqueue using post order.
516 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
517 const CFGBlock *block = *it;
518 worklist.enqueueBlock(block);
519
520 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
521 // We need to do this because we lack context in the reverse analysis
522 // to determine if a DeclRefExpr appears in such a context, and thus
523 // doesn't constitute a "use".
524 if (killAtAssign)
525 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
526 bi != be; ++bi) {
527 if (const CFGStmt *cs = bi->getAs<CFGStmt>()) {
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000528 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremenek88299892011-07-28 23:07:59 +0000529 if (BO->getOpcode() == BO_Assign) {
530 if (const DeclRefExpr *DR =
531 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
532 LV->inAssignment[DR] = 1;
533 }
534 }
535 }
536 }
537 }
538 }
539
Ted Kremenek87aa1252011-09-16 23:01:39 +0000540 worklist.sortWorklist();
541
542 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremenek88299892011-07-28 23:07:59 +0000543 // Determine if the block's end value has changed. If not, we
544 // have nothing left to do for this block.
545 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
546
547 // Merge the values of all successor blocks.
548 LivenessValues val;
549 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
550 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek87aa1252011-09-16 23:01:39 +0000551 if (const CFGBlock *succ = *it) {
Ted Kremenek88299892011-07-28 23:07:59 +0000552 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek87aa1252011-09-16 23:01:39 +0000553 }
Ted Kremenek88299892011-07-28 23:07:59 +0000554 }
555
556 if (!everAnalyzedBlock[block->getBlockID()])
557 everAnalyzedBlock[block->getBlockID()] = true;
558 else if (prevVal.equals(val))
559 continue;
560
561 prevVal = val;
562
563 // Update the dataflow value for the start of this block.
564 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
565
566 // Enqueue the value to the predecessors.
Ted Kremenek87aa1252011-09-16 23:01:39 +0000567 worklist.enqueuePredecessors(block);
Ted Kremenek88299892011-07-28 23:07:59 +0000568 }
569
570 return new LiveVariables(LV);
571}
572
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000573static bool compare_entries(const CFGBlock *A, const CFGBlock *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000574 return A->getBlockID() < B->getBlockID();
575}
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000576
577static bool compare_vd_entries(const Decl *A, const Decl *B) {
Ted Kremenek88299892011-07-28 23:07:59 +0000578 SourceLocation ALoc = A->getLocStart();
579 SourceLocation BLoc = B->getLocStart();
580 return ALoc.getRawEncoding() < BLoc.getRawEncoding();
581}
582
583void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
584 getImpl(impl).dumpBlockLiveness(M);
585}
586
587void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
588 std::vector<const CFGBlock *> vec;
589 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
590 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
591 it != ei; ++it) {
592 vec.push_back(it->first);
593 }
594 std::sort(vec.begin(), vec.end(), compare_entries);
595
596 std::vector<const VarDecl*> declVec;
597
598 for (std::vector<const CFGBlock *>::iterator
599 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
600 llvm::errs() << "\n[ B" << (*it)->getBlockID()
601 << " (live variables at block exit) ]\n";
602
603 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
604 declVec.clear();
605
606 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
607 vals.liveDecls.begin(),
608 se = vals.liveDecls.end(); si != se; ++si) {
609 declVec.push_back(*si);
610 }
611
612 std::sort(declVec.begin(), declVec.end(), compare_vd_entries);
613
614 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
615 de = declVec.end(); di != de; ++di) {
616 llvm::errs() << " " << (*di)->getDeclName().getAsString()
617 << " <";
618 (*di)->getLocation().dump(M);
Daniel Dunbarc0d56722009-10-17 18:12:37 +0000619 llvm::errs() << ">\n";
Ted Kremeneke4e63342007-09-06 00:17:54 +0000620 }
Ted Kremenek27b07c52007-09-06 21:26:58 +0000621 }
Ted Kremenek88299892011-07-28 23:07:59 +0000622 llvm::errs() << "\n";
Ted Kremenekc0576ca2007-09-10 17:36:42 +0000623}
Ted Kremenek88299892011-07-28 23:07:59 +0000624
Ted Kremeneka5937bb2011-10-07 22:21:02 +0000625const void *LiveVariables::getTag() { static int x; return &x; }
626const void *RelaxedLiveVariables::getTag() { static int x; return &x; }