blob: cd73a62e6918c1af735ec954bcca89f0df96c3e4 [file] [log] [blame]
Benjamin Kramer444a1302012-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 Kremenekbf593f82007-12-21 21:42:19 +000014#include "clang/Analysis/Analyses/LiveVariables.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000015#include "clang/AST/Stmt.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000016#include "clang/AST/StmtVisitor.h"
Artyom Skrobov27720762014-09-23 08:34:41 +000017#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Analysis/AnalysisContext.h"
19#include "clang/Analysis/CFG.h"
Ted Kremenek459597a2011-09-16 23:01:39 +000020#include "llvm/ADT/DenseMap.h"
Artyom Skrobov27720762014-09-23 08:34:41 +000021#include "llvm/ADT/PostOrderIterator.h"
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000022#include "llvm/ADT/PriorityQueue.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000024#include <algorithm>
25#include <vector>
Ted Kremenekb56a9902007-09-06 00:17:54 +000026
27using namespace clang;
28
Ted Kremenekb56a9902007-09-06 00:17:54 +000029namespace {
Artyom Skrobov27720762014-09-23 08:34:41 +000030
31class DataflowWorklist {
Artyom Skrobov27720762014-09-23 08:34:41 +000032 llvm::BitVector enqueuedBlocks;
33 PostOrderCFGView *POV;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000034 llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
35 PostOrderCFGView::BlockOrderCompare> worklist;
36
Artyom Skrobov27720762014-09-23 08:34:41 +000037public:
38 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
39 : enqueuedBlocks(cfg.getNumBlockIDs()),
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000040 POV(Ctx.getAnalysis<PostOrderCFGView>()),
41 worklist(POV->getComparator()) {}
Artyom Skrobov27720762014-09-23 08:34:41 +000042
43 void enqueueBlock(const CFGBlock *block);
44 void enqueuePredecessors(const CFGBlock *block);
45
46 const CFGBlock *dequeue();
Artyom Skrobov27720762014-09-23 08:34:41 +000047};
48
Alexander Kornienkoab9db512015-06-22 23:07:51 +000049}
Artyom Skrobov27720762014-09-23 08:34:41 +000050
51void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
52 if (block && !enqueuedBlocks[block->getBlockID()]) {
53 enqueuedBlocks[block->getBlockID()] = true;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000054 worklist.push(block);
Artyom Skrobov27720762014-09-23 08:34:41 +000055 }
56}
57
58void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
Artyom Skrobov27720762014-09-23 08:34:41 +000059 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
60 E = block->pred_end(); I != E; ++I) {
61 enqueueBlock(*I);
62 }
Artyom Skrobov27720762014-09-23 08:34:41 +000063}
64
65const CFGBlock *DataflowWorklist::dequeue() {
66 if (worklist.empty())
67 return nullptr;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000068 const CFGBlock *b = worklist.top();
69 worklist.pop();
Artyom Skrobov27720762014-09-23 08:34:41 +000070 enqueuedBlocks[b->getBlockID()] = false;
71 return b;
72}
73
74namespace {
Ted Kremenek459597a2011-09-16 23:01:39 +000075class LiveVariablesImpl {
76public:
Ted Kremenek81ce1c82011-10-24 01:32:45 +000077 AnalysisDeclContext &analysisContext;
Ted Kremenek459597a2011-09-16 23:01:39 +000078 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
79 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
80 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
81 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
82 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
83 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
84 const bool killAtAssign;
85
86 LiveVariables::LivenessValues
87 merge(LiveVariables::LivenessValues valsA,
88 LiveVariables::LivenessValues valsB);
Craig Topper25542942014-05-20 04:30:07 +000089
90 LiveVariables::LivenessValues
91 runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
92 LiveVariables::Observer *obs = nullptr);
Ted Kremenek459597a2011-09-16 23:01:39 +000093
94 void dumpBlockLiveness(const SourceManager& M);
95
Ted Kremenek81ce1c82011-10-24 01:32:45 +000096 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenekc8f008a2011-10-02 01:45:37 +000097 : analysisContext(ac),
98 SSetFact(false), // Do not canonicalize ImmutableSets by default.
99 DSetFact(false), // This is a *major* performance win.
100 killAtAssign(KillAtAssign) {}
Ted Kremenek459597a2011-09-16 23:01:39 +0000101};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000102}
Ted Kremenek82ff6d62008-04-15 18:35:30 +0000103
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000104static LiveVariablesImpl &getImpl(void *x) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000105 return *((LiveVariablesImpl *) x);
Ted Kremenekad8bce02007-09-25 04:31:27 +0000106}
Ted Kremenekb56a9902007-09-06 00:17:54 +0000107
108//===----------------------------------------------------------------------===//
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000109// Operations and queries on LivenessValues.
110//===----------------------------------------------------------------------===//
111
112bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
113 return liveStmts.contains(S);
114}
115
116bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
117 return liveDecls.contains(D);
118}
119
120namespace {
121 template <typename SET>
Ted Kremenek459597a2011-09-16 23:01:39 +0000122 SET mergeSets(SET A, SET B) {
123 if (A.isEmpty())
124 return B;
125
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000126 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000127 A = A.add(*it);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000128 }
129 return A;
130 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000131}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000132
David Blaikie68e081d2011-12-20 02:48:34 +0000133void LiveVariables::Observer::anchor() { }
134
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000135LiveVariables::LivenessValues
136LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
137 LiveVariables::LivenessValues valsB) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000138
139 llvm::ImmutableSetRef<const Stmt *>
140 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
141 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
142
143
144 llvm::ImmutableSetRef<const VarDecl *>
145 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
146 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
147
148
149 SSetRefA = mergeSets(SSetRefA, SSetRefB);
150 DSetRefA = mergeSets(DSetRefA, DSetRefB);
151
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000152 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
153 // comparison afterwards.
Ted Kremenek459597a2011-09-16 23:01:39 +0000154 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
155 DSetRefA.asImmutableSet());
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000156}
157
158bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
159 return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
160}
161
162//===----------------------------------------------------------------------===//
163// Query methods.
164//===----------------------------------------------------------------------===//
165
166static bool isAlwaysAlive(const VarDecl *D) {
167 return D->hasGlobalStorage();
168}
169
170bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
171 return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
172}
173
174bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
175 return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
176}
177
178bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
179 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
180}
181
182//===----------------------------------------------------------------------===//
183// Dataflow computation.
Mike Stump11289f42009-09-09 15:08:12 +0000184//===----------------------------------------------------------------------===//
Ted Kremenekb56a9902007-09-06 00:17:54 +0000185
186namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000187class TransferFunctions : public StmtVisitor<TransferFunctions> {
188 LiveVariablesImpl &LV;
189 LiveVariables::LivenessValues &val;
190 LiveVariables::Observer *observer;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000191 const CFGBlock *currentBlock;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000192public:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000193 TransferFunctions(LiveVariablesImpl &im,
194 LiveVariables::LivenessValues &Val,
195 LiveVariables::Observer *Observer,
196 const CFGBlock *CurrentBlock)
197 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
Ted Kremenekad8bce02007-09-25 04:31:27 +0000198
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000199 void VisitBinaryOperator(BinaryOperator *BO);
200 void VisitBlockExpr(BlockExpr *BE);
201 void VisitDeclRefExpr(DeclRefExpr *DR);
202 void VisitDeclStmt(DeclStmt *DS);
203 void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
204 void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
205 void VisitUnaryOperator(UnaryOperator *UO);
Mike Stump11289f42009-09-09 15:08:12 +0000206 void Visit(Stmt *S);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000207};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000208}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000209
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000210static const VariableArrayType *FindVA(QualType Ty) {
211 const Type *ty = Ty.getTypePtr();
212 while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
213 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
214 if (VAT->getSizeExpr())
215 return VAT;
216
217 ty = VT->getElementType().getTypePtr();
218 }
Craig Topper25542942014-05-20 04:30:07 +0000219
220 return nullptr;
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000221}
222
Ted Kremenek57170492011-11-05 00:26:53 +0000223static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek977e30d2011-11-05 07:34:28 +0000224 while (S) {
225 if (const Expr *Ex = dyn_cast<Expr>(S))
226 S = Ex->IgnoreParens();
John McCall29928fc2011-11-09 17:10:36 +0000227 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
228 S = EWC->getSubExpr();
229 continue;
230 }
Ted Kremenek977e30d2011-11-05 07:34:28 +0000231 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
232 S = OVE->getSourceExpr();
233 continue;
234 }
235 break;
236 }
Ted Kremenek57170492011-11-05 00:26:53 +0000237 return S;
238}
239
240static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
241 llvm::ImmutableSet<const Stmt *>::Factory &F,
242 const Stmt *S) {
243 Set = F.add(Set, LookThroughStmt(S));
244}
245
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000246void TransferFunctions::Visit(Stmt *S) {
247 if (observer)
248 observer->observeStmt(S, currentBlock, val);
Ted Kremenek9c951ab2009-12-24 02:40:30 +0000249
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000250 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000251
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000252 if (isa<Expr>(S)) {
253 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
254 }
255
256 // Mark all children expressions live.
257
258 switch (S->getStmtClass()) {
259 default:
260 break;
261 case Stmt::StmtExprClass: {
262 // For statement expressions, look through the compound statement.
263 S = cast<StmtExpr>(S)->getSubStmt();
264 break;
265 }
266 case Stmt::CXXMemberCallExprClass: {
267 // Include the implicit "this" pointer as being live.
268 CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000269 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenek57170492011-11-05 00:26:53 +0000270 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000271 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000272 break;
273 }
Anna Zaks23665a12012-08-14 00:36:20 +0000274 case Stmt::ObjCMessageExprClass: {
275 // In calls to super, include the implicit "self" pointer as being live.
276 ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
277 if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
278 val.liveDecls = LV.DSetFact.add(val.liveDecls,
279 LV.analysisContext.getSelfDecl());
280 break;
281 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000282 case Stmt::DeclStmtClass: {
283 const DeclStmt *DS = cast<DeclStmt>(S);
284 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
285 for (const VariableArrayType* VA = FindVA(VD->getType());
Craig Topper25542942014-05-20 04:30:07 +0000286 VA != nullptr; VA = FindVA(VA->getElementType())) {
Ted Kremenek57170492011-11-05 00:26:53 +0000287 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000288 }
289 }
290 break;
291 }
John McCallfe96e0b2011-11-06 09:01:30 +0000292 case Stmt::PseudoObjectExprClass: {
293 // A pseudo-object operation only directly consumes its result
294 // expression.
295 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
296 if (!child) return;
297 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
298 child = OV->getSourceExpr();
299 child = child->IgnoreParens();
300 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
301 return;
302 }
303
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000304 // FIXME: These cases eventually shouldn't be needed.
305 case Stmt::ExprWithCleanupsClass: {
306 S = cast<ExprWithCleanups>(S)->getSubExpr();
307 break;
308 }
309 case Stmt::CXXBindTemporaryExprClass: {
310 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
311 break;
312 }
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000313 case Stmt::UnaryExprOrTypeTraitExprClass: {
314 // No need to unconditionally visit subexpressions.
315 return;
316 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000317 }
Benjamin Kramer973431b2015-07-03 15:12:24 +0000318
319 for (Stmt *Child : S->children()) {
320 if (Child)
321 AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000322 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000323}
Mike Stump11289f42009-09-09 15:08:12 +0000324
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000325void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
326 if (B->isAssignmentOp()) {
327 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000328 return;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000329
330 // Assigning to a variable?
331 Expr *LHS = B->getLHS()->IgnoreParens();
332
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000333 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000334 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
335 // Assignments to references don't kill the ref's address
336 if (VD->getType()->isReferenceType())
337 return;
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000338
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000339 if (!isAlwaysAlive(VD)) {
340 // The variable is now dead.
341 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
342 }
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000343
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000344 if (observer)
345 observer->observerKill(DR);
Ted Kremenek20c91422008-02-22 00:34:10 +0000346 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000347 }
348}
Mike Stump11289f42009-09-09 15:08:12 +0000349
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000350void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000351 for (const VarDecl *VD :
352 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000353 if (isAlwaysAlive(VD))
354 continue;
355 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000356 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000357}
358
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000359void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
360 if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
361 if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
362 val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
363}
364
365void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
Aaron Ballman535bbcc2014-03-14 17:01:24 +0000366 for (const auto *DI : DS->decls())
367 if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000368 if (!isAlwaysAlive(VD))
369 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000370 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000371}
Mike Stump11289f42009-09-09 15:08:12 +0000372
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000373void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
374 // Kill the iteration variable.
Craig Topper25542942014-05-20 04:30:07 +0000375 DeclRefExpr *DR = nullptr;
376 const VarDecl *VD = nullptr;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000377
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000378 Stmt *element = OS->getElement();
379 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
380 VD = cast<VarDecl>(DS->getSingleDecl());
381 }
382 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
383 VD = cast<VarDecl>(DR->getDecl());
384 }
385
386 if (VD) {
387 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
388 if (observer && DR)
389 observer->observerKill(DR);
390 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000391}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000392
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000393void TransferFunctions::
394VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
395{
396 // While sizeof(var) doesn't technically extend the liveness of 'var', it
397 // does extent the liveness of metadata if 'var' is a VariableArrayType.
398 // We handle that special case here.
399 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
400 return;
401
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000402 const Expr *subEx = UE->getArgumentExpr();
403 if (subEx->getType()->isVariableArrayType()) {
404 assert(subEx->isLValue());
405 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
406 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000407}
408
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000409void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
410 // Treat ++/-- as a kill.
411 // Note we don't actually have to do anything if we don't have an observer,
412 // since a ++/-- acts as both a kill and a "use".
413 if (!observer)
414 return;
415
416 switch (UO->getOpcode()) {
417 default:
418 return;
419 case UO_PostInc:
420 case UO_PostDec:
421 case UO_PreInc:
422 case UO_PreDec:
423 break;
424 }
425
426 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
427 if (isa<VarDecl>(DR->getDecl())) {
428 // Treat ++/-- as a kill.
429 observer->observerKill(DR);
430 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000431}
432
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000433LiveVariables::LivenessValues
434LiveVariablesImpl::runOnBlock(const CFGBlock *block,
435 LiveVariables::LivenessValues val,
436 LiveVariables::Observer *obs) {
437
438 TransferFunctions TF(*this, val, obs, block);
439
440 // Visit the terminator (if any).
441 if (const Stmt *term = block->getTerminator())
442 TF.Visit(const_cast<Stmt*>(term));
443
444 // Apply the transfer function for all Stmts in the block.
445 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
446 ei = block->rend(); it != ei; ++it) {
447 const CFGElement &elem = *it;
Jordan Roseb3244562012-07-26 20:04:08 +0000448
David Blaikie00be69a2013-02-23 00:29:34 +0000449 if (Optional<CFGAutomaticObjDtor> Dtor =
450 elem.getAs<CFGAutomaticObjDtor>()) {
451 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Roseb3244562012-07-26 20:04:08 +0000452 continue;
453 }
454
David Blaikie2a01f5d2013-02-21 20:58:29 +0000455 if (!elem.getAs<CFGStmt>())
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000456 continue;
457
David Blaikie2a01f5d2013-02-21 20:58:29 +0000458 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000459 TF.Visit(const_cast<Stmt*>(S));
460 stmtsToLiveness[S] = val;
461 }
462 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000463}
464
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000465void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
466 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
467 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
468 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000469}
470
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000471LiveVariables::LiveVariables(void *im) : impl(im) {}
472
473LiveVariables::~LiveVariables() {
474 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000475}
476
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000477LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000478LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000479 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000480
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000481 // No CFG? Bail out.
482 CFG *cfg = AC.getCFG();
483 if (!cfg)
Craig Topper25542942014-05-20 04:30:07 +0000484 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000485
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000486 // The analysis currently has scalability issues for very large CFGs.
487 // Bail out if it looks too large.
488 if (cfg->getNumBlockIDs() > 300000)
Craig Topper25542942014-05-20 04:30:07 +0000489 return nullptr;
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000490
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000491 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
492
Artyom Skrobov27720762014-09-23 08:34:41 +0000493 // Construct the dataflow worklist. Enqueue the exit block as the
494 // start of the analysis.
495 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000496 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
497
Artyom Skrobov27720762014-09-23 08:34:41 +0000498 // FIXME: we should enqueue using post order.
499 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
500 const CFGBlock *block = *it;
501 worklist.enqueueBlock(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000502
503 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
504 // We need to do this because we lack context in the reverse analysis
505 // to determine if a DeclRefExpr appears in such a context, and thus
506 // doesn't constitute a "use".
Artyom Skrobov27720762014-09-23 08:34:41 +0000507 if (killAtAssign)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000508 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
509 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000510 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
511 if (const BinaryOperator *BO =
512 dyn_cast<BinaryOperator>(cs->getStmt())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000513 if (BO->getOpcode() == BO_Assign) {
514 if (const DeclRefExpr *DR =
515 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
516 LV->inAssignment[DR] = 1;
517 }
518 }
519 }
520 }
521 }
Artyom Skrobov27720762014-09-23 08:34:41 +0000522 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000523
Artyom Skrobov27720762014-09-23 08:34:41 +0000524 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000525 // Determine if the block's end value has changed. If not, we
526 // have nothing left to do for this block.
527 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
528
529 // Merge the values of all successor blocks.
530 LivenessValues val;
531 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
532 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000533 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000534 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000535 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000536 }
537
538 if (!everAnalyzedBlock[block->getBlockID()])
539 everAnalyzedBlock[block->getBlockID()] = true;
540 else if (prevVal.equals(val))
541 continue;
542
543 prevVal = val;
544
545 // Update the dataflow value for the start of this block.
546 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
547
548 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000549 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000550 }
551
552 return new LiveVariables(LV);
553}
554
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000555void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
556 getImpl(impl).dumpBlockLiveness(M);
557}
558
559void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
560 std::vector<const CFGBlock *> vec;
561 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
562 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
563 it != ei; ++it) {
564 vec.push_back(it->first);
565 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000566 std::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
567 return A->getBlockID() < B->getBlockID();
568 });
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000569
570 std::vector<const VarDecl*> declVec;
571
572 for (std::vector<const CFGBlock *>::iterator
573 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
574 llvm::errs() << "\n[ B" << (*it)->getBlockID()
575 << " (live variables at block exit) ]\n";
576
577 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
578 declVec.clear();
579
580 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
581 vals.liveDecls.begin(),
582 se = vals.liveDecls.end(); si != se; ++si) {
583 declVec.push_back(*si);
584 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000585
586 std::sort(declVec.begin(), declVec.end(), [](const Decl *A, const Decl *B) {
587 return A->getLocStart() < B->getLocStart();
588 });
589
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000590 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
591 de = declVec.end(); di != de; ++di) {
592 llvm::errs() << " " << (*di)->getDeclName().getAsString()
593 << " <";
594 (*di)->getLocation().dump(M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000595 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000596 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000597 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000598 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000599}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000600
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000601const void *LiveVariables::getTag() { static int x; return &x; }
602const void *RelaxedLiveVariables::getTag() { static int x; return &x; }