blob: 0b5a236bed046a603b47cadb588c019a65c5d9c3 [file] [log] [blame]
Ted Kremenekbf593f82007-12-21 21:42:19 +00001#include "clang/Analysis/Analyses/LiveVariables.h"
Ted Kremenek5abde7c2011-10-22 02:14:23 +00002#include "clang/Analysis/Analyses/PostOrderCFGView.h"
3
Ted Kremeneke9fda1e2011-07-28 23:07:59 +00004#include "clang/AST/Stmt.h"
Ted Kremenek6796fbd2009-07-16 18:13:04 +00005#include "clang/Analysis/CFG.h"
Ted Kremenekd6b87082010-01-25 04:41:41 +00006#include "clang/Analysis/AnalysisContext.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +00007#include "clang/AST/StmtVisitor.h"
8
Ted Kremenek459597a2011-09-16 23:01:39 +00009#include "llvm/ADT/PostOrderIterator.h"
10#include "llvm/ADT/DenseMap.h"
11
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000012#include <deque>
13#include <algorithm>
14#include <vector>
Ted Kremenekb56a9902007-09-06 00:17:54 +000015
16using namespace clang;
17
Ted Kremenekb56a9902007-09-06 00:17:54 +000018namespace {
Mike Stump11289f42009-09-09 15:08:12 +000019
Ted Kremenek459597a2011-09-16 23:01:39 +000020class DataflowWorklist {
21 SmallVector<const CFGBlock *, 20> worklist;
22 llvm::BitVector enqueuedBlocks;
Ted Kremenek5abde7c2011-10-22 02:14:23 +000023 PostOrderCFGView *POV;
Ted Kremenek459597a2011-09-16 23:01:39 +000024public:
Ted Kremenek81ce1c82011-10-24 01:32:45 +000025 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
Ted Kremenek459597a2011-09-16 23:01:39 +000026 : enqueuedBlocks(cfg.getNumBlockIDs()),
Ted Kremenek5abde7c2011-10-22 02:14:23 +000027 POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
Ted Kremenek459597a2011-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 Kremenek5abde7c2011-10-22 02:14:23 +000074 std::sort(worklist.begin(), worklist.end(), POV->getComparator());
Ted Kremenek459597a2011-09-16 23:01:39 +000075}
76
Ted Kremenek459597a2011-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 Kremenek81ce1c82011-10-24 01:32:45 +000089 AnalysisDeclContext &analysisContext;
Ted Kremenek459597a2011-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 Kremenek81ce1c82011-10-24 01:32:45 +0000109 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenekc8f008a2011-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 Kremenek459597a2011-09-16 23:01:39 +0000114};
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000115}
Ted Kremenek82ff6d62008-04-15 18:35:30 +0000116
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000117static LiveVariablesImpl &getImpl(void *x) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000118 return *((LiveVariablesImpl *) x);
Ted Kremenekad8bce02007-09-25 04:31:27 +0000119}
Ted Kremenekb56a9902007-09-06 00:17:54 +0000120
121//===----------------------------------------------------------------------===//
Ted Kremeneke9fda1e2011-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 Kremenek459597a2011-09-16 23:01:39 +0000135 SET mergeSets(SET A, SET B) {
136 if (A.isEmpty())
137 return B;
138
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000139 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000140 A = A.add(*it);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000141 }
142 return A;
143 }
144}
145
146LiveVariables::LivenessValues
147LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
148 LiveVariables::LivenessValues valsB) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000149
150 llvm::ImmutableSetRef<const Stmt *>
151 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
152 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
153
154
155 llvm::ImmutableSetRef<const VarDecl *>
156 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
157 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
158
159
160 SSetRefA = mergeSets(SSetRefA, SSetRefB);
161 DSetRefA = mergeSets(DSetRefA, DSetRefB);
162
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000163 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
164 // comparison afterwards.
Ted Kremenek459597a2011-09-16 23:01:39 +0000165 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
166 DSetRefA.asImmutableSet());
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000167}
168
169bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
170 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
171}
172
173//===----------------------------------------------------------------------===//
174// Query methods.
175//===----------------------------------------------------------------------===//
176
177static bool isAlwaysAlive(const VarDecl *D) {
178 return D->hasGlobalStorage();
179}
180
181bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
182 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
183}
184
185bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
186 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
187}
188
189bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
190 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
191}
192
193//===----------------------------------------------------------------------===//
194// Dataflow computation.
Mike Stump11289f42009-09-09 15:08:12 +0000195//===----------------------------------------------------------------------===//
Ted Kremenekb56a9902007-09-06 00:17:54 +0000196
197namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000198class TransferFunctions : public StmtVisitor<TransferFunctions> {
199 LiveVariablesImpl &LV;
200 LiveVariables::LivenessValues &val;
201 LiveVariables::Observer *observer;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000202 const CFGBlock *currentBlock;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000203public:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000204 TransferFunctions(LiveVariablesImpl &im,
205 LiveVariables::LivenessValues &Val,
206 LiveVariables::Observer *Observer,
207 const CFGBlock *CurrentBlock)
208 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekad8bce02007-09-25 04:31:27 +0000209
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000210 void VisitBinaryOperator(BinaryOperator *BO);
211 void VisitBlockExpr(BlockExpr *BE);
212 void VisitDeclRefExpr(DeclRefExpr *DR);
213 void VisitDeclStmt(DeclStmt *DS);
214 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
215 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
216 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump11289f42009-09-09 15:08:12 +0000217 void Visit(Stmt *S);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000218};
Ted Kremenekfb4750b2007-10-01 20:33:52 +0000219}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000220
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000221static const VariableArrayType *FindVA(QualType Ty) {
222 const Type *ty = Ty.getTypePtr();
223 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
224 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
225 if (VAT->getSizeExpr())
226 return VAT;
227
228 ty = VT->getElementType().getTypePtr();
229 }
230
231 return 0;
232}
233
Ted Kremenek57170492011-11-05 00:26:53 +0000234static const Stmt *LookThroughStmt(const Stmt *S) {
235 while (S) {
236 switch (S->getStmtClass()) {
237 case Stmt::ParenExprClass: {
238 S = cast<ParenExpr>(S)->getSubExpr();
239 continue;
240 }
241 case Stmt::OpaqueValueExprClass: {
242 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
243 continue;
244 }
245 default:
246 break;
247 }
248 }
249 return S;
250}
251
252static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
253 llvm::ImmutableSet<const Stmt *>::Factory &F,
254 const Stmt *S) {
255 Set = F.add(Set, LookThroughStmt(S));
256}
257
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000258void TransferFunctions::Visit(Stmt *S) {
259 if (observer)
260 observer->observeStmt(S, currentBlock, val);
Ted Kremenek9c951ab2009-12-24 02:40:30 +0000261
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000262 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000263
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000264 if (isa<Expr>(S)) {
265 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
266 }
267
268 // Mark all children expressions live.
269
270 switch (S->getStmtClass()) {
271 default:
272 break;
273 case Stmt::StmtExprClass: {
274 // For statement expressions, look through the compound statement.
275 S = cast<StmtExpr>(S)->getSubStmt();
276 break;
277 }
278 case Stmt::CXXMemberCallExprClass: {
279 // Include the implicit "this" pointer as being live.
280 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000281 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenek57170492011-11-05 00:26:53 +0000282 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000283 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000284 break;
285 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000286 case Stmt::DeclStmtClass: {
287 const DeclStmt *DS = cast<DeclStmt>(S);
288 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
289 for (const VariableArrayType* VA = FindVA(VD->getType());
290 VA != 0; VA = FindVA(VA->getElementType())) {
Ted Kremenek57170492011-11-05 00:26:53 +0000291 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000292 }
293 }
294 break;
295 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000296 // FIXME: These cases eventually shouldn't be needed.
297 case Stmt::ExprWithCleanupsClass: {
298 S = cast<ExprWithCleanups>(S)->getSubExpr();
299 break;
300 }
301 case Stmt::CXXBindTemporaryExprClass: {
302 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
303 break;
304 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000305 case Stmt::UnaryExprOrTypeTraitExprClass: {
306 // No need to unconditionally visit subexpressions.
307 return;
308 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000309 }
310
311 for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
312 it != ei; ++it) {
Ted Kremenek57170492011-11-05 00:26:53 +0000313 if (Stmt *child = *it)
314 AddLiveStmt(val.liveStmts, LV.SSetFact, child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000315 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000316}
Mike Stump11289f42009-09-09 15:08:12 +0000317
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000318void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
319 if (B->isAssignmentOp()) {
320 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000321 return;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000322
323 // Assigning to a variable?
324 Expr *LHS = B->getLHS()->IgnoreParens();
325
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000326 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000327 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
328 // Assignments to references don't kill the ref's address
329 if (VD->getType()->isReferenceType())
330 return;
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000331
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000332 if (!isAlwaysAlive(VD)) {
333 // The variable is now dead.
334 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
335 }
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000336
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000337 if (observer)
338 observer->observerKill(DR);
Ted Kremenek20c91422008-02-22 00:34:10 +0000339 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000340 }
341}
Mike Stump11289f42009-09-09 15:08:12 +0000342
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000343void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000344 AnalysisDeclContext::referenced_decls_iterator I, E;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000345 llvm::tie(I, E) =
346 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
347 for ( ; I != E ; ++I) {
348 const VarDecl *VD = *I;
349 if (isAlwaysAlive(VD))
350 continue;
351 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000352 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000353}
354
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000355void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
356 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
357 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
358 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
359}
360
361void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Ted Kremenek4f8792b2008-08-05 20:46:55 +0000362 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();
363 DI != DE; ++DI)
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000364 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000365 if (!isAlwaysAlive(VD))
366 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000367 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000368}
Mike Stump11289f42009-09-09 15:08:12 +0000369
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000370void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
371 // Kill the iteration variable.
372 DeclRefExpr *DR = 0;
373 const VarDecl *VD = 0;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000374
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000375 Stmt *element = OS->getElement();
376 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
377 VD = cast<VarDecl>(DS->getSingleDecl());
378 }
379 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
380 VD = cast<VarDecl>(DR->getDecl());
381 }
382
383 if (VD) {
384 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
385 if (observer && DR)
386 observer->observerKill(DR);
387 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000388}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000389
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000390void TransferFunctions::
391VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
392{
393 // While sizeof(var) doesn't technically extend the liveness of 'var', it
394 // does extent the liveness of metadata if 'var' is a VariableArrayType.
395 // We handle that special case here.
396 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
397 return;
398
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000399 const Expr *subEx = UE->getArgumentExpr();
400 if (subEx->getType()->isVariableArrayType()) {
401 assert(subEx->isLValue());
402 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
403 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000404}
405
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000406void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
407 // Treat ++/-- as a kill.
408 // Note we don't actually have to do anything if we don't have an observer,
409 // since a ++/-- acts as both a kill and a "use".
410 if (!observer)
411 return;
412
413 switch (UO->getOpcode()) {
414 default:
415 return;
416 case UO_PostInc:
417 case UO_PostDec:
418 case UO_PreInc:
419 case UO_PreDec:
420 break;
421 }
422
423 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
424 if (isa<VarDecl>(DR->getDecl())) {
425 // Treat ++/-- as a kill.
426 observer->observerKill(DR);
427 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000428}
429
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000430LiveVariables::LivenessValues
431LiveVariablesImpl::runOnBlock(const CFGBlock *block,
432 LiveVariables::LivenessValues val,
433 LiveVariables::Observer *obs) {
434
435 TransferFunctions TF(*this, val, obs, block);
436
437 // Visit the terminator (if any).
438 if (const Stmt *term = block->getTerminator())
439 TF.Visit(const_cast<Stmt*>(term));
440
441 // Apply the transfer function for all Stmts in the block.
442 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
443 ei = block->rend(); it != ei; ++it) {
444 const CFGElement &elem = *it;
445 if (!isa<CFGStmt>(elem))
446 continue;
447
448 const Stmt *S = cast<CFGStmt>(elem).getStmt();
449 TF.Visit(const_cast<Stmt*>(S));
450 stmtsToLiveness[S] = val;
451 }
452 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000453}
454
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000455void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
456 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
457 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
458 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000459}
460
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000461LiveVariables::LiveVariables(void *im) : impl(im) {}
462
463LiveVariables::~LiveVariables() {
464 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000465}
466
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000467LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000468LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000469 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000470
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000471 // No CFG? Bail out.
472 CFG *cfg = AC.getCFG();
473 if (!cfg)
474 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000475
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000476 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
477
478 // Construct the dataflow worklist. Enqueue the exit block as the
479 // start of the analysis.
Ted Kremenek5abde7c2011-10-22 02:14:23 +0000480 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000481 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
482
483 // FIXME: we should enqueue using post order.
484 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
485 const CFGBlock *block = *it;
486 worklist.enqueueBlock(block);
487
488 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
489 // We need to do this because we lack context in the reverse analysis
490 // to determine if a DeclRefExpr appears in such a context, and thus
491 // doesn't constitute a "use".
492 if (killAtAssign)
493 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
494 bi != be; ++bi) {
495 if (const CFGStmt *cs = bi->getAs<CFGStmt>()) {
Ted Kremenekadfb4452011-08-23 23:05:04 +0000496 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000497 if (BO->getOpcode() == BO_Assign) {
498 if (const DeclRefExpr *DR =
499 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
500 LV->inAssignment[DR] = 1;
501 }
502 }
503 }
504 }
505 }
506 }
507
Ted Kremenek459597a2011-09-16 23:01:39 +0000508 worklist.sortWorklist();
509
510 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000511 // Determine if the block's end value has changed. If not, we
512 // have nothing left to do for this block.
513 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
514
515 // Merge the values of all successor blocks.
516 LivenessValues val;
517 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
518 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000519 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000520 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000521 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000522 }
523
524 if (!everAnalyzedBlock[block->getBlockID()])
525 everAnalyzedBlock[block->getBlockID()] = true;
526 else if (prevVal.equals(val))
527 continue;
528
529 prevVal = val;
530
531 // Update the dataflow value for the start of this block.
532 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
533
534 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000535 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000536 }
537
538 return new LiveVariables(LV);
539}
540
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000541static bool compare_entries(const CFGBlock *A, const CFGBlock *B) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000542 return A->getBlockID() < B->getBlockID();
543}
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000544
545static bool compare_vd_entries(const Decl *A, const Decl *B) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000546 SourceLocation ALoc = A->getLocStart();
547 SourceLocation BLoc = B->getLocStart();
548 return ALoc.getRawEncoding() < BLoc.getRawEncoding();
549}
550
551void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
552 getImpl(impl).dumpBlockLiveness(M);
553}
554
555void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
556 std::vector<const CFGBlock *> vec;
557 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
558 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
559 it != ei; ++it) {
560 vec.push_back(it->first);
561 }
562 std::sort(vec.begin(), vec.end(), compare_entries);
563
564 std::vector<const VarDecl*> declVec;
565
566 for (std::vector<const CFGBlock *>::iterator
567 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
568 llvm::errs() << "\n[ B" << (*it)->getBlockID()
569 << " (live variables at block exit) ]\n";
570
571 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
572 declVec.clear();
573
574 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
575 vals.liveDecls.begin(),
576 se = vals.liveDecls.end(); si != se; ++si) {
577 declVec.push_back(*si);
578 }
579
580 std::sort(declVec.begin(), declVec.end(), compare_vd_entries);
581
582 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
583 de = declVec.end(); di != de; ++di) {
584 llvm::errs() << " " << (*di)->getDeclName().getAsString()
585 << " <";
586 (*di)->getLocation().dump(M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000587 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000588 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000589 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000590 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000591}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000592
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000593const void *LiveVariables::getTag() { static int x; return &x; }
594const void *RelaxedLiveVariables::getTag() { static int x; return &x; }