blob: e435ff2ee170c14d558061cf0f9f8f66aa863388 [file] [log] [blame]
Benjamin Kramer444a1302012-12-01 17:12:56 +00001//=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Benjamin Kramer444a1302012-12-01 17:12:56 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements Live Variables analysis for source-level CFGs.
10//
11//===----------------------------------------------------------------------===//
12
Ted Kremenekbf593f82007-12-21 21:42:19 +000013#include "clang/Analysis/Analyses/LiveVariables.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000014#include "clang/AST/Stmt.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000015#include "clang/AST/StmtVisitor.h"
Artyom Skrobov27720762014-09-23 08:34:41 +000016#include "clang/Analysis/Analyses/PostOrderCFGView.h"
George Karpenkov50657f62017-09-06 21:45:03 +000017#include "clang/Analysis/AnalysisDeclContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Analysis/CFG.h"
Ted Kremenek459597a2011-09-16 23:01:39 +000019#include "llvm/ADT/DenseMap.h"
Artyom Skrobov27720762014-09-23 08:34:41 +000020#include "llvm/ADT/PostOrderIterator.h"
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000021#include "llvm/ADT/PriorityQueue.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000022#include "llvm/Support/raw_ostream.h"
Ted Kremeneke9fda1e2011-07-28 23:07:59 +000023#include <algorithm>
24#include <vector>
Ted Kremenekb56a9902007-09-06 00:17:54 +000025
26using namespace clang;
27
Ted Kremenekb56a9902007-09-06 00:17:54 +000028namespace {
Artyom Skrobov27720762014-09-23 08:34:41 +000029
30class DataflowWorklist {
Artyom Skrobov27720762014-09-23 08:34:41 +000031 llvm::BitVector enqueuedBlocks;
32 PostOrderCFGView *POV;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000033 llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
34 PostOrderCFGView::BlockOrderCompare> worklist;
35
Artyom Skrobov27720762014-09-23 08:34:41 +000036public:
37 DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
38 : enqueuedBlocks(cfg.getNumBlockIDs()),
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000039 POV(Ctx.getAnalysis<PostOrderCFGView>()),
40 worklist(POV->getComparator()) {}
Fangrui Song6907ce22018-07-30 19:24:48 +000041
Artyom Skrobov27720762014-09-23 08:34:41 +000042 void enqueueBlock(const CFGBlock *block);
43 void enqueuePredecessors(const CFGBlock *block);
44
45 const CFGBlock *dequeue();
Artyom Skrobov27720762014-09-23 08:34:41 +000046};
47
Alexander Kornienkoab9db512015-06-22 23:07:51 +000048}
Artyom Skrobov27720762014-09-23 08:34:41 +000049
50void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
51 if (block && !enqueuedBlocks[block->getBlockID()]) {
52 enqueuedBlocks[block->getBlockID()] = true;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000053 worklist.push(block);
Artyom Skrobov27720762014-09-23 08:34:41 +000054 }
55}
56
57void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
Artyom Skrobov27720762014-09-23 08:34:41 +000058 for (CFGBlock::const_pred_iterator I = block->pred_begin(),
59 E = block->pred_end(); I != E; ++I) {
60 enqueueBlock(*I);
61 }
Artyom Skrobov27720762014-09-23 08:34:41 +000062}
63
64const CFGBlock *DataflowWorklist::dequeue() {
65 if (worklist.empty())
66 return nullptr;
Alexander Shaposhnikovfd905fc2016-10-13 21:31:46 +000067 const CFGBlock *b = worklist.top();
68 worklist.pop();
Artyom Skrobov27720762014-09-23 08:34:41 +000069 enqueuedBlocks[b->getBlockID()] = false;
70 return b;
71}
72
73namespace {
Ted Kremenek459597a2011-09-16 23:01:39 +000074class LiveVariablesImpl {
Fangrui Song6907ce22018-07-30 19:24:48 +000075public:
Ted Kremenek81ce1c82011-10-24 01:32:45 +000076 AnalysisDeclContext &analysisContext;
Ted Kremenek459597a2011-09-16 23:01:39 +000077 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
78 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
George Karpenkov137ca912018-03-31 01:20:06 +000079 llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
Ted Kremenek459597a2011-09-16 23:01:39 +000080 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;
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Ted Kremenek459597a2011-09-16 23:01:39 +000086 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);
Artem Dergachevdda42162018-12-16 23:44:06 +000095 void dumpStmtLiveness(const SourceManager& M);
Ted Kremenek459597a2011-09-16 23:01:39 +000096
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;
Fangrui Song6907ce22018-07-30 19:24:48 +0000133
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,
Fangrui Song6907ce22018-07-30 19:24:48 +0000145 LiveVariables::LivenessValues valsB) {
146
Ted Kremenek459597a2011-09-16 23:01:39 +0000147 llvm::ImmutableSetRef<const Stmt *>
148 SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
149 SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
151
Ted Kremenek459597a2011-09-16 23:01:39 +0000152 llvm::ImmutableSetRef<const VarDecl *>
153 DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
154 DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
Fangrui Song6907ce22018-07-30 19:24:48 +0000155
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);
Fangrui Song6907ce22018-07-30 19:24:48 +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(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000168 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);
Fangrui Song6907ce22018-07-30 19:24:48 +0000214 void VisitDeclRefExpr(DeclRefExpr *DR);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000215 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;
Fangrui Song6907ce22018-07-30 19:24:48 +0000229
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000230 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))
Fangrui Song6907ce22018-07-30 19:24:48 +0000239 S = Ex->IgnoreParens();
Bill Wendling7c44da22018-10-31 03:48:47 +0000240 if (const FullExpr *FE = dyn_cast<FullExpr>(S)) {
241 S = FE->getSubExpr();
John McCall29928fc2011-11-09 17:10:36 +0000242 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);
Fangrui Song6907ce22018-07-30 19:24:48 +0000262
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000263 StmtVisitor<TransferFunctions>::Visit(S);
Fangrui Song6907ce22018-07-30 19:24:48 +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.
Fangrui Song6907ce22018-07-30 19:24:48 +0000270
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000271 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 }
Artem Dergachevdda42162018-12-16 23:44:06 +0000330 case Stmt::IfStmtClass: {
331 // If one of the branches is an expression rather than a compound
332 // statement, it will be bad if we mark it as live at the terminator
333 // of the if-statement (i.e., immediately after the condition expression).
334 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<IfStmt>(S)->getCond());
335 return;
336 }
337 case Stmt::WhileStmtClass: {
338 // If the loop body is an expression rather than a compound statement,
339 // it will be bad if we mark it as live at the terminator of the loop
340 // (i.e., immediately after the condition expression).
341 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<WhileStmt>(S)->getCond());
342 return;
343 }
344 case Stmt::DoStmtClass: {
345 // If the loop body is an expression rather than a compound statement,
346 // it will be bad if we mark it as live at the terminator of the loop
347 // (i.e., immediately after the condition expression).
348 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<DoStmt>(S)->getCond());
349 return;
350 }
351 case Stmt::ForStmtClass: {
352 // If the loop body is an expression rather than a compound statement,
353 // it will be bad if we mark it as live at the terminator of the loop
354 // (i.e., immediately after the condition expression).
355 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<ForStmt>(S)->getCond());
356 return;
357 }
358
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000359 }
Benjamin Kramer973431b2015-07-03 15:12:24 +0000360
361 for (Stmt *Child : S->children()) {
362 if (Child)
363 AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
Ted Kremenek0f5e6f882009-11-26 02:31:33 +0000364 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000365}
Mike Stump11289f42009-09-09 15:08:12 +0000366
George Karpenkov137ca912018-03-31 01:20:06 +0000367static bool writeShouldKill(const VarDecl *VD) {
368 return VD && !VD->getType()->isReferenceType() &&
369 !isAlwaysAlive(VD);
370}
371
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000372void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
373 if (B->isAssignmentOp()) {
374 if (!LV.killAtAssign)
Ted Kremenekfc419a02008-11-14 21:07:14 +0000375 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000376
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000377 // Assigning to a variable?
378 Expr *LHS = B->getLHS()->IgnoreParens();
Ted Kremenek3b4e1d52008-11-11 19:40:47 +0000379
George Karpenkov137ca912018-03-31 01:20:06 +0000380 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
381 const Decl* D = DR->getDecl();
382 bool Killed = false;
383
384 if (const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
385 Killed = !BD->getType()->isReferenceType();
386 if (Killed)
387 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
388 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
389 Killed = writeShouldKill(VD);
390 if (Killed)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000391 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenekfbd2f402008-11-11 17:42:10 +0000392
Ted Kremenek20c91422008-02-22 00:34:10 +0000393 }
George Karpenkov137ca912018-03-31 01:20:06 +0000394
395 if (Killed && observer)
396 observer->observerKill(DR);
397 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000398 }
399}
Mike Stump11289f42009-09-09 15:08:12 +0000400
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000401void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +0000402 for (const VarDecl *VD :
403 LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000404 if (isAlwaysAlive(VD))
405 continue;
406 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
Ted Kremenekb56a9902007-09-06 00:17:54 +0000407 }
Ted Kremenekb56a9902007-09-06 00:17:54 +0000408}
409
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000410void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
George Karpenkov137ca912018-03-31 01:20:06 +0000411 const Decl* D = DR->getDecl();
412 bool InAssignment = LV.inAssignment[DR];
George Karpenkovdbddadd2018-04-06 19:14:05 +0000413 if (const auto *BD = dyn_cast<BindingDecl>(D)) {
George Karpenkov137ca912018-03-31 01:20:06 +0000414 if (!InAssignment)
Andrea Di Biagiod3144ea2018-04-02 12:04:37 +0000415 val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
George Karpenkov137ca912018-03-31 01:20:06 +0000416 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
417 if (!InAssignment && !isAlwaysAlive(VD))
418 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
419 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000420}
421
422void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
George Karpenkov137ca912018-03-31 01:20:06 +0000423 for (const auto *DI : DS->decls()) {
424 if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
425 for (const auto *BD : DD->bindings())
426 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
427 } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000428 if (!isAlwaysAlive(VD))
429 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
Ted Kremenek7845b262008-02-25 22:28:54 +0000430 }
George Karpenkov137ca912018-03-31 01:20:06 +0000431 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000432}
Mike Stump11289f42009-09-09 15:08:12 +0000433
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000434void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
435 // Kill the iteration variable.
Craig Topper25542942014-05-20 04:30:07 +0000436 DeclRefExpr *DR = nullptr;
437 const VarDecl *VD = nullptr;
Ted Kremenekb56a9902007-09-06 00:17:54 +0000438
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000439 Stmt *element = OS->getElement();
440 if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
441 VD = cast<VarDecl>(DS->getSingleDecl());
442 }
443 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
444 VD = cast<VarDecl>(DR->getDecl());
445 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000446
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000447 if (VD) {
448 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
449 if (observer && DR)
450 observer->observerKill(DR);
451 }
Ted Kremenekad8bce02007-09-25 04:31:27 +0000452}
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000453
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000454void TransferFunctions::
455VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
456{
457 // While sizeof(var) doesn't technically extend the liveness of 'var', it
458 // does extent the liveness of metadata if 'var' is a VariableArrayType.
459 // We handle that special case here.
460 if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
461 return;
462
Ted Kremenek84a1ca52011-08-06 00:30:00 +0000463 const Expr *subEx = UE->getArgumentExpr();
464 if (subEx->getType()->isVariableArrayType()) {
465 assert(subEx->isLValue());
466 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
467 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000468}
469
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000470void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
471 // Treat ++/-- as a kill.
472 // Note we don't actually have to do anything if we don't have an observer,
473 // since a ++/-- acts as both a kill and a "use".
474 if (!observer)
475 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000476
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000477 switch (UO->getOpcode()) {
478 default:
479 return;
480 case UO_PostInc:
Fangrui Song6907ce22018-07-30 19:24:48 +0000481 case UO_PostDec:
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000482 case UO_PreInc:
483 case UO_PreDec:
484 break;
485 }
George Karpenkov137ca912018-03-31 01:20:06 +0000486
487 if (auto *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
488 const Decl *D = DR->getDecl();
489 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000490 // Treat ++/-- as a kill.
491 observer->observerKill(DR);
492 }
George Karpenkov137ca912018-03-31 01:20:06 +0000493 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000494}
495
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000496LiveVariables::LivenessValues
497LiveVariablesImpl::runOnBlock(const CFGBlock *block,
498 LiveVariables::LivenessValues val,
499 LiveVariables::Observer *obs) {
500
501 TransferFunctions TF(*this, val, obs, block);
Fangrui Song6907ce22018-07-30 19:24:48 +0000502
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000503 // Visit the terminator (if any).
504 if (const Stmt *term = block->getTerminator())
505 TF.Visit(const_cast<Stmt*>(term));
Fangrui Song6907ce22018-07-30 19:24:48 +0000506
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000507 // Apply the transfer function for all Stmts in the block.
508 for (CFGBlock::const_reverse_iterator it = block->rbegin(),
509 ei = block->rend(); it != ei; ++it) {
510 const CFGElement &elem = *it;
Jordan Roseb3244562012-07-26 20:04:08 +0000511
David Blaikie00be69a2013-02-23 00:29:34 +0000512 if (Optional<CFGAutomaticObjDtor> Dtor =
513 elem.getAs<CFGAutomaticObjDtor>()) {
514 val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
Jordan Roseb3244562012-07-26 20:04:08 +0000515 continue;
516 }
517
David Blaikie2a01f5d2013-02-21 20:58:29 +0000518 if (!elem.getAs<CFGStmt>())
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000519 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000520
David Blaikie2a01f5d2013-02-21 20:58:29 +0000521 const Stmt *S = elem.castAs<CFGStmt>().getStmt();
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000522 TF.Visit(const_cast<Stmt*>(S));
523 stmtsToLiveness[S] = val;
524 }
525 return val;
Ted Kremenek6dc7b112007-09-06 23:00:42 +0000526}
527
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000528void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
529 const CFG *cfg = getImpl(impl).analysisContext.getCFG();
530 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
Fangrui Song6907ce22018-07-30 19:24:48 +0000531 getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
Ted Kremenek85be7cf2008-01-17 20:48:37 +0000532}
533
Fangrui Song6907ce22018-07-30 19:24:48 +0000534LiveVariables::LiveVariables(void *im) : impl(im) {}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000535
536LiveVariables::~LiveVariables() {
537 delete (LiveVariablesImpl*) impl;
Ted Kremenek05ecfdd2008-01-18 00:40:21 +0000538}
539
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000540LiveVariables *
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000541LiveVariables::computeLiveness(AnalysisDeclContext &AC,
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000542 bool killAtAssign) {
Ted Kremenekb56a9902007-09-06 00:17:54 +0000543
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000544 // No CFG? Bail out.
545 CFG *cfg = AC.getCFG();
546 if (!cfg)
Craig Topper25542942014-05-20 04:30:07 +0000547 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000548
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000549 // The analysis currently has scalability issues for very large CFGs.
550 // Bail out if it looks too large.
551 if (cfg->getNumBlockIDs() > 300000)
Craig Topper25542942014-05-20 04:30:07 +0000552 return nullptr;
Ted Kremenekde21a1c2012-07-02 20:21:52 +0000553
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000554 LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
555
Artyom Skrobov27720762014-09-23 08:34:41 +0000556 // Construct the dataflow worklist. Enqueue the exit block as the
557 // start of the analysis.
558 DataflowWorklist worklist(*cfg, AC);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000559 llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
560
Artyom Skrobov27720762014-09-23 08:34:41 +0000561 // FIXME: we should enqueue using post order.
562 for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
563 const CFGBlock *block = *it;
564 worklist.enqueueBlock(block);
Fangrui Song6907ce22018-07-30 19:24:48 +0000565
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000566 // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
567 // We need to do this because we lack context in the reverse analysis
568 // to determine if a DeclRefExpr appears in such a context, and thus
569 // doesn't constitute a "use".
Artyom Skrobov27720762014-09-23 08:34:41 +0000570 if (killAtAssign)
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000571 for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
572 bi != be; ++bi) {
David Blaikie00be69a2013-02-23 00:29:34 +0000573 if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
George Karpenkov137ca912018-03-31 01:20:06 +0000574 const Stmt* stmt = cs->getStmt();
575 if (const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000576 if (BO->getOpcode() == BO_Assign) {
George Karpenkov137ca912018-03-31 01:20:06 +0000577 if (const auto *DR =
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000578 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
579 LV->inAssignment[DR] = 1;
580 }
581 }
582 }
583 }
584 }
Artyom Skrobov27720762014-09-23 08:34:41 +0000585 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000586
Artyom Skrobov27720762014-09-23 08:34:41 +0000587 while (const CFGBlock *block = worklist.dequeue()) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000588 // Determine if the block's end value has changed. If not, we
589 // have nothing left to do for this block.
590 LivenessValues &prevVal = LV->blocksEndToLiveness[block];
Fangrui Song6907ce22018-07-30 19:24:48 +0000591
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000592 // Merge the values of all successor blocks.
593 LivenessValues val;
594 for (CFGBlock::const_succ_iterator it = block->succ_begin(),
595 ei = block->succ_end(); it != ei; ++it) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000596 if (const CFGBlock *succ = *it) {
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000597 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
Ted Kremenek459597a2011-09-16 23:01:39 +0000598 }
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000599 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000600
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000601 if (!everAnalyzedBlock[block->getBlockID()])
602 everAnalyzedBlock[block->getBlockID()] = true;
603 else if (prevVal.equals(val))
604 continue;
605
606 prevVal = val;
Fangrui Song6907ce22018-07-30 19:24:48 +0000607
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000608 // Update the dataflow value for the start of this block.
609 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
Fangrui Song6907ce22018-07-30 19:24:48 +0000610
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000611 // Enqueue the value to the predecessors.
Ted Kremenek459597a2011-09-16 23:01:39 +0000612 worklist.enqueuePredecessors(block);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000613 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000615 return new LiveVariables(LV);
616}
617
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000618void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
619 getImpl(impl).dumpBlockLiveness(M);
620}
621
622void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
623 std::vector<const CFGBlock *> vec;
624 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
625 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
626 it != ei; ++it) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000627 vec.push_back(it->first);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000628 }
Fangrui Song55fab262018-09-26 22:16:28 +0000629 llvm::sort(vec, [](const CFGBlock *A, const CFGBlock *B) {
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000630 return A->getBlockID() < B->getBlockID();
631 });
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000632
633 std::vector<const VarDecl*> declVec;
634
635 for (std::vector<const CFGBlock *>::iterator
636 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
637 llvm::errs() << "\n[ B" << (*it)->getBlockID()
638 << " (live variables at block exit) ]\n";
Fangrui Song6907ce22018-07-30 19:24:48 +0000639
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000640 LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
641 declVec.clear();
Fangrui Song6907ce22018-07-30 19:24:48 +0000642
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000643 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
644 vals.liveDecls.begin(),
645 se = vals.liveDecls.end(); si != se; ++si) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000646 declVec.push_back(*si);
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000647 }
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000648
Fangrui Song55fab262018-09-26 22:16:28 +0000649 llvm::sort(declVec, [](const Decl *A, const Decl *B) {
650 return A->getBeginLoc() < B->getBeginLoc();
651 });
Benjamin Kramer15ae7832014-03-07 21:35:40 +0000652
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000653 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
654 de = declVec.end(); di != de; ++di) {
655 llvm::errs() << " " << (*di)->getDeclName().getAsString()
656 << " <";
Stephen Kelly3124ce72018-08-15 20:32:06 +0000657 (*di)->getLocation().print(llvm::errs(), M);
Daniel Dunbare81a5532009-10-17 18:12:37 +0000658 llvm::errs() << ">\n";
Ted Kremenekb56a9902007-09-06 00:17:54 +0000659 }
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000660 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000661 llvm::errs() << "\n";
Ted Kremenekbd9cc5c2007-09-10 17:36:42 +0000662}
Ted Kremeneke9fda1e2011-07-28 23:07:59 +0000663
Artem Dergachevdda42162018-12-16 23:44:06 +0000664void LiveVariables::dumpStmtLiveness(const SourceManager &M) {
665 getImpl(impl).dumpStmtLiveness(M);
666}
667
668void LiveVariablesImpl::dumpStmtLiveness(const SourceManager &M) {
669 // Don't iterate over blockEndsToLiveness directly because it's not sorted.
670 for (auto I : *analysisContext.getCFG()) {
671
672 llvm::errs() << "\n[ B" << I->getBlockID()
673 << " (live statements at block exit) ]\n";
674 for (auto S : blocksEndToLiveness[I].liveStmts) {
675 llvm::errs() << "\n";
676 S->dump();
677 }
678 llvm::errs() << "\n";
679 }
680}
681
Ted Kremenekdccc2b22011-10-07 22:21:02 +0000682const void *LiveVariables::getTag() { static int x; return &x; }
683const void *RelaxedLiveVariables::getTag() { static int x; return &x; }