blob: d03d2a052d2cf535a709fc3cc6edf0acf78a4760 [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"
George Karpenkov50657f62017-09-06 21:45:03 +000018#include "clang/Analysis/AnalysisDeclContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#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;
George Karpenkov137ca912018-03-31 01:20:06 +000080 llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
Ted Kremenek459597a2011-09-16 23:01:39 +000081 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
82 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
83 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
84 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
85 const bool killAtAssign;
86
87 LiveVariables::LivenessValues
88 merge(LiveVariables::LivenessValues valsA,
89 LiveVariables::LivenessValues valsB);
Craig Topper25542942014-05-20 04:30:07 +000090
91 LiveVariables::LivenessValues
92 runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
93 LiveVariables::Observer *obs = nullptr);
Ted Kremenek459597a2011-09-16 23:01:39 +000094
95 void dumpBlockLiveness(const SourceManager& M);
96
Ted Kremenek81ce1c82011-10-24 01:32:45 +000097 LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
Ted Kremenekc8f008a2011-10-02 01:45:37 +000098 : analysisContext(ac),
99 SSetFact(false), // Do not canonicalize ImmutableSets by default.
100 DSetFact(false), // This is a *major* performance win.
George Karpenkov137ca912018-03-31 01:20:06 +0000101 BSetFact(false),
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000102 killAtAssign(KillAtAssign) {}
Ted Kremenek459597a2011-09-16 23:01:39 +0000103};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000104}
Ted Kremenek82ff6d62008-04-15 18:35:30 +0000105
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000106static LiveVariablesImpl &getImpl(void *x) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000107 return *((LiveVariablesImpl *) x);
Ted Kremenekad8bce02007-09-25 04:31:27 +0000108}
Ted Kremenekb56a9902007-09-06 00:17:54 +0000109
110//===----------------------------------------------------------------------===//
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000111// Operations and queries on LivenessValues.
112//===----------------------------------------------------------------------===//
113
114bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
115 return liveStmts.contains(S);
116}
117
118bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
George Karpenkov137ca912018-03-31 01:20:06 +0000119 if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
120 bool alive = false;
121 for (const BindingDecl *BD : DD->bindings())
122 alive |= liveBindings.contains(BD);
123 return alive;
124 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000125 return liveDecls.contains(D);
126}
127
128namespace {
129 template <typename SET>
Ted Kremenek459597a2011-09-16 23:01:39 +0000130 SET mergeSets(SET A, SET B) {
131 if (A.isEmpty())
132 return B;
133
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000134 for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000135 A = A.add(*it);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000136 }
137 return A;
138 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000139}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000140
David Blaikie68e081d2011-12-20 02:48:34 +0000141void LiveVariables::Observer::anchor() { }
142
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000143LiveVariables::LivenessValues
144LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
145 LiveVariables::LivenessValues valsB) {
Ted Kremenek459597a2011-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
George Karpenkov137ca912018-03-31 01:20:06 +0000156 llvm::ImmutableSetRef<const BindingDecl *>
157 BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
158 BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
Ted Kremenek459597a2011-09-16 23:01:39 +0000159
160 SSetRefA = mergeSets(SSetRefA, SSetRefB);
161 DSetRefA = mergeSets(DSetRefA, DSetRefB);
George Karpenkov137ca912018-03-31 01:20:06 +0000162 BSetRefA = mergeSets(BSetRefA, BSetRefB);
Ted Kremenek459597a2011-09-16 23:01:39 +0000163
Ted Kremenekc8f008a2011-10-02 01:45:37 +0000164 // asImmutableSet() canonicalizes the tree, allowing us to do an easy
165 // comparison afterwards.
Ted Kremenek459597a2011-09-16 23:01:39 +0000166 return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
George Karpenkov137ca912018-03-31 01:20:06 +0000167 DSetRefA.asImmutableSet(),
168 BSetRefA.asImmutableSet());
Ted Kremeneke9fda1e2011-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 Stump11289f42009-09-09 15:08:12 +0000197//===----------------------------------------------------------------------===//
Ted Kremenekb56a9902007-09-06 00:17:54 +0000198
199namespace {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000200class TransferFunctions : public StmtVisitor<TransferFunctions> {
201 LiveVariablesImpl &LV;
202 LiveVariables::LivenessValues &val;
203 LiveVariables::Observer *observer;
Ted Kremenek9865d7f2011-02-11 23:24:26 +0000204 const CFGBlock *currentBlock;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000205public:
Ted Kremeneke9fda1e2011-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 Kremenekad8bce02007-09-25 04:31:27 +0000211
Ted Kremeneke9fda1e2011-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 Stump11289f42009-09-09 15:08:12 +0000219 void Visit(Stmt *S);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000220};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000221}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000222
Ted Kremenek84a1ca52011-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 }
Craig Topper25542942014-05-20 04:30:07 +0000232
233 return nullptr;
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000234}
235
Ted Kremenek57170492011-11-05 00:26:53 +0000236static const Stmt *LookThroughStmt(const Stmt *S) {
Ted Kremenek977e30d2011-11-05 07:34:28 +0000237 while (S) {
238 if (const Expr *Ex = dyn_cast<Expr>(S))
239 S = Ex->IgnoreParens();
John McCall29928fc2011-11-09 17:10:36 +0000240 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
241 S = EWC->getSubExpr();
242 continue;
243 }
Ted Kremenek977e30d2011-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 Kremenek57170492011-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 Kremeneke9fda1e2011-07-28 23:07:59 +0000259void TransferFunctions::Visit(Stmt *S) {
260 if (observer)
261 observer->observeStmt(S, currentBlock, val);
Ted Kremenek9c951ab2009-12-24 02:40:30 +0000262
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000263 StmtVisitor<TransferFunctions>::Visit(S);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000264
Ted Kremeneke9fda1e2011-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 Kremenekb7531d62011-10-06 20:53:28 +0000282 if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
Ted Kremenek57170492011-11-05 00:26:53 +0000283 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
Ted Kremenekb7531d62011-10-06 20:53:28 +0000284 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000285 break;
286 }
Anna Zaks23665a12012-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 Kremenek84a1ca52011-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());
Craig Topper25542942014-05-20 04:30:07 +0000299 VA != nullptr; VA = FindVA(VA->getElementType())) {
Ted Kremenek57170492011-11-05 00:26:53 +0000300 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000301 }
302 }
303 break;
304 }
John McCallfe96e0b2011-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 Kremeneke9fda1e2011-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 Kremenek84a1ca52011-08-06 00:30:00 +0000326 case Stmt::UnaryExprOrTypeTraitExprClass: {
327 // No need to unconditionally visit subexpressions.
328 return;
329 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000330 }
Benjamin Kramer973431b2015-07-03 15:12:24 +0000331
332 for (Stmt *Child : S->children()) {
333 if (Child)
334 AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000335 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000336}
Mike Stump11289f42009-09-09 15:08:12 +0000337
George Karpenkov137ca912018-03-31 01:20:06 +0000338static bool writeShouldKill(const VarDecl *VD) {
339 return VD && !VD->getType()->isReferenceType() &&
340 !isAlwaysAlive(VD);
341}
342
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000343void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
344 if (B->isAssignmentOp()) {
345 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000346 return;
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000347
348 // Assigning to a variable?
349 Expr *LHS = B->getLHS()->IgnoreParens();
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000350
George Karpenkov137ca912018-03-31 01:20:06 +0000351 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
352 const Decl* D = DR->getDecl();
353 bool Killed = false;
354
355 if (const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
356 Killed = !BD->getType()->isReferenceType();
357 if (Killed)
358 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
359 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
360 Killed = writeShouldKill(VD);
361 if (Killed)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000362 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000363
Ted Kremenek20c91422008-02-22 00:34:10 +0000364 }
George Karpenkov137ca912018-03-31 01:20:06 +0000365
366 if (Killed && observer)
367 observer->observerKill(DR);
368 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000369 }
370}
Mike Stump11289f42009-09-09 15:08:12 +0000371
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000372void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000373 for (const VarDecl *VD :
374 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000375 if (isAlwaysAlive(VD))
376 continue;
377 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000378 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000379}
380
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000381void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
George Karpenkov137ca912018-03-31 01:20:06 +0000382 const Decl* D = DR->getDecl();
383 bool InAssignment = LV.inAssignment[DR];
384 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
385 if (!InAssignment)
386 val.liveBindings =
387 LV.BSetFact.add(val.liveBindings, cast<BindingDecl>(D));
388 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
389 if (!InAssignment && !isAlwaysAlive(VD))
390 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
391 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000392}
393
394void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
George Karpenkov137ca912018-03-31 01:20:06 +0000395 for (const auto *DI : DS->decls()) {
396 if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
397 for (const auto *BD : DD->bindings())
398 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
399 } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000400 if (!isAlwaysAlive(VD))
401 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000402 }
George Karpenkov137ca912018-03-31 01:20:06 +0000403 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000404}
Mike Stump11289f42009-09-09 15:08:12 +0000405
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000406void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
407 // Kill the iteration variable.
Craig Topper25542942014-05-20 04:30:07 +0000408 DeclRefExpr *DR = nullptr;
409 const VarDecl *VD = nullptr;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000410
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000411 Stmt *element = OS->getElement();
412 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
413 VD = cast<VarDecl>(DS->getSingleDecl());
414 }
415 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
416 VD = cast<VarDecl>(DR->getDecl());
417 }
418
419 if (VD) {
420 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
421 if (observer && DR)
422 observer->observerKill(DR);
423 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000424}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000425
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000426void TransferFunctions::
427VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
428{
429 // While sizeof(var) doesn't technically extend the liveness of 'var', it
430 // does extent the liveness of metadata if 'var' is a VariableArrayType.
431 // We handle that special case here.
432 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
433 return;
434
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000435 const Expr *subEx = UE->getArgumentExpr();
436 if (subEx->getType()->isVariableArrayType()) {
437 assert(subEx->isLValue());
438 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
439 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000440}
441
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000442void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
443 // Treat ++/-- as a kill.
444 // Note we don't actually have to do anything if we don't have an observer,
445 // since a ++/-- acts as both a kill and a "use".
446 if (!observer)
447 return;
448
449 switch (UO->getOpcode()) {
450 default:
451 return;
452 case UO_PostInc:
453 case UO_PostDec:
454 case UO_PreInc:
455 case UO_PreDec:
456 break;
457 }
George Karpenkov137ca912018-03-31 01:20:06 +0000458
459 if (auto *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
460 const Decl *D = DR->getDecl();
461 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000462 // Treat ++/-- as a kill.
463 observer->observerKill(DR);
464 }
George Karpenkov137ca912018-03-31 01:20:06 +0000465 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000466}
467
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000468LiveVariables::LivenessValues
469LiveVariablesImpl::runOnBlock(const CFGBlock *block,
470 LiveVariables::LivenessValues val,
471 LiveVariables::Observer *obs) {
472
473 TransferFunctions TF(*this, val, obs, block);
474
475 // Visit the terminator (if any).
476 if (const Stmt *term = block->getTerminator())
477 TF.Visit(const_cast<Stmt*>(term));
478
479 // Apply the transfer function for all Stmts in the block.
480 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
481 ei = block->rend(); it != ei; ++it) {
482 const CFGElement &elem = *it;
Jordan Roseb3244562012-07-26 20:04:08 +0000483
David Blaikie00be69a2013-02-23 00:29:34 +0000484 if (Optional<CFGAutomaticObjDtor> Dtor =
485 elem.getAs<CFGAutomaticObjDtor>()) {
486 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Roseb3244562012-07-26 20:04:08 +0000487 continue;
488 }
489
David Blaikie2a01f5d2013-02-21 20:58:29 +0000490 if (!elem.getAs<CFGStmt>())
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000491 continue;
492
David Blaikie2a01f5d2013-02-21 20:58:29 +0000493 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000494 TF.Visit(const_cast<Stmt*>(S));
495 stmtsToLiveness[S] = val;
496 }
497 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000498}
499
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000500void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
501 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
502 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
503 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000504}
505
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000506LiveVariables::LiveVariables(void *im) : impl(im) {}
507
508LiveVariables::~LiveVariables() {
509 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000510}
511
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000512LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000513LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000514 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000515
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000516 // No CFG? Bail out.
517 CFG *cfg = AC.getCFG();
518 if (!cfg)
Craig Topper25542942014-05-20 04:30:07 +0000519 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000520
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000521 // The analysis currently has scalability issues for very large CFGs.
522 // Bail out if it looks too large.
523 if (cfg->getNumBlockIDs() > 300000)
Craig Topper25542942014-05-20 04:30:07 +0000524 return nullptr;
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000525
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000526 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
527
Artyom Skrobov27720762014-09-23 08:34:41 +0000528 // Construct the dataflow worklist. Enqueue the exit block as the
529 // start of the analysis.
530 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000531 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
532
Artyom Skrobov27720762014-09-23 08:34:41 +0000533 // FIXME: we should enqueue using post order.
534 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
535 const CFGBlock *block = *it;
536 worklist.enqueueBlock(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000537
538 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
539 // We need to do this because we lack context in the reverse analysis
540 // to determine if a DeclRefExpr appears in such a context, and thus
541 // doesn't constitute a "use".
Artyom Skrobov27720762014-09-23 08:34:41 +0000542 if (killAtAssign)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000543 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
544 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000545 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
George Karpenkov137ca912018-03-31 01:20:06 +0000546 const Stmt* stmt = cs->getStmt();
547 if (const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000548 if (BO->getOpcode() == BO_Assign) {
George Karpenkov137ca912018-03-31 01:20:06 +0000549 if (const auto *DR =
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000550 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
551 LV->inAssignment[DR] = 1;
552 }
553 }
554 }
555 }
556 }
Artyom Skrobov27720762014-09-23 08:34:41 +0000557 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000558
Artyom Skrobov27720762014-09-23 08:34:41 +0000559 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000560 // Determine if the block's end value has changed. If not, we
561 // have nothing left to do for this block.
562 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
563
564 // Merge the values of all successor blocks.
565 LivenessValues val;
566 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
567 ei = block->succ_end(); it != ei; ++it) {
Ted Kremenek459597a2011-09-16 23:01:39 +0000568 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000569 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000570 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000571 }
572
573 if (!everAnalyzedBlock[block->getBlockID()])
574 everAnalyzedBlock[block->getBlockID()] = true;
575 else if (prevVal.equals(val))
576 continue;
577
578 prevVal = val;
579
580 // Update the dataflow value for the start of this block.
581 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
582
583 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000584 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000585 }
586
587 return new LiveVariables(LV);
588}
589
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000590void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
591 getImpl(impl).dumpBlockLiveness(M);
592}
593
594void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
595 std::vector<const CFGBlock *> vec;
596 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
597 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
598 it != ei; ++it) {
599 vec.push_back(it->first);
600 }
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000601 llvm::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000602 return A->getBlockID() < B->getBlockID();
603 });
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000604
605 std::vector<const VarDecl*> declVec;
606
607 for (std::vector<const CFGBlock *>::iterator
608 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
609 llvm::errs() << "\n[ B" << (*it)->getBlockID()
610 << " (live variables at block exit) ]\n";
611
612 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
613 declVec.clear();
614
615 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
616 vals.liveDecls.begin(),
617 se = vals.liveDecls.end(); si != se; ++si) {
618 declVec.push_back(*si);
619 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000620
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000621 llvm::sort(declVec.begin(), declVec.end(),
622 [](const Decl *A, const Decl *B) {
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000623 return A->getLocStart() < B->getLocStart();
624 });
625
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000626 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
627 de = declVec.end(); di != de; ++di) {
628 llvm::errs() << " " << (*di)->getDeclName().getAsString()
629 << " <";
630 (*di)->getLocation().dump(M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000631 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000632 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000633 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000634 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000635}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000636
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000637const void *LiveVariables::getTag() { static int x; return &x; }
638const void *RelaxedLiveVariables::getTag() { static int x; return &x; }